text:
using System;
using System.Collections.Generic;
using System.Linq;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.Core.Enums;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Collections;
using Microsoft.SharePoint.Client.Publishing.Navigation;
using Microsoft.SharePoint.Client.Taxonomy;

namespace Microsoft.SharePoint.Client
{

    /// <summary>
    /// This class holds navigation related methods
    /// </summary>
    public static partial class NavigationExtensions
    {

        #region Area Navigation (publishing sites)
        const string PublishingFeatureActivated = "__PublishingFeatureActivated";
        const string WebNavigationSettings = "_webnavigationsettings";
        const string CurrentNavigationIncludeTypes = "__CurrentNavigationIncludeTypes";
        const string CurrentDynamicChildLimit = "__CurrentDynamicChildLimit";
        const string GlobalNavigationIncludeTypes = "__GlobalNavigationIncludeTypes";
        const string GlobalDynamicChildLimit = "__GlobalDynamicChildLimit";
        const string NavigationOrderingMethod = "__NavigationOrderingMethod";
        const string NavigationAutomaticSortingMethod = "__NavigationAutomaticSortingMethod";
        const string NavigationSortAscending = "__NavigationSortAscending";
        const string NavigationShowSiblings = "__NavigationShowSiblings";

        /// <summary>
        /// Returns the navigation settings for the selected web
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static AreaNavigationEntity GetNavigationSettings(this Web web)
        {
            AreaNavigationEntity nav = new AreaNavigationEntity();

            //Read all the properties of the web
            web.Context.Load(web, w => w.AllProperties);
            web.Context.ExecuteQueryRetry();

            if (!ArePublishingFeaturesActivated(web.AllProperties))
            {
                throw new ArgumentException("Structural navigation settings are only supported for publishing sites");
            }

            // Determine if managed navigation is used...if so the other properties are not relevant
            string webNavigationSettings = web.AllProperties.GetPropertyAsString(WebNavigationSettings);
            if (webNavigationSettings == null)
            {
                nav.CurrentNavigation.ManagedNavigation = false;
                nav.GlobalNavigation.ManagedNavigation = false;
            }
            else
            {
                var navigationSettings = XElement.Parse(webNavigationSettings);
                IEnumerable<XElement> navNodes = navigationSettings.XPathSelectElements("./SiteMapProviderSettings/TaxonomySiteMapProviderSettings");
                foreach (var node in navNodes)
                {
                    if (node.Attribute("Name").Value.Equals("CurrentNavigationTaxonomyProvider", StringComparison.InvariantCulture))
                    {
                        bool managedNavigation = true;
                        if (node.Attribute("Disabled") != null)
                        {
                            if (bool.TryParse(node.Attribute("Disabled").Value, out managedNavigation))
                            {
                                managedNavigation = false;
                            }
                        }
                        nav.CurrentNavigation.ManagedNavigation = managedNavigation;
                    }
                    else if (node.Attribute("Name").Value.Equals("GlobalNavigationTaxonomyProvider", StringComparison.InvariantCulture))
                    {
                        bool managedNavigation = true;
                        if (node.Attribute("Disabled") != null)
                        {
                            if (bool.TryParse(node.Attribute("Disabled").Value, out managedNavigation))
                            {
                                managedNavigation = false;
                            }
                        }
                        nav.GlobalNavigation.ManagedNavigation = managedNavigation;
                    }
                }
            }

            // Only read the other values that make sense when not using managed navigation
            if (!nav.CurrentNavigation.ManagedNavigation)
            {
                int currentNavigationIncludeTypes = web.AllProperties.GetPropertyAsInt(CurrentNavigationIncludeTypes);
                if (currentNavigationIncludeTypes > -1)
                {
                    MapFromNavigationIncludeTypes(nav.CurrentNavigation, currentNavigationIncludeTypes);
                }

                int currentDynamicChildLimit = web.AllProperties.GetPropertyAsInt(CurrentDynamicChildLimit);
                if (currentDynamicChildLimit > -1)
                {
                    nav.CurrentNavigation.MaxDynamicItems = currentDynamicChildLimit;
                }

                // For the current navigation there's an option to show the sites siblings in structural navigation
                if (web.IsSubSite())
                {
                    bool showSiblings = false;
                    string navigationShowSiblings = web.AllProperties.GetPropertyAsString(NavigationShowSiblings);
                    if (bool.TryParse(navigationShowSiblings, out showSiblings))
                    {
                        nav.CurrentNavigation.ShowSiblings = showSiblings;
                    }
                }
            }

            if (!nav.GlobalNavigation.ManagedNavigation)
            {
                int globalNavigationIncludeTypes = web.AllProperties.GetPropertyAsInt(GlobalNavigationIncludeTypes);
                if (globalNavigationIncludeTypes > -1)
                {
                    MapFromNavigationIncludeTypes(nav.GlobalNavigation, globalNavigationIncludeTypes);
                }

                int globalDynamicChildLimit = web.AllProperties.GetPropertyAsInt(GlobalDynamicChildLimit);
                if (globalDynamicChildLimit > -1)
                {
                    nav.GlobalNavigation.MaxDynamicItems = globalDynamicChildLimit;
                }
            }

            // Read the sorting value
            int navigationOrderingMethod = web.AllProperties.GetPropertyAsInt(NavigationOrderingMethod);
            if (navigationOrderingMethod > -1)
            {
                nav.Sorting = (StructuralNavigationSorting)navigationOrderingMethod;
            }

            // Read the sort by value
            int navigationAutomaticSortingMethod = web.AllProperties.GetPropertyAsInt(NavigationAutomaticSortingMethod);
            if (navigationAutomaticSortingMethod > -1)
            {
                nav.SortBy = (StructuralNavigationSortBy)navigationAutomaticSortingMethod;
            }

            // Read the ordering setting
            bool navigationSortAscending = true;
            string navProp = web.AllProperties.GetPropertyAsString(NavigationSortAscending);

            if (bool.TryParse(navProp, out navigationSortAscending))
            {
                nav.SortAscending = navigationSortAscending;
            }

            return nav;
        }

        /// <summary>
        /// Updates navigation settings for the current web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="navigationSettings"></param>
        public static void UpdateNavigationSettings(this Web web, AreaNavigationEntity navigationSettings)
        {
            //Read all the properties of the web
            web.Context.Load(web, w => w.AllProperties);
            web.Context.ExecuteQueryRetry();

            if (!ArePublishingFeaturesActivated(web.AllProperties))
            {
                throw new ArgumentException("Structural navigation settings are only supported for publishing sites");
            }

            // Use publishing CSOM API to switch between managed metadata and structural navigation
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context);
            web.Context.Load(taxonomySession);
            web.Context.ExecuteQueryRetry();
            Microsoft.SharePoint.Client.Publishing.Navigation.WebNavigationSettings webNav = new Publishing.Navigation.WebNavigationSettings(web.Context, web);
            if (!navigationSettings.GlobalNavigation.ManagedNavigation)
            {
                webNav.GlobalNavigation.Source = Publishing.Navigation.StandardNavigationSource.PortalProvider;
            }
            else
            {
                webNav.GlobalNavigation.Source = Publishing.Navigation.StandardNavigationSource.TaxonomyProvider;
            }

            if (!navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                webNav.CurrentNavigation.Source = Publishing.Navigation.StandardNavigationSource.PortalProvider;
            }
            else
            {
                webNav.CurrentNavigation.Source = Publishing.Navigation.StandardNavigationSource.TaxonomyProvider;
            }
            webNav.Update(taxonomySession);
            web.Context.ExecuteQueryRetry();

            //Read all the properties of the web again after the above update
            web.Context.Load(web, w => w.AllProperties);
            web.Context.ExecuteQueryRetry();

            if (!navigationSettings.GlobalNavigation.ManagedNavigation)
            {
                int globalNavigationIncludeType = MapToNavigationIncludeTypes(navigationSettings.GlobalNavigation);
                web.AllProperties[GlobalNavigationIncludeTypes] = globalNavigationIncludeType;
                web.AllProperties[GlobalDynamicChildLimit] = navigationSettings.GlobalNavigation.MaxDynamicItems;
            }

            if (!navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                int currentNavigationIncludeType = MapToNavigationIncludeTypes(navigationSettings.CurrentNavigation);
                web.AllProperties[CurrentNavigationIncludeTypes] = currentNavigationIncludeType;
                web.AllProperties[CurrentDynamicChildLimit] = navigationSettings.CurrentNavigation.MaxDynamicItems;

                // Call web.update before the IsSubSite call as this might do an ExecuteQuery. Without the update called the changes will be lost
                web.Update();
                // For the current navigation there's an option to show the sites siblings in structural navigation
                if (web.IsSubSite())
                {
                    web.AllProperties[NavigationShowSiblings] = navigationSettings.CurrentNavigation.ShowSiblings.ToString();
                }
            }

            // if there's either global or current structural navigation then update the sorting settings
            if (!navigationSettings.GlobalNavigation.ManagedNavigation || !navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                // If there's automatic sorting or pages are shown with automatic page sorting then we can set all sort options
                if ((navigationSettings.Sorting == StructuralNavigationSorting.Automatically) ||
                    (navigationSettings.Sorting == StructuralNavigationSorting.ManuallyButPagesAutomatically && (navigationSettings.GlobalNavigation.ShowPages || navigationSettings.CurrentNavigation.ShowPages)))
                {
                    // All sort options can be set
                    web.AllProperties[NavigationOrderingMethod] = (int)navigationSettings.Sorting;
                    web.AllProperties[NavigationAutomaticSortingMethod] = (int)navigationSettings.SortBy;
                    web.AllProperties[NavigationSortAscending] = navigationSettings.SortAscending.ToString();
                }
                else
                {
                    // if pages are not shown we can set sorting to either automatic or manual
                    if (!navigationSettings.GlobalNavigation.ShowPages && !navigationSettings.CurrentNavigation.ShowPages)
                    {
                        if (navigationSettings.Sorting == StructuralNavigationSorting.ManuallyButPagesAutomatically)
                        {
                            throw new ArgumentException("Sorting can only be set to StructuralNavigationSorting.ManuallyButPagesAutomatically when ShowPages has been selected in either the global or current structural navigation settings");
                        }
                    }

                    web.AllProperties[NavigationOrderingMethod] = (int)navigationSettings.Sorting;
                }
            }

            //Persist all property updates at once
            web.Update();
            web.Context.ExecuteQueryRetry();
        }

        private static int MapToNavigationIncludeTypes(StructuralNavigationEntity sne)
        {
            int navigationIncludeType = -1;

            if (!sne.ShowPages && !sne.ShowSubsites)
            {
                navigationIncludeType = 0;
            }
            else if (!sne.ShowPages && sne.ShowSubsites)
            {
                navigationIncludeType = 1;
            }
            else if (sne.ShowPages && !sne.ShowSubsites)
            {
                navigationIncludeType = 2;
            }
            else if (sne.ShowPages && sne.ShowSubsites)
            {
                navigationIncludeType = 3;
            }

            return navigationIncludeType;
        }

        private static void MapFromNavigationIncludeTypes(StructuralNavigationEntity sne, int navigationIncludeTypes)
        {
            if (navigationIncludeTypes == 0)
            {
                sne.ShowPages = false;
                sne.ShowSubsites = false;
            }
            else if (navigationIncludeTypes == 1)
            {
                sne.ShowPages = false;
                sne.ShowSubsites = true;
            }
            else if (navigationIncludeTypes == 2)
            {
                sne.ShowPages = true;
                sne.ShowSubsites = false;
            }
            else if (navigationIncludeTypes == 3)
            {
                sne.ShowPages = true;
                sne.ShowSubsites = true;
            }
        }

        private static bool ArePublishingFeaturesActivated(PropertyValues props)
        {
            bool activated = false;

            if (bool.TryParse(props.GetPropertyAsString(PublishingFeatureActivated), out activated))
            {
            }

            return activated;
        }

        private static string GetPropertyAsString(this PropertyValues props, string key)
        {
            if (props.FieldValues.ContainsKey(key))
            {
                return props.FieldValues[key].ToString();
            }
            else
            {
                return null;
            }
        }
        private static int GetPropertyAsInt(this PropertyValues props, string key)
        {
            if (props.FieldValues.ContainsKey(key))
            {
                int res;
                if (int.TryParse(props.FieldValues[key].ToString(), out res))
                {
                    return res;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                return -1;
            }
        }
        #endregion

        #region Managed Navigation (publishing sites)

        /// <summary>
        /// Returns an editable version of the Global Navigation TermSet for a web site
        /// </summary>
        /// <param name="web">The target web.</param>
        /// <param name="navigationKind">Declares whether to look for Current or Global Navigation</param>
        /// <returns>The editable Global Navigation TermSet</returns>
        public static NavigationTermSet GetEditableNavigationTermSet(this Web web, ManagedNavigationKind navigationKind)
        {
            if (!web.IsManagedNavigationEnabled(navigationKind))
            {
                throw new ApplicationException(String.Format("The current web is not using the Taxonomy provider for {0} Navigation.", navigationKind));
            }

            switch (navigationKind)
            {
                case ManagedNavigationKind.Global:
                    return (GetEditableNavigationTermSetByProviderName(web, web.Context,
                        "GlobalNavigationTaxonomyProvider"));
                case ManagedNavigationKind.Current:
                    return (GetEditableNavigationTermSetByProviderName(web, web.Context,
                        "CurrentNavigationTaxonomyProvider"));
                default:
                    return (null);
            }
        }

        /// <summary>
        /// Determines whether the current Web has the managed navigation enabled
        /// </summary>
        /// <param name="web">The target web.</param>
        /// <param name="navigationKind">The kind of navigation (Current or Global).</param>
        /// <returns>A boolean result of the test.</returns>
        public static Boolean IsManagedNavigationEnabled(this Web web, ManagedNavigationKind navigationKind)
        {
            Boolean result = false;
            var navigationSettings = new WebNavigationSettings(web.Context, web);
            web.Context.Load(navigationSettings, ns => ns.CurrentNavigation, ns => ns.GlobalNavigation);
            web.Context.Load(web.ParentWeb, pw => pw.ServerRelativeUrl);
            web.Context.ExecuteQueryRetry();

            StandardNavigationSettings targeNavigationSettings =
                navigationKind == ManagedNavigationKind.Current ?
                navigationSettings.CurrentNavigation : navigationSettings.GlobalNavigation;

            if (targeNavigationSettings.Source == StandardNavigationSource.InheritFromParentWeb &&
                (web.ParentWeb.ServerObjectIsNull.HasValue && !web.ParentWeb.ServerObjectIsNull.Value))
            {
                Uri currentWebUri = new Uri(web.Url);
                Uri parentWebUri = new Uri(String.Format("{0}://{1}{2}", currentWebUri.Scheme, currentWebUri.Host, web.ParentWeb.ServerRelativeUrl));

                using (ClientContext parentContext = web.Context.Clone(parentWebUri))
                {
                    result = IsManagedNavigationEnabled(parentContext.Web, navigationKind);
                }
            }
            else
            {
                result = targeNavigationSettings.Source == StandardNavigationSource.TaxonomyProvider;
            }

            return (result);
        }

        private static NavigationTermSet GetEditableNavigationTermSetByProviderName(
            Web web, ClientRuntimeContext context, String providerName)
        {
            // Get the current taxonomy session and update cache, just in case
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context);
            taxonomySession.UpdateCache();

            context.ExecuteQueryRetry();

            // Retrieve the Navigation TermSet for the current web
            NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web.Context,
                web, providerName, true);
            context.Load(navigationTermSet);
            context.ExecuteQueryRetry();

            // Retrieve an editable TermSet for the current target navigation
            NavigationTermSet editableNavigationTermSet = navigationTermSet.GetAsEditable(taxonomySession);
            context.Load(editableNavigationTermSet);
            context.ExecuteQueryRetry();

            return (editableNavigationTermSet);
        }

        #endregion

        #region Navigation elements - quicklaunch, top navigation, search navigation
        /// <summary>
        /// Add a node to quick launch, top navigation bar or search navigation. The node will be added as the last node in the
        /// collection.
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="nodeTitle">the title of node to add</param>
        /// <param name="nodeUri">the url of node to add</param>
        /// <param name="parentNodeTitle">if string.Empty, then will add this node as top level node</param>
        /// <param name="navigationType">the type of navigation, quick launch, top navigation or search navigation</param>
        /// <param name="isExternal">true if the link is an external link</param>

        public static void AddNavigationNode(this Web web, string nodeTitle, Uri nodeUri, string parentNodeTitle, NavigationType navigationType, bool isExternal = false)
        {
            web.Context.Load(web, w => w.Navigation.QuickLaunch, w => w.Navigation.TopNavigationBar);
            web.Context.ExecuteQueryRetry();
            NavigationNodeCreationInformation node = new NavigationNodeCreationInformation
            {
                AsLastNode = true,
                Title = nodeTitle,
                Url = nodeUri != null ? nodeUri.OriginalString : string.Empty,
                IsExternal = isExternal
            };

            try
            {
                if (navigationType == NavigationType.QuickLaunch)
                {
                    var quickLaunch = web.Navigation.QuickLaunch;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        quickLaunch.Add(node);
                        return;
                    }
                    NavigationNode parentNode = quickLaunch.SingleOrDefault(n => n.Title == parentNodeTitle);
                    if (parentNode != null)
                    {
                        parentNode.Children.Add(node);
                    }
                }
                else if (navigationType == NavigationType.TopNavigationBar)
                {
                    var topLink = web.Navigation.TopNavigationBar;
                    if (!string.IsNullOrEmpty(parentNodeTitle))
                    {
                        var parentNode = topLink.FirstOrDefault(n => n.Title == parentNodeTitle);
                        if (parentNode != null)
                        {
                            parentNode.Children.Add(node);
                        }
                    }
                    else
                    {
                        topLink.Add(node);
                    }
                }
                else if (navigationType == NavigationType.SearchNav)
                {
                    var searchNavigation = web.LoadSearchNavigation();
                    searchNavigation.Add(node);
                }
            }
            finally
            {
                web.Context.ExecuteQueryRetry();
            }
        }

        /// <summary>
        /// Deletes a navigation node from the quickLaunch or top navigation bar
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="nodeTitle">the title of node to delete</param>
        /// <param name="parentNodeTitle">if string.Empty, then will delete this node as top level node</param>
        /// <param name="navigationType">the type of navigation, quick launch, top navigation or search navigation</param>
        public static void DeleteNavigationNode(this Web web, string nodeTitle, string parentNodeTitle, NavigationType navigationType)
        {
            web.Context.Load(web, w => w.Navigation.QuickLaunch, w => w.Navigation.TopNavigationBar);
            web.Context.ExecuteQueryRetry();
            NavigationNode deleteNode = null;
            try
            {
                if (navigationType == NavigationType.QuickLaunch)
                {
                    var quickLaunch = web.Navigation.QuickLaunch;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        deleteNode = quickLaunch.SingleOrDefault(n => n.Title == nodeTitle);
                    }
                    else
                    {
                        foreach (var nodeInfo in quickLaunch)
                        {
                            if (nodeInfo.Title != parentNodeTitle)
                            {
                                continue;
                            }

                            web.Context.Load(nodeInfo.Children);
                            web.Context.ExecuteQueryRetry();
                            deleteNode = nodeInfo.Children.SingleOrDefault(n => n.Title == nodeTitle);
                        }
                    }
                }
                else if (navigationType == NavigationType.TopNavigationBar)
                {
                    var topLink = web.Navigation.TopNavigationBar;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        deleteNode = topLink.SingleOrDefault(n => n.Title == nodeTitle);
                    }
                    else
                    {
                        foreach (var nodeInfo in topLink)
                        {
                            if (nodeInfo.Title != parentNodeTitle)
                            {
                                continue;
                            }
                            web.Context.Load(nodeInfo.Children);
                            web.Context.ExecuteQueryRetry();
                            deleteNode = nodeInfo.Children.SingleOrDefault(n => n.Title == nodeTitle);
                        }
                    }
                }
                else if (navigationType == NavigationType.SearchNav)
                {
                    NavigationNodeCollection nodeCollection = web.LoadSearchNavigation();
                    deleteNode = nodeCollection.SingleOrDefault(n => n.Title == nodeTitle);
                }
            }
            finally
            {
                if (deleteNode != null)
                {
                    deleteNode.DeleteObject();
                }
                web.Context.ExecuteQueryRetry();
            }
        }

        /// <summary>
        /// Deletes all Navigation Nodes from a given navigation
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="navigationType">The type of navigation to support</param>
        public static void DeleteAllNavigationNodes(this Web web, NavigationType navigationType)
        {
            if (navigationType == NavigationType.QuickLaunch)
            {
                web.Context.Load(web, w => w.Navigation.QuickLaunch);
                web.Context.ExecuteQueryRetry();

                var quickLaunch = web.Navigation.QuickLaunch;
                for (int i = quickLaunch.Count - 1; i >= 0; i--)
                {
                    quickLaunch[i].DeleteObject();
                }
                web.Context.ExecuteQueryRetry();
            }
            else if (navigationType == NavigationType.TopNavigationBar)
            {
                web.Context.Load(web, w => w.Navigation.TopNavigationBar);
                web.Context.ExecuteQueryRetry();
                var topNavigation = web.Navigation.TopNavigationBar;
                for (int i = topNavigation.Count - 1; i >= 0; i--)
                {
                    topNavigation[i].DeleteObject();
                }
                web.Context.ExecuteQueryRetry();
            }
            else if (navigationType == NavigationType.SearchNav)
            {
                var searchNavigation = web.LoadSearchNavigation();
                for (int i = searchNavigation.Count - 1; i >= 0; i--)
                {
                    searchNavigation[i].DeleteObject();
                }
                web.Context.ExecuteQueryRetry();
            }
        }

        /// <summary>
        /// Updates the navigation inheritance setting
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="inheritNavigation">boolean indicating if navigation inheritance is needed or not</param>
        public static void UpdateNavigationInheritance(this Web web, bool inheritNavigation)
        {
            web.Navigation.UseShared = inheritNavigation;
            web.Update();
            web.Context.ExecuteQueryRetry();
        }

        /// <summary>
        /// Loads the search navigation nodes
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <returns>Collection of NavigationNode instances</returns>
        public static NavigationNodeCollection LoadSearchNavigation(this Web web)
        {
            var searchNav = web.Navigation.GetNodeById(1040); // 1040 is the id of the search navigation
            var nodeCollection = searchNav.Children;
            web.Context.Load(searchNav);
            web.Context.Load(nodeCollection);
            web.Context.ExecuteQueryRetry();
            return nodeCollection;
        }
        #endregion

        #region Custom actions
        /// <summary>
        /// Adds custom action to a web. If the CustomAction exists the item will be updated.
        /// Setting CustomActionEntity.Remove == true will delete the CustomAction.
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="customAction">Information about the custom action be added or deleted</param>
        /// <example>
        /// var editAction = new CustomActionEntity()
        /// {
        ///    Title = "Edit Site Classification",
        ///    Description = "Manage business impact information for site collection or sub sites.",
        ///    Sequence = 1000,
        ///    Group = "SiteActions",
        ///    Location = "Microsoft.SharePoint.StandardMenu",
        ///    Url = EditFormUrl,
        ///    ImageUrl = EditFormImageUrl,
        ///    Rights = new BasePermissions(),
        /// };
        /// editAction.Rights.Set(PermissionKind.ManageWeb);
        /// web.AddCustomAction(editAction);
        /// </example>
        /// <returns>True if action was successfull</returns>
        public static bool AddCustomAction(this Web web, CustomActionEntity customAction)
        {
            return AddCustomActionImplementation(web, customAction);
        }

        /// <summary>
        /// Adds custom action to a site collection. If the CustomAction exists the item will be updated.
        /// Setting CustomActionEntity.Remove == true will delete the CustomAction.
        /// </summary>
        /// <param name="site">Site collection to be processed</param>
        /// <param name="customAction">Information about the custom action be added or deleted</param>
        /// <returns>True if action was successfull</returns>
        public static bool AddCustomAction(this Site site, CustomActionEntity customAction)
        {
            return AddCustomActionImplementation(site, customAction);
        }

        private static bool AddCustomActionImplementation(ClientObject clientObject, CustomActionEntity customAction)
        {
            UserCustomAction targetAction;
            UserCustomActionCollection existingActions;
            if (clientObject is Web)
            {
                var web = (Web)clientObject;

                existingActions = web.UserCustomActions;
                web.Context.Load(existingActions);
                web.Context.ExecuteQueryRetry();

                targetAction = web.UserCustomActions.FirstOrDefault(uca => uca.Name == customAction.Name);
            }
            else
            {
                var site = (Site)clientObject;

                existingActions = site.UserCustomActions;
                site.Context.Load(existingActions);
                site.Context.ExecuteQueryRetry();

                targetAction = site.UserCustomActions.FirstOrDefault(uca => uca.Name == customAction.Name);
            }

            if (targetAction == null)
            {
                // If we're removing the custom action then we need to leave when not found...else we're creating the custom action
                if (customAction.Remove)
                {
                    return true;
                }
                targetAction = existingActions.Add();
            }
            else if (customAction.Remove)
            {
                targetAction.DeleteObject();
                clientObject.Context.ExecuteQueryRetry();
                return true;
            }

            targetAction.Name = customAction.Name;
            targetAction.Description = customAction.Description;
            targetAction.Location = customAction.Location;
            targetAction.Sequence = customAction.Sequence;

            if (customAction.Location == JavaScriptExtensions.SCRIPT_LOCATION)
            {
                targetAction.ScriptBlock = customAction.ScriptBlock;
                targetAction.ScriptSrc = customAction.ScriptSrc;
            }
            else
            {
                targetAction.Url = customAction.Url;
                targetAction.Group = customAction.Group;
                targetAction.Title = customAction.Title;
                targetAction.ImageUrl = customAction.ImageUrl;

                if (customAction.RegistrationId != null)
                {
                    targetAction.RegistrationId = customAction.RegistrationId;
                }

                if (!string.IsNullOrEmpty(customAction.CommandUIExtension))
                {
                    targetAction.CommandUIExtension = customAction.CommandUIExtension;
                }

                if (customAction.Rights != null)
                {
                    targetAction.Rights = customAction.Rights;
                }

                if (customAction.RegistrationType.HasValue)
                {
                    targetAction.RegistrationType = customAction.RegistrationType.Value;
                }
            }

            targetAction.Update();
            if (clientObject is Web)
            {
                var web = (Web)clientObject;
                web.Context.Load(web, w => w.UserCustomActions);
                web.Context.ExecuteQueryRetry();
            }
            else
            {
                var site = (Site)clientObject;
                site.Context.Load(site, s => s.UserCustomActions);
                site.Context.ExecuteQueryRetry();
            }

            return true;
        }

        /// <summary>
        /// Returns all custom actions in a web
        /// </summary>
        /// <param name="web">The web to process</param>
        /// <returns></returns>
        public static IEnumerable<UserCustomAction> GetCustomActions(this Web web)
        {
            var clientContext = (ClientContext)web.Context;

            List<UserCustomAction> actions = new List<UserCustomAction>();

            clientContext.Load(web.UserCustomActions);
            clientContext.ExecuteQueryRetry();

            foreach (UserCustomAction uca in web.UserCustomActions)
            {
                actions.Add(uca);
            }
            return actions;
        }

        /// <summary>
        /// Returns all custom actions in a web
        /// </summary>
        /// <param name="site">The site to process</param>
        /// <returns></returns>
        public static IEnumerable<UserCustomAction> GetCustomActions(this Site site)
        {
            var clientContext = (ClientContext)site.Context;

            List<UserCustomAction> actions = new List<UserCustomAction>();

            clientContext.Load(site.UserCustomActions);
            clientContext.ExecuteQueryRetry();

            foreach (UserCustomAction uca in site.UserCustomActions)
            {
                actions.Add(uca);
            }
            return actions;
        }

        /// <summary>
        /// Removes a custom action
        /// </summary>
        /// <param name="web">The web to process</param>
        /// <param name="id">The id of the action to remove. <seealso>
        ///         <cref>GetCustomActions</cref>
        ///     </seealso>
        /// </param>
        public static void DeleteCustomAction(this Web web, Guid id)
        {
            var clientContext = (ClientContext)web.Context;

            clientContext.Load(web.UserCustomActions);
            clientContext.ExecuteQueryRetry();

            foreach (UserCustomAction action in web.UserCustomActions)
            {
                if (action.Id == id)
                {
                    action.DeleteObject();
                    clientContext.ExecuteQueryRetry();
                    break;
                }
            }
        }

        /// <summary>
        /// Removes a custom action
        /// </summary>
        /// <param name="site">The site to process</param>
        /// <param name="id">The id of the action to remove. <seealso>
        ///         <cref>GetCustomActions</cref>
        ///     </seealso>
        /// </param>
        public static void DeleteCustomAction(this Site site, Guid id)
        {
            var clientContext = (ClientContext)site.Context;

            clientContext.Load(site.UserCustomActions);
            clientContext.ExecuteQueryRetry();

            foreach (UserCustomAction action in site.UserCustomActions)
            {
                if (action.Id == id)
                {
                    action.DeleteObject();
                    clientContext.ExecuteQueryRetry();
                    break;
                }
            }
        }

        /// <summary>
        /// Utility method to check particular custom action already exists on the web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="name">Name of the custom action</param>
        /// <returns></returns>
        public static bool CustomActionExists(this Web web, string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            web.Context.Load(web.UserCustomActions);
            web.Context.ExecuteQueryRetry();

            var customActions = web.UserCustomActions.AsEnumerable<UserCustomAction>();
            foreach (var customAction in customActions)
            {
                var customActionName = customAction.Name;
                if (!string.IsNullOrEmpty(customActionName) &&
                    customActionName.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Utility method to check particular custom action already exists on the web
        /// </summary>
        /// <param name="site"></param>
        /// <param name="name">Name of the custom action</param>
        /// <returns></returns>
        public static bool CustomActionExists(this Site site, string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            site.Context.Load(site.UserCustomActions);
            site.Context.ExecuteQueryRetry();

            var customActions = site.UserCustomActions.AsEnumerable<UserCustomAction>();
            foreach (var customAction in customActions)
            {
                var customActionName = customAction.Name;
                if (!string.IsNullOrEmpty(customActionName) &&
                    customActionName.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        #endregion
    }

    /// <summary>
    /// Defines the kind of Managed Navigation for a site
    /// </summary>
    public enum ManagedNavigationKind
    {
        /// <summary>
        /// Current Navigation
        /// </summary>
        Current,
        /// <summary>
        /// Global Navigation
        /// </summary>
        Global,
    }
}


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.0, maximum-scale=1.0, user-scalable=no">

	<title>Gameforest - Responsive Gaming HTML Theme</title>

	<link rel="shortcut icon" href="img/favicon.ico">

	<link href="plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="css/style.css" rel="stylesheet">
	<link href="css/helpers.css" rel="stylesheet">

	<link href="plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet">
	<link href="plugins/ionicons/css/ionicons.min.css" rel="stylesheet">
	<link href="plugins/animate/animate.min.css" rel="stylesheet">
	<link href="plugins/animate/animate.delay.css" rel="stylesheet">

Home

					Games

Platforms

 All Platform

 Playstation 4

 Playstation 3

 Xbox One

 Xbox 360

 Steam

 Computer

									PC

Witcher 3 Limited Version

Nam id velit vitae nisi tempus blandit nec commodo est. Vivamus justo nunc, malesuada eu tellus vel, sollicitudin...

									PS4

Last of Us Remastered

Ullam feugiat, libero pharetra tempor pulvinar, eros purus faucibus augue, vel laoreet lorem elit fermentum...

Genres

Action

Adventure

FPS

Indie

Strategy

RPG

Simulation

					Blog

							 Blog Large

Archive

Sidebar

Single Post

							 Blog Medium

Archive

Sidebar

Single Post

							 Single Post

Blog Image Post

Blog Slideshow Post

Blog Video Post

Blog Music Post

 Masonry Blog

 Thumbnail Blog

						Pages

Default Examples

Games

Game Post

Reviews

Review Post

Videos

Contact

Initial Examples

Login

Register

Timeline

Full Width

Blank Page

404 Error

						Elements

Typography

 General Typography

 Blockquote

 Helper Classes

 Testimonials

 Grid Layouts

 Alert & Messages

 Labels & Badges

 Audio, Videos & Images

 Pagination & Pagers

Button & Icons

 General Buttons

 Social Buttons

 Glyphicons

 FontAwesome icons

 IonIcons

Components

 Media Objects

 Page headers

 Wells

Default Elements

 General Widgets

 Colored Widgets

 Thumbnails

 Accordion & Tabs

 Timeline

 Tables

 Progress Bars

 Panels

Forms & Info

 General Forms

 Form Layouts

 Modals

 Carousel Examples

 Charts & Countdowns

 Google Maps

Videos

Gallery

Contact

					 Nathan Drake

 Profile

 Likes 32

 Games

 Settings

 Sign Out

 You have 5 likes

 Alien Isolation

 Witcher 3 XBOX

 Last of Us

 Uncharted 4 PS4

 GTA 5 PC

View all likes

						<input type="text" class="form-control" placeholder="Type to search...">

			<input type="text" class="form-control" placeholder="Type to search...">

About GameForest

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pharetra mattis arcu, a congue leo malesuada eu. Nam nec mauris ut odio tristique varius et eu metus. Quisque massa purus, aliquet quis blandit et,

mollis sed lorem. Sed vel tincidunt elit. Phasellus at varius odio, sit amet fermentum mauris.

Categories

Playstation 4

XBOX ONE

PC

PS3

Gaming

Portfolio

Videos

Reviews

Email Newsletters

Subscribe to our newsletter and get notification when new games are available.

					<form method="post" class="margin-top-25 btn-inline">
						<input type="text" class="form-control form-inverse input-lg no-border no-shadow padding-right-40" placeholder="Email..." />
						<button type="submit" class="btn btn-link color-white margin-top-5"></button>
					</form>

				© 2015 GAMEFOREST. All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
class EnableCalendarAndGanttModulesWhereAppropriate < ActiveRecord::Migration
  def self.up
    EnabledModule.where(:name => 'issue_tracking').all.each do |e|
      EnabledModule.create(:name => 'calendar', :project_id => e.project_id)
      EnabledModule.create(:name => 'gantt', :project_id => e.project_id)
    end
  end

  def self.down
    EnabledModule.delete_all("name = 'calendar' OR name = 'gantt'")
  end
end


text:
* Updated package information for Debian packaging (andrewrk)

## 0.9.0
* Add automatic retries to session authorisation.
* Deprecated session.authorise() in favour of supplying a token at creation.

## 0.8.4
* Added some user functions to list of signed methods (maxkueng)
* Added some library functions to list of write methods (maxkueng)

## 0.8.3
* Fix issue where undefined mbid in track object would cause scrobble
  to fail. (maxkueng)
* Fix issue where all undefined and null parameters would cause signatures
  to fail.
* Use http.request instead of deprecated http.createClient. (xhochy)
* lastfm-node now requires node v0.4.10 and above.

## 0.8.1
* Automatically set album parameter from track details when available.
* Experimental REPL.

## 0.8.0

### Breaking changes
* Removed old handler options which were deprecated in 0.6.0.

### New features
* Scrobble request which return error codes 11, 16 or 29 are automatically retried.

## 0.7.0

### Breaking changes
* The success event on `lastfm.request` now emits parsed JSON rather than raw text.
* `RecentTracksStream.isStreaming` has been removed in favour of `RecentTracksStream.isStreaming()`.

## 0.6.3

* Fixed bug where success/error handlers on lastfm.info and lastfm.update were being fired twice.
* Configurable user-agent string.
* LastFmUpdate can now accept any parameter. This will be passed through to Last.Fm. This allows artist/track info to be supplied without having to use the track object from RecentTrackStream.

## 0.6.2

Fixed path issue (regression)

## 0.6.1

* Reinstated LastFmSession.authorise() handler options which were accidentallly removed rather than deprecated. Thanks to Vytautas Jakutis for the spot.
* Fixed LastFmSession.authorise() documentation (Vytautas Jakutis)

## 0.6.0

### New features

* Added request() method. Provides low-level support for entire Last.Fm API.
* Event handler options on RecentTrackStream, LastFmUpdate and LastFmInfo have been deprecated and replaced with more generic `handlers` option. These will be removed soon.

## 0.5.1

* More accurate error reporting from RecentTrackParser
* v0.4.x support

## 0.5.0

* Renamed lastfm.readRequest/writeRequest to read/write.
* Replace response reader with LastFmRequest.

## 0.4.4

* Handles response errors (timeouts, etc) when communicating with Last.fm
* Fixed bug where unexpected data in LastFmInfo would crash application.

## 0.4.3

* Fixed bug where RecentTrackStream was working with null tracks.

## 0.4.2

* Added session.isAuthorised()

## 0.4.1

* Added slightly more descriptive errors to RecentTracksParser.

## 0.4.0

### Breaking changes

* `LastFmSession` is no longer responsible for sending update. Use `lastfm.update()`  instead.

    lastfm.update("nowplaying", session, { track: track });

### New Features

* Access getInfo API calls through `lastfm.info()`. See README for example.


text:
using System.IO;

namespace Nez.Persistence.Binary
{
	public class TextPersistableReader : StreamReader, IPersistableReader
	{
		public TextPersistableReader(string filename) : base(File.OpenRead(filename))
		{
		}

		public TextPersistableReader(Stream stream) : base(stream)
		{
		}

		public string ReadString()
		{
			var length = ReadInt();
			var buff = new char[length];
			ReadBlock(buff, 0, length);

			// chomp the newline that is after our string
			ReadLine();

			return new string(buff);
		}

		public bool ReadBool() => bool.Parse(ReadLine());

		public double ReadDouble() => double.Parse(ReadLine());

		public float ReadFloat() => float.Parse(ReadLine());

		public int ReadInt() => int.Parse(ReadLine());

		public uint ReadUInt() => uint.Parse(ReadLine());
	}
}


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

// This file is auto-generated and should not be modified manually.

namespace SpirvNet.Spirv.Ops.DeviceSideEnqueue
{
    /// <summary>
    /// OpEnqueueKernel
    ///
    /// Enqueue the the function specified by Invoke and the NDRange specified by ND Range for execution to the queue object specified by q.
    ///
    /// ND Range must be a OpTypeStruct created by OpBuildNDRange.
    ///
    /// Num Events specifies the number of event objects in the wait list pointed Wait Events and must be 32 bit OpTypeInt treated as unsigned integer.
    ///
    /// Wait Events specifies the list of wait event objects and must be a OpTypePointer to OpTypeDeviceEvent.
    ///
    /// Ret Event is OpTypePointer to OpTypeDeviceEvent which gets implictly retained by this instruction.  must be a OpTypePointer to OpTypeDeviceEvent.
    ///
    /// Invoke must be a OpTypeFunction with the following signature:
    /// - Result Type must be OpTypeVoid.
    /// - The first parameter must be OpTypePointer to 8 bits OpTypeInt.
    /// - Optional list of parameters that must be OpTypePointer with WorkgroupLocal storage class.
    ///
    /// Param is the first parameter of the function specified by Invoke and must be OpTypePointer to 8 bit OpTypeInt.
    ///
    /// Param Size is the size in bytes of the memory pointed by Param and must be a 32 bit OpTypeInt treated as unsigned int.
    ///
    /// Param Align is the alignment of Param.
    ///
    /// Local Size is an optional list of 32 bit OpTypeInt values which are treated as unsigned integers. Every Local Size specifies the size in bytes of the OpTypePointer with WorkgroupLocal of Invoke.  The number of Local Size operands must match the signature of Invoke OpTypeFunction
    ///
    /// Result Type must be a 32 bit OpTypeInt.
    ///
    /// These are the possible return values:
    /// A successfull enqueue is indicated by the integer value 0
    /// A failed enqueue is indicated by the negative integer value -101
    ///
    /// When running the clCompileProgram or clBuildProgram  with -g flag, the following errors may be returned instead of the negative value -101:
    /// - When q is an invalid queue object, the negative integer value -102 is returned.
    /// - When ND Range is an invalid descriptor or if the program was compiled with -cl-uniform-work-group-size and the local work size is specified in ndrange but the global work size specified in ND Range is not a multiple of the local work size, the negative integer value -160 is returned.
    /// - When Wait Events is null and Num Events > 0, or if Wait Events is not null and Num Events is 0, or if event objects in Wait Events are not valid events, the negative integer value -57 is returned.
    /// - When the queue object q is full, the negative integer value -161 is returned.
    /// - When one of the operands Local Size is 0, the negative integer value -51 is returned.
    /// - When Ret Event is not a null object and an event could not be allocated, the negative integer value -100 is returned.
    /// - When there is a failure to queue Invoke in the queue q because of insufficient resources needed to execute the kernel, the negative integer value -5 is returned.
    /// </summary>
    [DependsOn(LanguageCapability.Kernel)]
    public sealed class OpEnqueueKernel : DeviceSideEnqueueInstruction
    {
        public override bool IsDeviceSideEnqueue => true;
        public override OpCode OpCode => OpCode.EnqueueKernel;
        public override ID? ResultID => Result;
        public override ID? ResultTypeID => ResultType;

        public ID ResultType;
        public ID Result;
        public ID Q;
        public KernelEnqueueFlags Flags;
        public ID NDRange;
        public ID NumEvents;
        public ID WaitEvents;
        public ID RetEvent;
        public ID Invoke;
        public ID Param;
        public ID ParamSize;
        public ID ParamAlign;
        public ID[] Locals = { };

        #region Code
        public override string ToString() => "(" + OpCode + "(" + (int)OpCode + ")" + ", " + StrOf(ResultType) + ", " + StrOf(Result) + ", " + StrOf(Q) + ", " + StrOf(Flags) + ", " + StrOf(NDRange) + ", " + StrOf(NumEvents) + ", " + StrOf(WaitEvents) + ", " + StrOf(RetEvent) + ", " + StrOf(Invoke) + ", " + StrOf(Param) + ", " + StrOf(ParamSize) + ", " + StrOf(ParamAlign) + ", " + StrOf(Locals) + ")";
        public override string ArgString => "Q: " + StrOf(Q) + ", " + "Flags: " + StrOf(Flags) + ", " + "NDRange: " + StrOf(NDRange) + ", " + "NumEvents: " + StrOf(NumEvents) + ", " + "WaitEvents: " + StrOf(WaitEvents) + ", " + "RetEvent: " + StrOf(RetEvent) + ", " + "Invoke: " + StrOf(Invoke) + ", " + "Param: " + StrOf(Param) + ", " + "ParamSize: " + StrOf(ParamSize) + ", " + "ParamAlign: " + StrOf(ParamAlign) + ", " + "Locals: " + StrOf(Locals);

        protected override void FromCode(uint[] codes, int start)
        {
            System.Diagnostics.Debug.Assert((codes[start] & 0x0000FFFF) == (uint)OpCode.EnqueueKernel);
            var i = start + 1;
            ResultType = new ID(codes[i++]);
            Result = new ID(codes[i++]);
            Q = new ID(codes[i++]);
            Flags = (KernelEnqueueFlags)codes[i++];
            NDRange = new ID(codes[i++]);
            NumEvents = new ID(codes[i++]);
            WaitEvents = new ID(codes[i++]);
            RetEvent = new ID(codes[i++]);
            Invoke = new ID(codes[i++]);
            Param = new ID(codes[i++]);
            ParamSize = new ID(codes[i++]);
            ParamAlign = new ID(codes[i++]);
            var length = WordCount - (i - start);
            Locals = new ID[length];
            for (var k = 0; k < length; ++k)
                Locals[k] = new ID(codes[i++]);
        }

        protected override void WriteCode(List<uint> code)
        {
            code.Add(ResultType.Value);
            code.Add(Result.Value);
            code.Add(Q.Value);
            code.Add((uint)Flags);
            code.Add(NDRange.Value);
            code.Add(NumEvents.Value);
            code.Add(WaitEvents.Value);
            code.Add(RetEvent.Value);
            code.Add(Invoke.Value);
            code.Add(Param.Value);
            code.Add(ParamSize.Value);
            code.Add(ParamAlign.Value);
            if (Locals != null)
                foreach (var val in Locals)
                    code.Add(val.Value);
        }

        public override IEnumerable<ID> AllIDs
        {
            get
            {
                yield return ResultType;
                yield return Result;
                yield return Q;
                yield return NDRange;
                yield return NumEvents;
                yield return WaitEvents;
                yield return RetEvent;
                yield return Invoke;
                yield return Param;
                yield return ParamSize;
                yield return ParamAlign;
                if (Locals != null)
                    foreach (var id in Locals)
                        yield return id;
            }
        }
        #endregion
    }
}


text:
package com.github.mogproject.redismock.util.hashing

import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, FunSpec, Matchers}

class MurmurHashSpec extends FunSpec with Matchers with BeforeAndAfterEach with BeforeAndAfterAll {
  describe("HashUtil#murmurHash64A") {
    it("should return 64 bit value") {
      MurmurHash.murmurHash64A("A".getBytes) shouldBe 0xfc089b66b14af040L
      MurmurHash.murmurHash64A("AB".getBytes) shouldBe 0x24fb508dc42efb7fL
      MurmurHash.murmurHash64A("B".getBytes) shouldBe 0x130dd9603dcd32a4L
      MurmurHash.murmurHash64A("BA".getBytes) shouldBe 0x25cbc673105b365dL

      MurmurHash.murmurHash64A("".getBytes) shouldBe 0xd8dfea6585bc9732L
      MurmurHash.murmurHash64A("ABCDEFGHabcdefg".getBytes) shouldBe 0x3dfb8e09231eeb32L
      MurmurHash.murmurHash64A("ABCDEFGHabcdefgh".getBytes) shouldBe 0x40055074d92b389fL
      MurmurHash.murmurHash64A("ABCDEFGHabcdefghi".getBytes) shouldBe 0xd298ffe6aa77babeL

      MurmurHash.murmurHash64A(Seq.fill[Byte](100)(0)) shouldBe 0xc9450ffd5a7bf9ccL
      MurmurHash.murmurHash64A(Seq.fill[Byte](100)(-1)) shouldBe 0x78be0c4f11cdc6d5L
    }
  }
}


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mfd/adp5520.h>

#include <linux/gpio.h>

struct adp5520_gpio {
	struct device *master;
	struct gpio_chip gpio_chip;
	unsigned char lut[ADP5520_MAXGPIOS];
	unsigned long output;
};

static int adp5520_gpio_get_value(struct gpio_chip *chip, unsigned off)
{
	struct adp5520_gpio *dev;
	uint8_t reg_val;

	dev = container_of(chip, struct adp5520_gpio, gpio_chip);

	/*
	 * There are dedicated registers for GPIO IN/OUT.
	 * Make sure we return the right value, even when configured as output
	 */

	if (test_bit(off, &dev->output))
		adp5520_read(dev->master, GPIO_OUT, &reg_val);
	else
		adp5520_read(dev->master, GPIO_IN, &reg_val);

	return !!(reg_val & dev->lut[off]);
}

static void adp5520_gpio_set_value(struct gpio_chip *chip,
		unsigned off, int val)
{
	struct adp5520_gpio *dev;
	dev = container_of(chip, struct adp5520_gpio, gpio_chip);

	if (val)
		adp5520_set_bits(dev->master, GPIO_OUT, dev->lut[off]);
	else
		adp5520_clr_bits(dev->master, GPIO_OUT, dev->lut[off]);
}

static int adp5520_gpio_direction_input(struct gpio_chip *chip, unsigned off)
{
	struct adp5520_gpio *dev;
	dev = container_of(chip, struct adp5520_gpio, gpio_chip);

	clear_bit(off, &dev->output);

	return adp5520_clr_bits(dev->master, GPIO_CFG_2, dev->lut[off]);
}

static int adp5520_gpio_direction_output(struct gpio_chip *chip,
		unsigned off, int val)
{
	struct adp5520_gpio *dev;
	int ret = 0;
	dev = container_of(chip, struct adp5520_gpio, gpio_chip);

	set_bit(off, &dev->output);

	if (val)
		ret |= adp5520_set_bits(dev->master, GPIO_OUT, dev->lut[off]);
	else
		ret |= adp5520_clr_bits(dev->master, GPIO_OUT, dev->lut[off]);

	ret |= adp5520_set_bits(dev->master, GPIO_CFG_2, dev->lut[off]);

	return ret;
}

static int __devinit adp5520_gpio_probe(struct platform_device *pdev)
{
	struct adp5520_gpio_platfrom_data *pdata = pdev->dev.platform_data;
	struct adp5520_gpio *dev;
	struct gpio_chip *gc;
	int ret, i, gpios;
	unsigned char ctl_mask = 0;

	if (pdata == NULL) {
		dev_err(&pdev->dev, "missing platform data\n");
		return -ENODEV;
	}

	if (pdev->id != ID_ADP5520) {
		dev_err(&pdev->dev, "only ADP5520 supports GPIO\n");
		return -ENODEV;
	}

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL) {
		dev_err(&pdev->dev, "failed to alloc memory\n");
		return -ENOMEM;
	}

	dev->master = pdev->dev.parent;

	for (gpios = 0, i = 0; i < ADP5520_MAXGPIOS; i++)
		if (pdata->gpio_en_mask & (1 << i))
			dev->lut[gpios++] = 1 << i;

	if (gpios < 1) {
		ret = -EINVAL;
		goto err;
	}

	gc = &dev->gpio_chip;
	gc->direction_input  = adp5520_gpio_direction_input;
	gc->direction_output = adp5520_gpio_direction_output;
	gc->get = adp5520_gpio_get_value;
	gc->set = adp5520_gpio_set_value;
	gc->can_sleep = 1;

	gc->base = pdata->gpio_start;
	gc->ngpio = gpios;
	gc->label = pdev->name;
	gc->owner = THIS_MODULE;

	ret = adp5520_clr_bits(dev->master, GPIO_CFG_1,
		pdata->gpio_en_mask);

	if (pdata->gpio_en_mask & GPIO_C3)
		ctl_mask |= C3_MODE;

	if (pdata->gpio_en_mask & GPIO_R3)
		ctl_mask |= R3_MODE;

	if (ctl_mask)
		ret = adp5520_set_bits(dev->master, LED_CONTROL,
			ctl_mask);

	ret |= adp5520_set_bits(dev->master, GPIO_PULLUP,
		pdata->gpio_pullup_mask);

	if (ret) {
		dev_err(&pdev->dev, "failed to write\n");
		goto err;
	}

	ret = gpiochip_add(&dev->gpio_chip);
	if (ret)
		goto err;

	platform_set_drvdata(pdev, dev);
	return 0;

err:
	kfree(dev);
	return ret;
}

static int __devexit adp5520_gpio_remove(struct platform_device *pdev)
{
	struct adp5520_gpio *dev;
	int ret;

	dev = platform_get_drvdata(pdev);
	ret = gpiochip_remove(&dev->gpio_chip);
	if (ret) {
		dev_err(&pdev->dev, "%s failed, %d\n",
				"gpiochip_remove()", ret);
		return ret;
	}

	kfree(dev);
	return 0;
}

static struct platform_driver adp5520_gpio_driver = {
	.driver	= {
		.name	= "adp5520-gpio",
		.owner	= THIS_MODULE,
	},
	.probe		= adp5520_gpio_probe,
	.remove		= __devexit_p(adp5520_gpio_remove),
};

static int __init adp5520_gpio_init(void)
{
	return platform_driver_register(&adp5520_gpio_driver);
}
module_init(adp5520_gpio_init);

static void __exit adp5520_gpio_exit(void)
{
	platform_driver_unregister(&adp5520_gpio_driver);
}
module_exit(adp5520_gpio_exit);

MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("GPIO ADP5520 Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:adp5520-gpio");


text:
package com.hackerrank.algorithm.warmup.angryprofessor.java;

import java.util.Scanner;

/**
 * Created by kevin on 21/03/15
 */
public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Integer nbOfTest = in.nextInt();

        for (int cptOfTest = nbOfTest; cptOfTest > 0; cptOfTest--) {
            Integer nbStudents = in.nextInt(),
                    minStutendsForClass = in.nextInt();

            Integer numberOfStudendsPresent = 0;
            for (int cptOfStudents = nbStudents; cptOfStudents > 0; cptOfStudents--) {
                numberOfStudendsPresent += (in.nextInt() <= 0) ? 1 : 0;
            }

            System.out.println(numberOfStudendsPresent < minStutendsForClass ? "YES" : "NO" );
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$window = json_decode($tab);
$tab 	= $window->tab;
switch ($tab) {
	case 'home':
?>

		Regresar
	  	 Petición
	  	 Notas
	  	 Adjuntos
	  	 Historial

<?php
		break;
	case 'addUser':
?>

	   Mostrar
	   Agregar

<?php
		break;
	default:
?>

<?php
		break;
}
?>


text:
<?php

namespace Abby\Knowledgebase\app\Http\Controllers\Admin;

use Backpack\CRUD\app\Http\Controllers\CrudController;
// VALIDATION: change the requests to match your own file names if you need form validation
use Abby\Knowledgebase\app\Http\Requests\SpaceRequest as StoreRequest;
use Abby\Knowledgebase\app\Http\Requests\SpaceRequest as UpdateRequest;

class SpaceCrudController extends CrudController
{
    public function __construct()
    {
        parent::__construct();

        /*
        |--------------------------------------------------------------------------
        | BASIC CRUD INFORMATION
        |--------------------------------------------------------------------------
        */
        $this->crud->setModel("Abby\Knowledgebase\app\Models\Space");
        $this->crud->setRoute(config('backpack.base.route_prefix', 'admin').'/knowledgebase/space');
        $this->crud->setEntityNameStrings(trans('backpack::knowledgebase.space'), trans('backpack::knowledgebase.spaces'));

        /*
        |--------------------------------------------------------------------------
        | COLUMNS AND FIELDS
        |--------------------------------------------------------------------------
        */

        // ------ CRUD COLUMNS
        $this->crud->addColumn([
                                'name' => 'icon',
                                'label' => 'Icon',
                                'type' => 'icon-fontawesome'
                            ]);
        $this->crud->addColumn([
                                'name' => 'title',
                                'label' => 'Title',
                            ]);
        $this->crud->addColumn([
                                'name' => 'slug',
                                'label' => 'Slug',
                            ]);
        $this->crud->addColumn([
                                'name' => 'description',
                                'label' => 'Description',
                            ]);

        // ------ CRUD FIELDS
        $this->crud->addField([    // TEXT
                                'name' => 'title',
                                'label' => 'Title',
                                'type' => 'text',
                                'placeholder' => 'Your title here',
                            ]);
        $this->crud->addField([
                                'name' => 'slug',
                                'label' => 'Slug (URL)',
                                'type' => 'text',
                                'hint' => 'Will be automatically generated from your title, if left empty.',
                            ]);
        $this->crud->addField([    // TEXT
                                'name' => 'icon',
                                'label' => 'Icon',
                                'type' => 'icon_picker',
                                'iconset' => 'fontawesome',
                            ]);
        $this->crud->addField([
                                'name' => 'description',
                                'label' => 'Description',
                                'type' => 'text',
                            ]);

        $this->crud->enableAjaxTable();
    }

    public function store(StoreRequest $request)
    {
        return parent::storeCrud();
    }

    public function update(UpdateRequest $request)
    {
        return parent::updateCrud();
    }
}


text:
package com.github.trytocatch.mapsearcher;

import com.github.trytocatch.mapsearcher.Task.ReturnState;

abstract class Searcher<N> {
	abstract <R> ReturnState doSearch(SearchInfo<N, R> info);
}


text:
require 'freakin/version'
require 'freakin/translator'

module Freakin #:nodoc:
  # The main Freakin class. It is not intended to be instantiated and instead
  # just need to call its hi method.
  class Freakin
    # When called returns a greeting matching the language defined. Currently
    # supports English and Spanish.
    #
    # ==== Attributes
    #
    # * +language+ - Set to select a different language. Default is +english+.
    #
    # ==== Examples
    #
    #   Freakin::Freakin.hi
    #   Freakin::Freakin.hi('spanish')
    #
    def self.hi(language = 'english')
      trans = Translator.new(language)
      trans.hi
    end
  end
end


text:
class InstancesController < MVCLI::Controller

  requires :instances
  requires :command

  def index
    instances.all
  end

  def show
    instance.reload
  end

  def create
    template = Instances::CreateForm
    argv = MVCLI::Argv.new command.argv
    form = template.new argv.options
    form.validate!

    #How expansive do we want these command line options to be?
    options = {
      name: form.name,
      flavor_id: form.flavor,
      volume_size: form.size
    }
    instances.create options
  end

  def destroy
    instance.tap do |i|
      i.destroy
    end
  end

  private

  def instance
    @instance ||= index.find {|i| i.name == params[:id]} or fail Fog::Errors::NotFound
  end
end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18449
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Azure.DataCenterMigration.App
{

  /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class StringResources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal StringResources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Azure.DataCenterMigration.App.StringResources", typeof(StringResources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Exception of type {0} occurred : {1}.
        /// </summary>
        internal static string ExceptionOccurred {
            get {
                return ResourceManager.GetString("ExceptionOccurred", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Press Any Key To Exit...
        /// </summary>
        internal static string ExitApplicationMessage {
            get {
                return ResourceManager.GetString("ExitApplicationMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ---------------------------------------------------------------.
        /// </summary>
        internal static string HelpDash {
            get {
                return ResourceManager.GetString("HelpDash", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DeltaBackOff :  (optional) Delta backoff in seconds for 'Exponential Backoff' retry strategy, Default is 90 seconds.
        /// </summary>
        internal static string HelpDeltaBackOff {
            get {
                return ResourceManager.GetString("HelpDeltaBackOff", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationCertificateThumbprint : Certificate thumbprint for source subscription. User needs to provide value for either DestinationPublishSettingsFilePath or DestinationCertificateThumbprint for authentiacation.
        /// </summary>
        internal static string HelpDestinationCertificateThumbprint {
            get {
                return ResourceManager.GetString("HelpDestinationCertificateThumbprint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationDCName : Destination Data Center Name.
        /// </summary>
        internal static string HelpDestinationDCName {
            get {
                return ResourceManager.GetString("HelpDestinationDCName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationPrefixName : Destination Prefix Name.
        /// </summary>
        internal static string HelpDestinationPrefixName {
            get {
                return ResourceManager.GetString("HelpDestinationPrefixName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationPublishSettingsFilePath : Destination PublishSettings file path.
        /// </summary>
        internal static string HelpDestinationPublishSettingsFilePath {
            get {
                return ResourceManager.GetString("HelpDestinationPublishSettingsFilePath", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationSubscriptionID : Destination Subscription Id.
        /// </summary>
        internal static string HelpDestinationSubscriptionId {
            get {
                return ResourceManager.GetString("HelpDestinationSubscriptionId", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Example :  -Operation "Export" -SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" -SourceDCName "East Asia" -ExportMetadataFolderPath "D:\\DataCenterMigration" -SourcePublishSettingsFilePath  "D:\\PublishSettings.PublishSettings" -SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7" -QuietMode "True" -GenerateMapperXml "True" -RetryCount "5" -MinBackoff "3" -MaxBackoff "3" -DeltaBackoff "90".
        /// </summary>
        internal static string HelpExportExample {
            get {
                return ResourceManager.GetString("HelpExportExample", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -ExportMetadataFolderPath : Folder path where the exported metadata file will be saved.
        /// </summary>
        internal static string HelpExportMetadataFolderPath {
            get {
                return ResourceManager.GetString("HelpExportMetadataFolderPath", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Help for Export Functionality : -.
        /// </summary>
        internal static string HelpForExportFunctionality {
            get {
                return ResourceManager.GetString("HelpForExportFunctionality", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Help for Import Functionality : -.
        /// </summary>
        internal static string HelpForImportFunctionality {
            get {
                return ResourceManager.GetString("HelpForImportFunctionality", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Help for Migrate Functionality : -.
        /// </summary>
        internal static string HelpForMigrateFunctionality {
            get {
                return ResourceManager.GetString("HelpForMigrateFunctionality", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -GenerateMapperXml : (optional) true if user wants to create mapper xml file for resource name. Default is false..
        /// </summary>
        internal static string HelpGenerateMapperXml {
            get {
                return ResourceManager.GetString("HelpGenerateMapperXml", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -DestinationPrefixName : Destination Prefix Name. User needs to provide value for either MapperXmlFilePath or DestinationPrefixName..
        /// </summary>
        internal static string HelpImportDestinationPrefixName {
            get {
                return ResourceManager.GetString("HelpImportDestinationPrefixName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Example : -Operation "Import" -SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" -DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" -DestinationDCName "West US" -SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings"  -SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7" -DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" -DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7" -ImportMetadataFilePath "D:\\Data [rest of string was truncated]";.
        /// </summary>
        internal static string HelpImportExample {
            get {
                return ResourceManager.GetString("HelpImportExample", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -ImportMetadataFilePath: File path where the metadata is saved.
        /// </summary>
        internal static string HelpImportMetadataFilePath {
            get {
                return ResourceManager.GetString("HelpImportMetadataFilePath", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -MapperXmlFilePath: File path where the mapper xml is saved.
        /// </summary>
        internal static string HelpMapperXmlFilePath {
            get {
                return ResourceManager.GetString("HelpMapperXmlFilePath", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -MaxBackoff :  (optional) Maximum backoff in seconds for 'Exponential Backoff' retry strategy, Default is 30 seconds.
        /// </summary>
        internal static string HelpMaxBackoff {
            get {
                return ResourceManager.GetString("HelpMaxBackoff", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Example : -Operation "Migrate" -SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" -DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" -SourceDCName "East Asia" -DestinationDCName "West US" -SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings"  -SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7" -DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" -DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7" -Expor [rest of string was truncated]";.
        /// </summary>
        internal static string HelpMigrateExample {
            get {
                return ResourceManager.GetString("HelpMigrateExample", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -MinBackoff :  (optional) Minimum backoff in seconds for 'Exponential Backoff' retry strategy, Default is 30 seconds.
        /// </summary>
        internal static string HelpMinBackoff {
            get {
                return ResourceManager.GetString("HelpMinBackoff", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -QuietMode : (optional) true if user don't want to print progress messages on console. Default is false..
        /// </summary>
        internal static string HelpQuietMode {
            get {
                return ResourceManager.GetString("HelpQuietMode", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -ResumeImport : (optional)true if user wants to update import status in the same file. Default is false..
        /// </summary>
        internal static string HelpResumeImport {
            get {
                return ResourceManager.GetString("HelpResumeImport", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -RetryCount : (optional) No. of times to retry in case of exception, Default is '5'.
        /// </summary>
        internal static string HelpRetryCount {
            get {
                return ResourceManager.GetString("HelpRetryCount", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -RollBackOnFailure : (optional)true if user wants to rollback all imported resources. Default is false..
        /// </summary>
        internal static string HelpRollbackOnFailure {
            get {
                return ResourceManager.GetString("HelpRollbackOnFailure", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -SourceCertificateThumbprint : Certificate thumbprint for source subscription. User needs to provide value for either SourcePublishSettingsFilePath or SourceCertificateThumbprint for authentiacation.
        /// </summary>
        internal static string HelpSourceCertificateThumbprint {
            get {
                return ResourceManager.GetString("HelpSourceCertificateThumbprint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -SourceDCName : Source Data Center Name.
        /// </summary>
        internal static string HelpSourceDCName {
            get {
                return ResourceManager.GetString("HelpSourceDCName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -SourcePublishSettingsFilePath : SourcePublishSettings file path.
        /// </summary>
        internal static string HelpSourcePublishSettingsFilePath {
            get {
                return ResourceManager.GetString("HelpSourcePublishSettingsFilePath", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -SourceSubscriptionID : Source Subscription Id.
        /// </summary>
        internal static string HelpSourceSubscriptionId {
            get {
                return ResourceManager.GetString("HelpSourceSubscriptionId", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to WARNING : Import process will stop virtual machines of source subscription. Do you want to continue? (Y/N) : .
        /// </summary>
        internal static string ImportWarning {
            get {
                return ResourceManager.GetString("ImportWarning", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to WARNING : Import process will stop virtual machines of source subscription. .
        /// </summary>
        internal static string ImportWarningLog {
            get {
                return ResourceManager.GetString("ImportWarningLog", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid syntax. Argument name should be preceded with '-'. .
        /// </summary>
        internal static string InvalidArgumentDeclaration {
            get {
                return ResourceManager.GetString("InvalidArgumentDeclaration", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid argument name : '{0}'..
        /// </summary>
        internal static string InvalidArgumentName {
            get {
                return ResourceManager.GetString("InvalidArgumentName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid number of arguments..
        /// </summary>
        internal static string InvalidNumberOfArguments {
            get {
                return ResourceManager.GetString("InvalidNumberOfArguments", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to No input parameters are provided. Pass commandline arguments or provide the values in App.config file..
        /// </summary>
        internal static string MissingInputParameters {
            get {
                return ResourceManager.GetString("MissingInputParameters", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -Operation parameter should be define first parameter with value as Export /Import /Migrate.
        /// </summary>
        internal static string MissingOperationParameter {
            get {
                return ResourceManager.GetString("MissingOperationParameter", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Required parameter '{0}' is missing. Define parameter in '{1}' ..
        /// </summary>
        internal static string MissingRequiredParameter {
            get {
                return ResourceManager.GetString("MissingRequiredParameter", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Please select a valid option (y/n): .
        /// </summary>
        internal static string SelectValidOption {
            get {
                return ResourceManager.GetString("SelectValidOption", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Validation Error : {0} .
        /// </summary>
        internal static string ValidationError {
            get {
                return ResourceManager.GetString("ValidationError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Argument {0} should contain "true" / "false" value only.
        /// </summary>
        internal static string WrongInputForBoolArg {
            get {
                return ResourceManager.GetString("WrongInputForBoolArg", resourceCulture);
            }
        }
    }
}


text:
package model.tasks;

import model.map.Map;
import model.units.Unit;

/**
 * Performed when the unit needs to drink
 * @author Christopher Chapline, James Fagan, Emily Leones, Michelle Yung
 *
 */
public class DrinkTask extends Task {

	private static final long serialVersionUID = -3242173019984231381L;

	public DrinkTask(int work, int locTask, Map map, Unit unit) {
		super(work, locTask, map);
	}

	/**
	 * Restores the unit's thirst level to it's max level
	 */
	@Override public void performAction() {
		int maxThirstLevel = unit.getMAX_THIRST_LEVEL();

		unit.setThirstLevel( maxThirstLevel);
		this.isDone = true;
	}

}