text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Xml;

namespace Sce.Atf.Applications
{
    ///
    /// Service that manages user editable settings (preferences) and app settings persistence
    public abstract class SettingsServiceBase : ISettingsService, ISettingsPathsProvider, ICommandClient
    {
        ///
        /// Constructor
        protected SettingsServiceBase()
        {
            // Can be null if called from unmanaged code, like in UnitTests.
            Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();

            AssemblyName assemblyName = assembly.GetName();
            m_applicationName = assemblyName.Name;
            Version version = assemblyName.Version;
            m_versionString = version.Major + "." + version.Minor;

            string startupPath = Path.GetDirectoryName(new Uri(assemblyName.CodeBase).LocalPath);
            m_defaultSettingsPath = Path.Combine(startupPath, "DefaultSettings.xml");

            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            m_settingsPath = string.Format("{0}\\{1}\\{2}\\AppSettings.xml", appDataPath, m_applicationName, m_versionString);
        }

        ///
        /// Gets or sets the file path where settings data should be persisted
        /// <remarks>Path is initialized to Environment.SpecialFolder.ApplicationData\Application.ProductName\Version\AppSettings.xml</remarks>
        public string SettingsPath
        {
            get { return m_settingsPath; }
            set { m_settingsPath = value; }
        }

        ///
        /// Gets or sets the file path where default settings data can be found; default data is used
        /// when no persisted settings data can be found
        /// <remarks>Path is initialized to Application.StartupPath\DefaultSettings.xml</remarks>
        public string DefaultSettingsPath
        {
            get { return m_defaultSettingsPath; }
            set { m_defaultSettingsPath = value; }
        }

        ///
        /// Gets or sets a value indicating if the user can edit settings
        /// <remarks>Default is true</remarks>
        public bool AllowUserEdits
        {
            get { return m_allowUserEdits; }
            set { m_allowUserEdits = value; }
        }

        ///
        /// Gets or sets a value indicating if the user can load and save settings files
        /// <remarks>Default is true</remarks>
        public bool AllowUserLoadSave
        {
            get { return m_allowUserLoadSave; }
            set { m_allowUserLoadSave = value; }
        }

        ///
        /// Gets or sets the current state of all properties (Memento pattern)
        public object State
        {
            get
            {
                MemoryStream stream = new MemoryStream();
                Serialize(stream);
                return stream;
            }
            set
            {
                MemoryStream stream = value as MemoryStream;
                if (stream == null)
                    throw new ArgumentException("Not a valid memento");
                stream.Position = 0;
                Deserialize(stream);
            }
        }

        ///
        /// Gets and sets the current state of all properties that are user settable (Memento pattern)
        public object UserState
        {
            get
            {
                // Collect all the pairs of property descriptors and the current value of that property
                var values = new List<Pair<PropertyDescriptor, object>>();
                foreach (var propertyDescriptor in UserPropertyDescriptors)
                    values.Add(new Pair<PropertyDescriptor, object>(propertyDescriptor, propertyDescriptor.GetValue(null)));
                return values;
            }
            set
            {
                // Restore the state by setting the properties to their former values
                var values = (List<Pair<PropertyDescriptor, object>>)value;
                foreach (var pair in values)
                    pair.First.SetValue(null, pair.Second);
            }
        }

        ///
        /// Sets all settings to their default values
        /// <remarks>Settings that have no default are not changed</remarks>
        public void SetDefaults()
        {
            foreach (SettingsInfo info in m_settings.Values)
            {
                foreach (SettingsInfo.Setting setting in info.Settings.Values)
                    if (setting.PropertyDescriptor != null && setting.PropertyDescriptor.CanResetValue(null))
                        setting.PropertyDescriptor.ResetValue(null);
            }
        }

        #region ICommandClient Members

        ///
        /// Checks if the client can do the command
        /// <param name="tag">Command</param>
        /// <returns>true, if client can do the command</returns>
        public virtual bool CanDoCommand(object tag)
        {
            bool enabled = false;
            if (tag is CommandId)
            {
                switch ((CommandId)tag)
                {
                    case CommandId.EditPreferences:
                    case CommandId.EditImportExportSettings:
                        enabled = true;
                        break;
                }
            }

            return enabled;
        }

        ///
        /// Do a command
        /// <param name="tag">Command</param>
        public virtual void DoCommand(object tag)
        {
            if (tag is CommandId)
            {
                switch ((CommandId)tag)
                {
                    case CommandId.EditPreferences:
                        PresentUserSettings(null);
                        break;

                    case CommandId.EditImportExportSettings:
                        PresentLoadSaveSettings();
                        break;
                }
            }
        }

        ///
        /// Updates command state for given command
        /// <param name="commandTag">Command</param>
        /// <param name="state">Command state to update</param>
        public virtual void UpdateCommand(object commandTag, CommandState state)
        {
        }

        #endregion

        #region ISettingsService Members

        ///
        /// Registers persistent application settings
        /// <param name="uid">Unique identifer for settings</param>
        /// <param name="settings">All settings</param>
        public void RegisterSettings(string uid, params PropertyDescriptor[] settings)
        {
            SettingsInfo settingsInfo;
            if (!m_settings.TryGetValue(uid, out settingsInfo))
            {
                settingsInfo = new SettingsInfo(uid);
                m_settings.Add(uid, settingsInfo);
            }

            foreach (PropertyDescriptor descriptor in settings)
                settingsInfo.Add(descriptor);
        }

        ///
        /// Registers settings that can be presented to the user for editing. These are not
        /// persisted unless RegisterSettings() is also called.
        /// <param name="pathName">Path to settings</param>
        /// <param name="settings">User editable settings</param>
        public void RegisterUserSettings(string pathName, params PropertyDescriptor[] settings)
        {
            if (string.IsNullOrEmpty(pathName))
                throw new ArgumentException("pathName");

            string[] path = pathName.Split(s_delimiters, 16);

            // get root folder
            Tree<object> folder = UserSettings as Tree<object>;
            if (folder == null)
                throw new InvalidOperationException("userSettings");

            // for each subsequent segment of the path, get folder
            for (int i = 0; i < path.Length - 1; i++)
                folder = GetOrCreateFolder(path[i], folder);

            // get the node that should hold the settings, if it already exists
            string name = path[path.Length - 1];
            UserSettingsInfo existing = null;
            int index = 0;
            foreach (Tree<object> node in folder.Children)
            {
                UserSettingsInfo info = node.Value as UserSettingsInfo;
                if (info != null)
                {
                    if (info.Name == name)
                    {
                        existing = info;
                        break;
                    }
                    if (info.Name.CompareTo(name) < 0)
                        index++;
                }
            }

            // add the settings, either by merging with the existing node or creating a new one
            if (existing != null)
            {
                foreach (PropertyDescriptor pd in settings)
                    existing.Settings.Add(pd);
            }
            else
            {
                Tree<object> node = new Tree<object>(new UserSettingsInfo(name, settings));
                folder.Children.Insert(index, node);
            }
        }

        ///
        /// Presents the settings dialog to the user, with the tree control opened to
        /// the given path
        /// <param name="pathName">Path of settings to display initially, or null</param>
        public abstract void PresentUserSettings(string pathName);

        ///
        /// Event that is raised when settings are being saved
        public event EventHandler Saving;

        ///
        /// Event that is raised when settings are being loaded
        public event EventHandler Loading;

        ///
        /// Event that is raised when the tree is reloaded
        public event EventHandler Reloaded;

        #endregion

        ///
        /// Initialize MEF component by registering commands with Command service and load settings
        protected virtual void Initialize()
        {
            // register our menu commands
            if (m_commandService != null)
            {
                if (m_allowUserEdits)
                {
                    m_commandService.RegisterCommand(
                        CommandId.EditPreferences,
                        StandardMenu.Edit,
                        StandardCommandGroup.EditPreferences,
                        "Preferences...".Localize("Edit user preferences"),
                        "Edit user preferences".Localize(),
                        this);
                }

                if (m_allowUserLoadSave)
                {
                    m_commandService.RegisterCommand(
                        CommandId.EditImportExportSettings,
                        StandardMenu.Edit,
                        StandardCommandGroup.EditPreferences,
                        "Load or Save Settings...".Localize(),
                        "User can save or load application settings from files".Localize(),
                        this);
                }
            }

            // load settings as late as possible, so that other components have a chance to
            //  register their settings first
            LoadSettings();
        }

        ///
        /// Presents the load/save settings dialog to the user
        protected abstract void PresentLoadSaveSettings();

        ///
        /// Saves application settings safely and creates a backup in the process
        public void SaveSettings()
        {
            string tempNew = string.Empty;

            string mutexName = GetMutexName(m_settingsPath);
            using (Mutex saveMutex = new Mutex(false, mutexName))
            {
                try
                {
                    saveMutex.WaitOne();

                    // Create zero-size file.
                    tempNew = Path.GetTempFileName();

                    using (Stream stream = File.Create(tempNew))
                        Serialize(stream);

                    // Make sure the settings directory exists. Do nothing if it already exists.
                    string settingsDir = Path.GetDirectoryName(m_settingsPath);
                    Directory.CreateDirectory(settingsDir);

                    // Erase old backup (if any) and move current settings file (if any).
                    string tempBackup = Path.Combine(settingsDir, "~Settings.xml");
                    if (File.Exists(tempBackup)) // seems unnecessary, but Dan put this check in the WPF version --Ron
                        File.Delete(tempBackup);
                    if (File.Exists(m_settingsPath))
                        File.Move(m_settingsPath, tempBackup);

                    // Move temporary file to be the new settings file, then delete backup.
                    File.Move(tempNew, m_settingsPath);
                    File.Delete(tempBackup);
                }
                catch (TargetInvocationException)
                {
                    // Catch and ignore TargetInvocationException happening if Windows
                    // is shut down with the application still running.
                    // TO DO: Find a way to successfully save settings and exit on shutdown.
                }
                catch (Exception ex)
                {
                    Outputs.WriteLine(OutputMessageType.Error, ex.Message);
                }
                finally
                {
                    // Attempt clean-up. No exception is thrown if file doesn't exist.
                    File.Delete(tempNew);
                    saveMutex.ReleaseMutex();
                }
            }
        }

        ///
        /// Loads all saved settings
        public void LoadSettings()
        {
            Loading.Raise(this, EventArgs.Empty);

            try
            {
                bool defaultSettingsExists = File.Exists(m_defaultSettingsPath);
                bool appSettingsExists = File.Exists(m_settingsPath);

                // only update property descriptors during the DefaultSettings.xml pass
                // if DefaultSettings.xml exists and AppSettings.xml does not exist
                SettingsInfo.CanMakeChanges = defaultSettingsExists && !appSettingsExists;

                // first, load default settings, if they exist:
                if (defaultSettingsExists)
                {
                    using (Stream stream = File.OpenRead(m_defaultSettingsPath))
                        Deserialize(stream);
                }

                // restore for AppSettings.xml pass
                SettingsInfo.CanMakeChanges = true;

                // now load user settings, overriding defaults:
                if (appSettingsExists)
                {
                    using (Stream stream = File.OpenRead(m_settingsPath))
                        Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                Outputs.WriteLine(OutputMessageType.Error, ex.Message);
            }
            finally
            {
                // restore value
                SettingsInfo.CanMakeChanges = true;
            }
        }

        ///
        /// Serialize settings values and write to given Stream
        /// <remarks>For use by SettingsLoadSaveDialog only</remarks>
        /// <param name="stream">Stream settings values written to</param>
        protected void Serialize(Stream stream)
        {
            Saving.Raise(this, EventArgs.Empty);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            XmlElement root = xmlDoc.CreateElement("settings");
            xmlDoc.AppendChild(root);

            // add application name and version to the root element.
            root.SetAttribute("appName", m_applicationName);
            root.SetAttribute("appVersion", m_versionString);

            foreach (SettingsInfo info in m_settings.Values)
            {
                XmlElement block = xmlDoc.CreateElement("block");
                block.SetAttribute("id", info.Name);

                foreach (SettingsInfo.Setting setting in info.Settings.Values)
                {
                    PropertyDescriptor descriptor = setting.PropertyDescriptor;
                    if (descriptor != null)
                    {
                        object value = descriptor.GetValue(null);
                        if (CanWriteValue(value))
                            WriteValue(descriptor.Name, value, block);
                    }
                    else
                    {
                        WriteValue(setting.Name, setting.ValueString, block);
                    }
                }
                // skip empty block
                if (block.ChildNodes.Count > 0)
                    root.AppendChild(block);
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.CloseOutput = false;
            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                xmlDoc.WriteTo(writer);
            }
        }

        ///
        /// Pull out persisted settings and set property descriptor values
        /// <remarks>Marked 'internal' for use by SettingsLoadSaveDialog only</remarks>
        /// <param name="stream">Persisted settings Stream</param>
        /// <returns>True iff successful</returns>
        protected bool Deserialize(Stream stream)
        {
            // create XML DOM from stream
            // if failed, display message box and return
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);

                XmlElement root = xmlDoc.DocumentElement;

                // get all the blocks
                XmlNodeList blocks = root.SelectNodes("block");
                if (blocks == null || blocks.Count == 0)
                    throw new Exception("The setting file is empty");

                foreach (XmlElement block in blocks)
                {
                    try
                    {
                        string id = block.GetAttribute("id");

                        SettingsInfo info;
                        if (!m_settings.TryGetValue(id, out info))
                        {
                            info = new SettingsInfo(id);
                            m_settings.Add(id, info);
                        }

                        // get a list of value element in each block
                        XmlNodeList valueNodes = block.SelectNodes("value");

                        // skip over empty block
                        if (valueNodes == null || valueNodes.Count == 0)
                            continue;

                        foreach (XmlElement xmlElement in valueNodes)
                        {
                            string name = xmlElement.GetAttribute("name");
                            string valueString = GetElementValueString(xmlElement);

                            info.Add(name, valueString);
                        }
                    }
                    catch (Exception ex)
                    {
                        Outputs.WriteLine(OutputMessageType.Error, ex.Message);
                    }
                }

                OnReloaded();
            }
            catch (Exception ex)
            {
                Outputs.WriteLine(
                    OutputMessageType.Error,
                    "Can't load settings".Localize() + ": {0}",
                    ex.Message);

                return false;
            }

            return true;
        }

        ///
        /// Raises the Reloaded event
        protected virtual void OnReloaded()
        {
            Reloaded.Raise(this, EventArgs.Empty);
        }

        ///
        /// Get user settings tree
        /// <remarks>For use by SettingsDialog only</remarks>
        protected virtual ITreeView UserSettings { get { return null; } }

        ///
        /// Return list of setting PropertyDescriptors
        /// <remarks>For use by SettingsDialog only</remarks>
        /// <param name="tree">Tree of user editable settings</param>
        /// <returns>List of setting PropertyDescriptors</returns>
        protected List<PropertyDescriptor> GetProperties(Tree<object> tree)
        {
            UserSettingsInfo info = tree.Value as UserSettingsInfo;
            if (info != null)
                return info.Settings;

            return null;
        }

        ///
        /// Return path of values associated with settings path
        /// <remarks>For use by SettingsDialog only</remarks>
        /// <param name="pathName">Path to settings</param>
        /// <returns>Path of values associated with settings path</returns>
        protected Path<object> GetSettingsPath(string pathName)
        {
            string[] pathSegments = pathName.Split(s_delimiters, 16);
            object[] path = new object[pathSegments.Length + 1];

            // first node is the settings tree root
            var userSettings = UserSettings as Tree<object>;
            if (userSettings == null)
                throw new InvalidOperationException("userSettings");

            Tree<object> node = userSettings;
            path[0] = userSettings.Value;

            // middle nodes are folders
            for (int i = 1; i < path.Length - 1; i++)
            {
                node = GetOrCreateFolder(pathSegments[i - 1], node);
                path[i] = node.Value;
            }

            // leaf node is user settings object
            foreach (Tree<object> leaf in node.Children)
            {
                UserSettingsInfo info = node.Value as UserSettingsInfo;
                if (info != null && info.Name == pathSegments[pathSegments.Length - 1])
                {
                    path[path.Length - 1] = leaf.Value;
                    break;
                }
            }

            return new Path<object>(path);
        }

        private Tree<object> GetOrCreateFolder(string name, Tree<object> tree)
        {
            // search for folder
            Tree<object> result = null;
            int index = 0;
            foreach (Tree<object> child in tree.Children)
            {
                string folderName = child.Value as string;
                if (folderName != null)
                {
                    if (folderName == name)
                    {
                        result = child;
                        break;
                    }

                    if (folderName.CompareTo(name) < 0)
                        index++;
                }
                else // child is UserSettingsInfo
                {
                    index++; // folders should follow settings nodes
                }

            }

            // if not found, create it
            if (result == null)
            {
                result = new Tree<object>(name);
                tree.Children.Insert(index, result);
            }

            return result;
        }

        private bool CanWriteValue(object value)
        {
            if (value == null)
                return false;

            TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
            return CanConvertToAndFromString(converter) || value.GetType().IsSerializable;
        }

        private void WriteValue(string name, object value, XmlElement block)
        {
            if (value == null)
                return;

            // skip persisting if any exception occurs
            string valueString = null;
            Type type = value.GetType();
            TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (CanConvertToAndFromString(converter))
            {
                valueString = converter.ConvertToInvariantString(value);
            }
            else if (type.IsSerializable)
            {
                // serialize
                BinaryFormatter formatter = new BinaryFormatter();
                using (MemoryStream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, value);
                    valueString = Convert.ToBase64String(stream.GetBuffer());
                }
            }

            if (string.IsNullOrEmpty(valueString))
                return;

            XmlDocument xmlDoc = block.OwnerDocument;
            XmlElement elmValue = xmlDoc.CreateElement("value");
            elmValue.SetAttribute("name", name);
            elmValue.SetAttribute("type", type.Name);

            // if the valueString is xmlDoc then
            XmlDocument temp = StringToXmlDoc(valueString);
            if (temp != null)
            {
                // remove xml declaration if exists
                XmlDeclaration decl = temp.FirstChild as XmlDeclaration;
                if (decl != null)
                    temp.RemoveChild(decl);
                elmValue.InnerXml = temp.DocumentElement.OuterXml;
            }
            else
            {
                elmValue.InnerText = valueString;
            }

            block.AppendChild(elmValue);
        }

        // handle normal elements, and those with embedded XML documents
        private static string GetElementValueString(XmlElement element)
        {
            string valueString = element.InnerText;
            if (string.IsNullOrEmpty(valueString))
                valueString = element.InnerXml;

            return valueString;
        }

        private static object GetValue(Type type, string valueString)
        {
            object value = null;
            try
            {
                TypeConverter converter = TypeDescriptor.GetConverter(type);
                if (CanConvertToAndFromString(converter))
                {
                    value = converter.ConvertFromInvariantString(valueString);
                }
                else
                {
                    // deserialize
                    byte[] data = Convert.FromBase64String(valueString);
                    using (MemoryStream stream = new MemoryStream(data))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        value = formatter.Deserialize(stream);
                    }
                }
            }
            catch
            {
                value = null;
            }
            return value;
        }

        private static bool CanConvertToAndFromString(TypeConverter converter)
        {
            return converter.CanConvertFrom(typeof(string)) &&
                   converter.CanConvertTo(typeof(string));
        }

        private XmlDocument StringToXmlDoc(string strXml)
        {
            XmlDocument xmlDoc = null;
            try
            {
                int len = (strXml.Length > 20) ? 20 : strXml.Length;
                string test = StringUtil.RemoveAllWhiteSpace(strXml.Substring(0, len)).ToLower();
                if (test.Contains("<?xmlversion="))
                {
                    xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(strXml);
                }
            }
            catch
            {
                xmlDoc = null;
            }
            return xmlDoc;

        }

        // Gets the property descriptors of just the user settings. The component is 'null' for
        //  the property descriptors, when getting or setting the value for a particular property.
        private IEnumerable<PropertyDescriptor> UserPropertyDescriptors
        {
            get
            {
                var userSettings = UserSettings as Tree<object>;
                if (userSettings == null)
                    throw new InvalidOperationException("userSettings");

                foreach (Tree<object> node in userSettings.Children)
                {
                    UserSettingsInfo info = node.Value as UserSettingsInfo;
                    if (info != null)
                    {
                        foreach (PropertyDescriptor property in info.Settings)
                            yield return property;
                    }
                }
            }
        }

        // Gets a mutex name that can be used to lock access to a particular file.
        private static string GetMutexName(string pathName)
        {
            string safeName = pathName;

            //255 characters will break IpcChannel constructor. 250 works.
            if (safeName.Length > 250)
                safeName = safeName.Substring(safeName.Length - 250);

            // The Mutex constructor will crash if given '\', unless it's part of a valid path.
            // NextInstanceMonitor.ActivateApplication() will crash if there are '/' characters.
            safeName = safeName.Replace('/', '-');
            safeName = safeName.Replace('\\', '-');

            return safeName;
        }

        ///
        /// Class for handling information in a group of settings
        protected class SettingsInfo
        {
            ///
            /// Constructor with name
            /// <param name="name">Name associated with this group of settings</param>
            public SettingsInfo(string name)
            {
                Name = name;
            }

            ///
            /// Add a setting to group of settings as a name and value, replacing the previous value if present
            /// <param name="name">Setting name</param>
            /// <param name="valueString">Setting value</param>
            public void Add(string name, string valueString)
            {
                Setting setting;
                if (Settings.TryGetValue(name, out setting))
                {
                    setting.Set(name, valueString);
                }
                else
                {
                    Settings.Add(name, new Setting(name, valueString));
                }
            }

            ///
            /// Add a setting to group of settings as a PropertyDescriptor, replacing the previous value if present
            /// <param name="descriptor">PropertyDescriptor describing setting</param>
            public void Add(PropertyDescriptor descriptor)
            {
                Setting setting;
                if (Settings.TryGetValue(descriptor.Name, out setting))
                {
                    setting.Set(descriptor);
                }
                else
                {
                    Settings.Add(descriptor.Name, new Setting(descriptor));
                }
            }

            ///
            /// Name associated with this group of settings
            public readonly string Name;
            ///
            /// Dictionary for names and values of settings in group
            public readonly SortedDictionary<string, Setting> Settings = new SortedDictionary<string, Setting>();

            ///
            /// Class for handling individual setting information
            public class Setting
            {
                ///
                /// Constructor with PropertyDescriptor
                /// <param name="descriptor">PropertyDescriptor describing setting</param>
                public Setting(PropertyDescriptor descriptor)
                {
                    PropertyDescriptor = descriptor;
                }

                ///
                /// Constructor with name and value of setting
                /// <param name="name">Setting name</param>
                /// <param name="valueString">Setting value</param>
                public Setting(string name, string valueString)
                {
                    Name = name;
                    ValueString = valueString;
                }

                ///
                /// Set a setting's value with name and value of setting
                /// <param name="name">Setting name</param>
                /// <param name="valueString">Setting value</param>
                public void Set(string name, string valueString)
                {
                    Name = name;
                    ValueString = valueString;
                    if (PropertyDescriptor != null)
                    {
                        SetValue();
                    }
                }

                ///
                /// Set a setting's value with PropertyDescriptor
                /// <param name="descriptor">PropertyDescriptor describing setting</param>
                public void Set(PropertyDescriptor descriptor)
                {
                    PropertyDescriptor = descriptor;
                    if (Name != null && ValueString != null)
                    {
                        SetValue();
                    }
                }

                private void SetValue()
                {
                    if (!CanMakeChanges)
                        return;

                    object value = GetValue(PropertyDescriptor.PropertyType, ValueString);
                    PropertyDescriptor.SetValue(null, value);
                }

                ///
                /// Setting name
                public string Name;
                ///
                /// Setting value
                public string ValueString;
                ///
                /// Setting PropertyDescriptor
                public PropertyDescriptor PropertyDescriptor;
            }

            ///
            /// Set whether property descriptors are allowed to make changes
            /// <remarks>Used when persisted settings are being loaded from disk
            /// to prevent property descriptors from being set multiple times as
            /// in the case where DefaultSettings.xml and AppSettings.xml both exist</remarks>
            public static bool CanMakeChanges { private get; set; }
        }

        ///
        /// Class for group of user settings
        protected class UserSettingsInfo
        {
            ///
            /// Constructor with name and PropertyDescriptors
            /// <param name="name">Name of group of user settings</param>
            /// <param name="settings">PropertyDescriptors with settings</param>
            public UserSettingsInfo(string name, PropertyDescriptor[] settings)
            {
                Name = name;
                Settings = new List<PropertyDescriptor>(settings);
            }

            ///
            /// Name of group of user settings
            public readonly string Name;
            ///
            /// PropertyDescriptors with settings
            public readonly List<PropertyDescriptor> Settings;
        }

        [Import(AllowDefault = true)]
        private ICommandService m_commandService = null;

        private readonly string m_applicationName;
        private readonly string m_versionString;
        private string m_settingsPath;
        private string m_defaultSettingsPath;
        private readonly SortedDictionary<string, SettingsInfo> m_settings = new SortedDictionary<string, SettingsInfo>();
        private bool m_allowUserLoadSave = true;
        private bool m_allowUserEdits = true;

        private static readonly char[] s_delimiters = new[] { '/', '.', '\\' };
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="38dp"
        android:layout_weight="0.00"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/username"
            android:layout_width="194dp"
            android:layout_height="match_parent"
            android:layout_weight="0.53"
            android:fontFamily="@font/pt_sans_italic"
            android:text="@string/username"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/title"
            android:layout_width="205dp"
            android:layout_height="match_parent"
            android:layout_weight="0.31"
            android:fontFamily="@font/pt_sans_italic"
            android:text="@string/title"
            android:textSize="18sp" />
    </LinearLayout>

    <TextView
        android:id="@+id/reason"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.07"
        android:fontFamily="@font/pt_sans_italic"
        android:text="@string/reason"
        android:textSize="18sp"
        android:gravity="center_vertical"/>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.taverna.workbench.views.results.saveactions;

import static java.lang.Math.max;
import static java.util.Arrays.asList;
import static org.apache.taverna.workbench.icons.WorkbenchIcons.saveIcon;
import static org.apache.poi.ss.usermodel.CellStyle.BORDER_NONE;
import static org.apache.poi.ss.usermodel.CellStyle.BORDER_THIN;
import static org.apache.poi.ss.usermodel.CellStyle.SOLID_FOREGROUND;

import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;

import javax.swing.AbstractAction;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * Stores the entire map of result objects to disk as a single XML data document.
 *
 * @author Tom Oinn
 */
public class SaveAllResultsAsExcel extends SaveAllResultsSPI {
	private static final long serialVersionUID = -2759817859804112070L;

	HSSFWorkbook wb = null;
	HSSFSheet sheet = null;
	HSSFCellStyle headingStyle = null;
	HSSFCellStyle[] styles = null;

	public SaveAllResultsAsExcel() {
		super();
		putValue(NAME, "Save as Excel");
		putValue(SMALL_ICON, saveIcon);
	}

	@Override
	public AbstractAction getAction() {
		return new SaveAllResultsAsExcel();
	}

	@Override
	protected void saveData(File f) throws IOException {
		try {
			generateSheet();
		} catch (IntrospectionException e) {
			throw new IOException("failed to generate excel sheet model", e);
		}
		saveSheet(f);
	}

	/**
	 * Generate the Excel sheet from the DataThing's in the map. All of the
	 * results are shown in the same spreadsheet, but in different columns. Flat
	 * lists are shown vertically, 2d lists as a matrix, and deeper lists are
	 * flattened to 2d.
	 *
	 * @throws IntrospectionException
	 */
	void generateSheet() throws IntrospectionException {
		wb = new HSSFWorkbook();
		setStyles();
		sheet = wb.createSheet("Workflow results");
		sheet.setDisplayGridlines(false);
		int currentCol = 0;

		for (String portName : chosenReferences.keySet()) {
			logger.debug("Output for : " + portName);
			DataThing resultValue = bake(getObjectForName(portName));
			// Check whether there's a textual type
			Boolean textualType = isTextual(resultValue.getDataObject());
			if (textualType == null || !textualType)
				continue;
			logger.debug("Output is textual");
			getCell(currentCol, 0).setCellValue(portName);
			getCell(currentCol, 0).setCellStyle(headingStyle);
			int numCols = 1;
			int numRows = 1;
			int currentRow = 0;
			BaclavaIterator rows;
			try {
				rows = resultValue.iterator("l('')");
			} catch (IntrospectionException ex) {
				// Not a list, single value. We'll fake the iterator
				DataThing fakeValues = new DataThing(
						asList(resultValue.getDataObject()));
				rows = fakeValues.iterator("l('')");
			}
			/*
			 * If we only have one row, we'll show each value on a new row
			 * instead
			 */
			boolean isFlat = rows.size() == 1;
			while (rows.hasNext()) {
				DataThing row = (DataThing) rows.next();
				/*
				 * Even increase first time, as we don't want to overwrite our
				 * header
				 */
				currentRow++;
				BaclavaIterator bi = row.iterator("''");
				while (bi.hasNext()) {
					DataThing containedThing = (DataThing) bi.next();
					String containedValue = (String) containedThing.getDataObject();
					int columnOffset = 0;
					int[] location = bi.getCurrentLocation();
					if (!isFlat && location.length > 0) {
						columnOffset = location[location.length - 1];
						numCols = Math.max(numCols, columnOffset + 1);
					}
					logger.debug("Storing in cell " + (currentCol + columnOffset) + " "
							+ currentRow + ": " + containedValue);
					getCell(currentCol + columnOffset, currentRow).setCellValue(containedValue);
					if (isFlat)
						currentRow++;
				}
			}
			numRows = max(numRows, currentRow);

			// Set the styles
			for (int x = currentCol; x < currentCol + numCols; x++)
				for (int y = 1; y < numRows + 1; y++)
					setStyle(currentCol, x, y);
			sheet.setColumnWidth(currentCol + numCols, 200);
			currentCol += numCols + 1;
		}
	}

	void setStyle(int currentCol, int column, int row) {
		if (!hasValue(column, row))
			return;
		HSSFCell cell = getCell(column, row);
		int n = 0, s = 0, w = 0, e = 0;
		if (row < 2 || !hasValue(column, row - 1))
			n = 1;
		if (column == currentCol || !hasValue(column - 1, row))
			w = 1;
		if (!hasValue(column, row + 1))
			s = 1;
		if (!hasValue(column + 1, row))
			e = 1;
		int index = n + 2 * s + 4 * e + 8 * w;
		cell.setCellStyle(styles[index]);
	}

	void setStyles() {
		headingStyle = wb.createCellStyle();
		headingStyle.setBorderTop(BORDER_THIN);
		headingStyle.setBorderBottom(BORDER_THIN);
		headingStyle.setBorderLeft(BORDER_THIN);
		headingStyle.setBorderRight(BORDER_THIN);
		headingStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
		headingStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		headingStyle.setFillPattern(SOLID_FOREGROUND);
		styles = new HSSFCellStyle[16];
		for (int n = 0; n < 2; n++)
			for (int s = 0; s < 2; s++)
				for (int e = 0; e < 2; e++)
					for (int w = 0; w < 2; w++) {
						int index = n + 2 * s + 4 * e + 8 * w;
						styles[index] = wb.createCellStyle();
						styles[index].setBorderTop(n == 1 ? BORDER_THIN
								: BORDER_NONE);
						styles[index].setBorderBottom(s == 1 ? BORDER_THIN
								: BORDER_NONE);
						styles[index].setBorderRight(e == 1 ? BORDER_THIN
								: BORDER_NONE);
						styles[index].setBorderLeft(w == 1 ? BORDER_THIN
								: BORDER_NONE);
						styles[index].setFillBackgroundColor(HSSFColor.GOLD.index);
						styles[index].setFillForegroundColor(HSSFColor.GOLD.index);
						styles[index].setFillPattern(SOLID_FOREGROUND);
					}
	}

	/**
	 * Check if o is a String or contains elements that satisfy isTextual(o)
	 * <p>
	 * Traverse down the Collection o if possible, and check the tree of collection at the deepest
	 * level.
	 * </p>
	 *
	 * @param o
	 *            Object to check
	 * @return true if o is a String or is a Collection that contains a string at the deepest level.
	 *         false if o is not a String or Collection, or if it is a collection that contains
	 *         non-strings.
	 *         null if o is a Collection, but it is empty or contains nothing but Collections.
	 */
	Boolean isTextual(Object o) {
		if (o instanceof String)
			// We dug down and found a string. Hurray!
			return true;
		if (o instanceof Collection) {
			for (Object child : (Collection<?>) o) {
				Boolean isTxt = isTextual(child);
				if (isTxt == null)
					// Unknown, try next one
					continue;
				return isTxt;
			}
			/*
			 * We looped through and found just empty collections (or we are an
			 * empty collection), we don't know.
			 */
			return null;
		}
		// No, sorry mate.. o was neither a String or Collection
		return false;
	}

	/**
	 * Get a cell at the given coordinates, create it if needed.
	 *
	 * @param column
	 * @param row
	 * @return
	 */
	HSSFCell getCell(int column, int row) {
		HSSFRow srow = sheet.getRow(row);
		if (srow == null)
			srow = sheet.createRow(row);
		HSSFCell scell = srow.getCell(column);
		if (scell == null)
			scell = srow.createCell(column);
		return scell;
	}

	/**
	 * Check if a cell has a value.
	 *
	 * @param column
	 * @param row
	 * @return
	 */
	boolean hasValue(int column, int row) {
		HSSFRow srow = sheet.getRow(row);
		if (srow == null)
			return false;
		HSSFCell scell = srow.getCell(column);
		if (scell == null)
			return false;
		return true;
	}

	/**
	 * Save the generated worksheet to a file
	 *
	 * @param file
	 *            to save to
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	void saveSheet(File file) throws IOException {
		FileOutputStream fos = new FileOutputStream(file);
		wb.write(fos);
		fos.close();
	}

	@Override
	protected String getFilter() {
		return "xls";
	}
}


text:
from turtle import *
def curvemove():
    for i in range(200):
        right(1)
        forward(1)
color('red','pink')
begin_fill()
left(140)
forward(111.65)
curvemove()
left(120)
curvemove()
forward(111.65)
end_fill()
done()


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <integer name="isbn13_length">13</integer>
    <integer name="ean_width">8</integer>
    <dimen name="head_line">24sp</dimen>
    <dimen name="small_fontsize">12sp</dimen>

    <!-- Per the design guidelines, navigation drawers should be between 240dp and 320dp:
         https://developer.android.com/design/patterns/navigation-drawer.html -->
    <dimen name="navigation_drawer_width">240dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="half_activity_horizontal_margin">8dp</dimen>
    <dimen name="half_activity_vertical_margin">8dp</dimen>

    <dimen name="book_list_item_cover_height">40dp</dimen>
    <dimen name="empty_book_list_image_size">180dp</dimen>

</resources>


text:
using DragonSpark.Extensions;
using DragonSpark.Sources.Parameterized;
using DragonSpark.Specifications;
using DragonSpark.TypeSystem;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using PostSharp.Reflection;
using System;
using System.Collections.Generic;

namespace DragonSpark.Aspects.Build
{
	public sealed class ObjectConstructionFactory<T> : ParameterizedSourceBase<IEnumerable<object>, ObjectConstruction>
	{
		public static ObjectConstructionFactory<T> Default { get; } = new ObjectConstructionFactory<T>();
		ObjectConstructionFactory() {}

		public ObjectConstruction Get() => GetUsing( Items<object>.Default );
		public ObjectConstruction GetUsing( params object[] parameter ) => Get( parameter );

		public override ObjectConstruction Get( IEnumerable<object> parameter ) => new ObjectConstruction( typeof(T), parameter.Fixed() );
	}

	public sealed class AspectInstanceFactory<TAspect, TTarget> : SpecificationParameterizedSource<TTarget, AspectInstance>
	{
		public static AspectInstanceFactory<TAspect, TTarget> Default { get; } = new AspectInstanceFactory<TAspect, TTarget>();
		AspectInstanceFactory() : base( HasAspectSpecification.DefaultNested.Inverse(), Factory.DefaultNested.Get ) {}

		sealed class HasAspectSpecification : SpecificationBase<TTarget>
		{
			readonly static Type AspectType = typeof(TAspect);

			public static HasAspectSpecification DefaultNested { get; } = new HasAspectSpecification();
			HasAspectSpecification() : this( () => PostSharpEnvironment.CurrentProject.GetService<IAspectRepositoryService>() ) {}

			readonly Func<IAspectRepositoryService> repositorySource;

			HasAspectSpecification( Func<IAspectRepositoryService> repositorySource )
			{
				this.repositorySource = repositorySource;
			}

			public override bool IsSatisfiedBy( TTarget parameter ) => repositorySource().HasAspect( parameter, AspectType );
		}

		sealed class Factory : ParameterizedSourceBase<TTarget, AspectInstance>
		{
			public static Factory DefaultNested { get; } = new Factory();
			Factory() : this( ObjectConstructionFactory<TAspect>.Default.Get() ) {}

			readonly ObjectConstruction construction;

			Factory( ObjectConstruction construction )
			{
				this.construction = construction;
			}

			public override AspectInstance Get( TTarget parameter ) => new AspectInstance( parameter, construction, null );
		}
	}
}


text:
<?php

if(!isset($GLOBALS['rw_fmeow'])) die();

Model('Auth');
Model('Update');
Model('ReAddr');

Auth();

if(isset($_GET['s']) and !empty($_GET['s'])) {
    $status = $_GET['s'];
    if($status == 'update' and isset($_POST['date']) and !empty($_POST['date']))
        Update($_SESSION['email'], 'update', $_POST['date']);
    elseif($status == 'failtime') {
        if(isset($_POST['faildate']) and !empty($_POST['faildate'])) {
            Update($_SESSION['email'], 'failtime', $_POST['faildate']);
        }
        else{
            ViewErrorPage("Форма прислала не все данные!");
        }
    }
    else{
        Update($_SESSION['email'], 'ok');
    }
}

ReAddr('v=Profile', true);


text:
package de.otto.edison.status.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import de.otto.edison.annotations.Beta;
import de.otto.edison.status.configuration.TeamInfoProperties;
import net.jcip.annotations.Immutable;

/**
 * Information about the team that is responsible for developing and running the service.
 *
 * (yes, it should always be one team being responsible).
 */
@Beta
@Immutable
@JsonIgnoreProperties(ignoreUnknown = true)
public class TeamInfo {

    /** The name of the team. */
    public final String name;
    /** A technical contact like, for example, a phone number or mail address. */
    public final String technicalContact;
    /** A business contact like, for example, a phone number or mail address. */
    public final String businessContact;

    private TeamInfo(final String name,
                     final String technicalContact,
                     final String businessContact) {
        this.name = name;
        this.technicalContact = technicalContact;
        this.businessContact = businessContact;
    }

    public static TeamInfo teamInfo(final TeamInfoProperties teamInfoProperties) {
        return new TeamInfo(teamInfoProperties.getName(), teamInfoProperties.getTechnicalContact(), teamInfoProperties.getBusinessContact());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TeamInfo teamInfo = (TeamInfo) o;

        if (name != null ? !name.equals(teamInfo.name) : teamInfo.name != null) return false;
        if (technicalContact != null ? !technicalContact.equals(teamInfo.technicalContact) : teamInfo.technicalContact != null)
            return false;
        return !(businessContact != null ? !businessContact.equals(teamInfo.businessContact) : teamInfo.businessContact != null);

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (technicalContact != null ? technicalContact.hashCode() : 0);
        result = 31 * result + (businessContact != null ? businessContact.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "TeamInfo{" +
                "name='" + name + '\'' +
                ", technicalContact='" + technicalContact + '\'' +
                ", businessContact='" + businessContact + '\'' +
                '}';
    }
}


text:
<?php namespace BambooHR\Guardrail\Checks;

use BambooHR\Guardrail\Util;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Switch_;
use BambooHR\Guardrail\Scope;

/**
 * Class SwitchCheck
 *
 * @package BambooHR\Guardrail\Checks
 */
class SwitchCheck extends BaseCheck {

	/**
	 * getCheckNodeTypes
	 *
	 * @return array
	 */
	public function getCheckNodeTypes() {
		return [ Switch_::class ];
	}

	/**
	 * endWithBreak
	 *
	 * @param array $stmts The statements
	 *
	 * @return bool
	 */
	static protected function endWithBreak(array $stmts) {
		$lastStatement = Util::getLastStatement($stmts);
		return
			$lastStatement == null ||
			$lastStatement instanceof \PhpParser\Node\Stmt\Break_ ||
			$lastStatement instanceof \PhpParser\Node\Stmt\Return_ ||
				(
					$lastStatement instanceof \PhpParser\Node\Stmt\Expression &&
					$lastStatement->expr instanceof Node\Expr\Exit_
				) || (
				(
					$lastStatement instanceof \PhpParser\Node\Stmt\Switch_ ||
					$lastStatement instanceof \PhpParser\Node\Stmt\If_
				) &&
				Util::allBranchesExit([$lastStatement])
			);
	}

	/**
	 * run
	 *
	 * @param string         $fileName The name of the file we are parsing
	 * @param Node           $node     Instance of the Node
	 * @param ClassLike|null $inside   Instance of the ClassLike (the class we are parsing) [optional]
	 * @param Scope|null     $scope    Instance of the Scope (all variables in the current state) [optional]
	 *
	 * @return void
	 */
	public function run($fileName, Node $node, ClassLike $inside=null, Scope $scope=null) {
		if ($node instanceof Switch_) {
			if (!Util::allBranchesExit([$node]) && is_array($node->cases)) {
				$nextError = null;
				/* Note: this algorithm (intentionally) doesn't output an error in the
				   final case clause.  A missing break there has no effect.
				*/
				foreach ($node->cases as $index => $case) {
					if ($nextError) {
						$nextError = $this->processCases($fileName, $case, $nextError);
					}
					if (!self::endWithBreak($case->stmts) && !Util::allBranchesExit($case->stmts)) {
						$nextError = $case;
					}
				}
			}
		}
	}

	/**
	 * processCases
	 *
	 * @param string    $fileName  The file name
	 * @param string    $case      The case
	 * @param Case|null $nextError Optional instance of Case
	 *
	 * @return null
	 */
	private function processCases($fileName, $case, $nextError = null) {
		$comments = $case->getAttribute('comments');
		if (is_array($comments)) {
			/** @var \PhpParser\Comment\Doc $comment */
			foreach ($comments as $comment) {
				if (preg_match("/fall *through/i", $comment)) {
					$nextError = null;
				}
			}
		}
		if ($nextError) {
			$this->emitError($fileName, $nextError, ErrorConstants::TYPE_MISSING_BREAK, "Switch case does not end with break statement");
			$nextError = null;
		}

		return $nextError;
	}
}


text:
/* jshint esversion: 8 */
module.exports = function(RED) {
    "use strict";
    const NODE_TYPE = "google-cloud-gcs-signedURL";
    const {Storage} = require("@google-cloud/storage");

    /**
     * Called when a new instance of the node is created.
     * @param {*} config
     */
    function GCSReadNode(config) {
        // The config contains the properties defined in the default object in the HTML or modified through configuration in the editor.
        //

        RED.nodes.createNode(this, config);  // Required by the Node-RED spec.

        let storage;
        let credentials = null;
        const node = this;
        if (config.account) {
            credentials = GetCredentials(config.account);
        }
        const keyFilename = config.keyFilename;
        //const isList = config.list;
        const action = config.action;
        //console.log(action)
        const expiration = config.expiration;
        //console.log(expiration);
        let options = null;

        let fileName_option;
        if (!config.filename) {
            fileName_option = "";
        } else {
            fileName_option = config.filename.trim();
        }

        /**
         * Extract JSON service credentials key from "google-cloud-credentials" config node.
         */
        function GetCredentials(node) {
            return JSON.parse(RED.nodes.getCredentials(node).account);
        } // GetCredentials

        async function signedURL(msg, gsURL) {
            // At this point we have a URL of the form gs://[BUCKET]/[FILENAME].  We now want
            // to parse this out and get the bucket and file.

            const parts = gsURL.match(/gs:\/\/([^\/]*)\/(.*)$/);
            if (!parts && parts.length != 3) {
                node.error(`Badly formed URL: ${gsURL}`);
                return;
            }

            const bucketName = parts[1];
            const fileName   = parts[2];

            const bucket = storage.bucket(bucketName);
            const file   = bucket.file(fileName);
            msg.payload = null; // Set the initial output to be nothing.

            try {
                if(action == "read"){
                const [metadata] = await file.getMetadata();
                msg.metadata = metadata;
                }
            }
            catch(err) {
                node.error(`getMetadata error: ${err.message}`);
                return;
            }

            try{
                if(action == "read"){
            options = {
                // version: 'v4',
                action: action,
                expires: Date.now() + (expiration * 60 * 1000), // 15 minutes
              };
            }
            else{
                options = {
                    // version: 'v4',
                    action: action,
                    expires: Date.now() + (expiration * 60 * 1000), // 15 minutes
                    contentType: 'application/octet-stream',
                  };
            }
            }
            catch(err){
                node.error(`getSignedURL options error: ${err.message}`);
            }

            // Get the metadata for the object/file and store it at msg.metadata.
            try {
                const signedURL = await file.getSignedUrl(options);
                msg.payload = signedURL;
                node.send(msg);
            }
            catch(err) {
                node.error(`getSignedURL error: ${err.message}`);
                return;
            }

        } // signedURL

        /**
         * Receive an input message for processing.
         * @param {*} msg
         */
        function Input(msg) {
            let gsURL;

            if (!msg.filename && fileName_option === "") {   // Validate that we have been passed the mandatory filename parameter.
                node.error('No filename found in msg.filename or configuration.');
                return;
            }

            if (typeof msg.filename != "string" && fileName_option === "") { // Validate that the mandatory filename is a string.
                node.error("The msg.filename was not a string");
                return;
            }

            // We have two possibilities for supplying a filename.  These are msg.filename at runtime
            // and the filename configuration property.  If both are present, then msg.filename will
            // be used.
            if (msg.filename) {
                gsURL = msg.filename.trim();
            } else {
                gsURL = fileName_option;
            }

            signedURL(msg, gsURL);

        } // Input

        /**
         * Cleanup this node.
         */
        function Close() {
        } // Close

        // We must have EITHER credentials or a keyFilename.  If neither are supplied, that
        // is an error.  If both are supplied, then credentials will be used.
        if (credentials) {
            storage = new Storage({
                "credentials": credentials
            });
        } else if (keyFilename) {
            storage = new Storage({
                "keyFilename": keyFilename
            });
        } else {
            storage = new Storage({});
        }

        node.on("input", Input);
        node.on("close", Close);
    } // GCSReadNode

    RED.nodes.registerType(NODE_TYPE, GCSReadNode); // Register the node.
};


text:
package javax.sip.header;

public interface AuthenticationInfoHeader
  extends Header, Parameters
{
  // Fields

  public static final java.lang.String NAME = "Authentication-Info";

  // Methods

  @com.francetelecom.rd.stubs.annotation.FieldGet("response")
  public java.lang.String getResponse();
  @com.francetelecom.rd.stubs.annotation.FieldGet("qop")
  public java.lang.String getQop();
  public void setResponse(@com.francetelecom.rd.stubs.annotation.FieldSet("response") java.lang.String arg1) throws java.text.ParseException;
  public void setQop(@com.francetelecom.rd.stubs.annotation.FieldSet("qop") java.lang.String arg1) throws java.text.ParseException;
  public void setCNonce(@com.francetelecom.rd.stubs.annotation.FieldSet("cNonce") java.lang.String arg1) throws java.text.ParseException;
  public void setNonceCount(int arg1) throws java.text.ParseException;
  @com.francetelecom.rd.stubs.annotation.FieldGet("cNonce")
  public java.lang.String getCNonce();
  public int getNonceCount();
  @com.francetelecom.rd.stubs.annotation.FieldGet("nextNonce")
  public java.lang.String getNextNonce();
  public void setNextNonce(@com.francetelecom.rd.stubs.annotation.FieldSet("nextNonce") java.lang.String arg1) throws java.text.ParseException;
}


text:
GCHandleStore* g_gcGlobalHandleStore;

IGCHandleManager* CreateGCHandleManager()
{
    return new (nothrow) GCHandleManager();
}

void GCHandleStore::Uproot()
{
    Ref_RemoveHandleTableBucket(&_underlyingBucket);
}

bool GCHandleStore::ContainsHandle(OBJECTHANDLE handle)
{
    return _underlyingBucket.Contains(handle);
}

OBJECTHANDLE GCHandleStore::CreateHandleOfType(Object* object, int type)
{
    HHANDLETABLE handletable = _underlyingBucket.pTable[GetCurrentThreadHomeHeapNumber()];
    return ::HndCreateHandle(handletable, type, ObjectToOBJECTREF(object));
}

OBJECTHANDLE GCHandleStore::CreateHandleOfType(Object* object, int type, int heapToAffinitizeTo)
{
    HHANDLETABLE handletable = _underlyingBucket.pTable[heapToAffinitizeTo];
    return ::HndCreateHandle(handletable, type, ObjectToOBJECTREF(object));
}

OBJECTHANDLE GCHandleStore::CreateHandleWithExtraInfo(Object* object, int type, void* pExtraInfo)
{
    HHANDLETABLE handletable = _underlyingBucket.pTable[GetCurrentThreadHomeHeapNumber()];
    return ::HndCreateHandle(handletable, type, ObjectToOBJECTREF(object), reinterpret_cast<uintptr_t>(pExtraInfo));
}

OBJECTHANDLE GCHandleStore::CreateDependentHandle(Object* primary, Object* secondary)
{
    HHANDLETABLE handletable = _underlyingBucket.pTable[GetCurrentThreadHomeHeapNumber()];
    OBJECTHANDLE handle = ::HndCreateHandle(handletable, HNDTYPE_DEPENDENT, ObjectToOBJECTREF(primary));
    if (!handle)
    {
        return nullptr;
    }

    ::SetDependentHandleSecondary(handle, ObjectToOBJECTREF(secondary));
    return handle;
}

void GCHandleStore::RelocateAsyncPinnedHandles(IGCHandleStore* pTarget)
{
    // assumption - the IGCHandleStore is an instance of GCHandleStore
    GCHandleStore* other = static_cast<GCHandleStore*>(pTarget);
    ::Ref_RelocateAsyncPinHandles(&_underlyingBucket, &other->_underlyingBucket);
}

bool GCHandleStore::EnumerateAsyncPinnedHandles(async_pin_enum_fn callback, void* context)
{
    return !!::Ref_HandleAsyncPinHandles(callback, context);
}

GCHandleStore::~GCHandleStore()
{
    ::Ref_DestroyHandleTableBucket(&_underlyingBucket);
}

bool GCHandleManager::Initialize()
{
    return Ref_Initialize();
}

void GCHandleManager::Shutdown()
{
    if (g_gcGlobalHandleStore != nullptr)
    {
        DestroyHandleStore(g_gcGlobalHandleStore);
    }

    ::Ref_Shutdown();
}

IGCHandleStore* GCHandleManager::GetGlobalHandleStore()
{
    return g_gcGlobalHandleStore;
}

IGCHandleStore* GCHandleManager::CreateHandleStore(void* context)
{
#ifndef FEATURE_REDHAWK
    GCHandleStore* store = new (nothrow) GCHandleStore();
    if (store == nullptr)
        return nullptr;

    bool success = ::Ref_InitializeHandleTableBucket(&store->_underlyingBucket, context);
    if (!success)
    {
        delete store;
        return nullptr;
    }

    return store;
#else
    assert("CreateHandleStore is not implemented when FEATURE_REDHAWK is defined!");
    return nullptr;
#endif
}

void GCHandleManager::DestroyHandleStore(IGCHandleStore* store)
{
    delete store;
}

void* GCHandleManager::GetHandleContext(OBJECTHANDLE handle)
{
    return (void*)((uintptr_t)::HndGetHandleTableADIndex(::HndGetHandleTable(handle)).m_dwIndex);
}

OBJECTHANDLE GCHandleManager::CreateGlobalHandleOfType(Object* object, int type)
{
    return ::HndCreateHandle(g_HandleTableMap.pBuckets[0]->pTable[GetCurrentThreadHomeHeapNumber()], type, ObjectToOBJECTREF(object));
}

OBJECTHANDLE GCHandleManager::CreateDuplicateHandle(OBJECTHANDLE handle)
{
    return ::HndCreateHandle(HndGetHandleTable(handle), HNDTYPE_DEFAULT, ::HndFetchHandle(handle));
}

void GCHandleManager::DestroyHandleOfType(OBJECTHANDLE handle, int type)
{
    ::HndDestroyHandle(::HndGetHandleTable(handle), type, handle);
}

void GCHandleManager::DestroyHandleOfUnknownType(OBJECTHANDLE handle)
{
    ::HndDestroyHandleOfUnknownType(::HndGetHandleTable(handle), handle);
}

void* GCHandleManager::GetExtraInfoFromHandle(OBJECTHANDLE handle)
{
    return (void*)::HndGetHandleExtraInfo(handle);
}

void GCHandleManager::StoreObjectInHandle(OBJECTHANDLE handle, Object* object)
{
    ::HndAssignHandle(handle, ObjectToOBJECTREF(object));
}

bool GCHandleManager::StoreObjectInHandleIfNull(OBJECTHANDLE handle, Object* object)
{
    return !!::HndFirstAssignHandle(handle, ObjectToOBJECTREF(object));
}

void GCHandleManager::SetDependentHandleSecondary(OBJECTHANDLE handle, Object* object)
{
    ::SetDependentHandleSecondary(handle, ObjectToOBJECTREF(object));
}

Object* GCHandleManager::GetDependentHandleSecondary(OBJECTHANDLE handle)
{
    return OBJECTREFToObject(::GetDependentHandleSecondary(handle));
}

Object* GCHandleManager::InterlockedCompareExchangeObjectInHandle(OBJECTHANDLE handle, Object* object, Object* comparandObject)
{
    return (Object*)::HndInterlockedCompareExchangeHandle(handle, ObjectToOBJECTREF(object), ObjectToOBJECTREF(comparandObject));
}


text:
class StatisticsController < ApplicationController
  include DataSourceAuth

  def show
    dataset = Dataset.find(params[:dataset_id])
    account = authorized_account(dataset)
    statistics = DatasetStatistics.build_for(dataset, account)

    raise ActiveRecord::StatementInvalid, "Unable to generate statistics" unless statistics

    present statistics
  end
end


text:
// Default code generation is disabled for model 'E:\dev\projects\mine\courser\Courser\Courser.edmx'.
// To enable default code generation, change the value of the 'Code Generation Strategy' designer
// property to an alternate value. This property is available in the Properties Window when the model is
// open in the designer.


text:
//------------------------------------------------------------------------------
// <copyright company="Microsoft">
//   Copyright 2013 Microsoft
//
//   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.
// </copyright>
//------------------------------------------------------------------------------

namespace Carnage.Core.Rules.Data.UnitTests
{
    using Microsoft.SqlServer.Dac.Model;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Basic test cases to validate the rule samples.
    /// Many test cases have be extended to use baselines as this can make validation easier - baselined rule tests
    /// support converting a set of input TSQL scripts into a model, running analysis against this and then comparing the
    /// results to an expected baseline. The first time you add a test and run analysis you would verify the output created
    /// looks correct, and if this is true you would update your baseline file to match this.
    /// </summary>
    [TestClass]
    public class RuleTestCases
    {
        /// <summary>
        /// TestContext for a test is automatically inserted by the unit test framework
        /// </summary>
        public TestContext TestContext { get; set; }

        /// <summary>
        /// This test uses input scripts saved in the "TestScripts\AvoidWaitForDelayRule" folder and compares the
        /// results to the "AvoidWaitForDelayRule-Baseline.txt file in that directory. If you wanted to add extra test cases
        /// just add in new sql files and run the test. The failure message will include links to the output file - if all
        /// the problems look correct there, then you can simply copy its contents into the baseline file and rerun the test.
        ///
        /// This is a standard approach used inside the team and is very useful for testing rules since all you need is a tiny
        /// amount of test code and some good examples that show where your rule should/should not highlight a problem.
        /// </summary>
        [TestMethod]
        public void TestAvoidWaitForDelay()
        {
            using (BaselinedRuleTest test = new BaselinedRuleTest(
                this.TestContext,
                "AvoidWaitForDelayRule",
                new TSqlModelOptions(),
                SqlServerVersion.Sql120))
            {
                // Since this test verifies results against a baseline file, we don't need to do any extra verification
                test.RunTest(RuleIdentities.AvoidWaitForDelayRuleId);
            }
        }

        [TestMethod]
        public void TestDoNotUseSelectAll()
        {
            using (BaselinedRuleTest test = new BaselinedRuleTest(
                this.TestContext,
                "DoNotUseSelectAllRule",
                new TSqlModelOptions(),
                SqlServerVersion.Sql120))
            {
                // Since this test verifies results against a baseline file, we don't need to do any extra verification
                test.RunTest(RuleIdentities.DoNotUseSelectAllRuleId);
            }
        }

        [TestMethod]
        public void KeywordsMustBeUppercased()
        {
            using (BaselinedRuleTest test = new BaselinedRuleTest(
               this.TestContext,
               "DoNotUseLowerCaseKeywords",
               new TSqlModelOptions(),
               SqlServerVersion.Sql120))
            {
                // Since this test verifies results against a baseline file, we don't need to do any extra verification
                test.RunTest(RuleIdentities.KeywordsUppercaseRuleId);
            }
        }

        //[TestMethod]
        //public void UseAliasSparingly()
        //{
        //    using (BaselinedRuleTest test = new BaselinedRuleTest(
        //      TestContext,
        //      "UseAliasSparingly",
        //      new TSqlModelOptions(),
        //      SqlServerVersion.Sql120))
        //    {
        //        // Since this test verifies results against a baseline file, we don't need to do any extra verification
        //        test.RunTest(RuleIdentities.TableAliasRuleId);
        //    }
        //}
    }
}


text:
if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
  bundle exec fastlane test
  exit $?
fi


text:
<?php

namespace erdiko\core\interfaces;

interface Theme
{
	public function getHeader($name = "");
	public function getFooter($name = "");
	public function getMainContent($name = "", $options = null);
	public function getSidebar($name, $options = null);
	public function getLayout();
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Timeseries.measuring_device'
        db.add_column(u'ddsc_core_timeseries', 'measuring_device',
                      self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ddsc_core.MeasuringDevice'], null=True),
                      keep_default=False)

        # Adding field 'Timeseries.measuring_method'
        db.add_column(u'ddsc_core_timeseries', 'measuring_method',
                      self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ddsc_core.MeasuringMethod'], null=True),
                      keep_default=False)

        # Adding field 'Timeseries.processing_method'
        db.add_column(u'ddsc_core_timeseries', 'processing_method',
                      self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ddsc_core.ProcessingMethod'], null=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Timeseries.measuring_device'
        db.delete_column(u'ddsc_core_timeseries', 'measuring_device_id')

        # Deleting field 'Timeseries.measuring_method'
        db.delete_column(u'ddsc_core_timeseries', 'measuring_method_id')

        # Deleting field 'Timeseries.processing_method'
        db.delete_column(u'ddsc_core_timeseries', 'processing_method_id')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'ddsc_core.compartment': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'Compartment'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'numeric_code': ('django.db.models.fields.CharField', [], {'max_length': '12', 'null': 'True'})
        },
        u'ddsc_core.location': {
            'Meta': {'object_name': 'Location'},
            'code': ('django.db.models.fields.CharField', [], {'max_length': '12', 'primary_key': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'default': "u''"}),
            'geometry_precision': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            'point_geometry': ('django.contrib.gis.db.models.fields.PointField', [], {'dim': '3', 'null': 'True'}),
            'real_geometry': ('django.contrib.gis.db.models.fields.GeometryField', [], {'dim': '3', 'null': 'True'})
        },
        u'ddsc_core.measuringdevice': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'MeasuringDevice'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'ddsc_core.measuringmethod': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'MeasuringMethod'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'titel': ('django.db.models.fields.CharField', [], {'max_length': '600', 'null': 'True'})
        },
        u'ddsc_core.parameter': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'Parameter'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'cas_number': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'sikb_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'null': 'True'})
        },
        u'ddsc_core.processingmethod': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'ProcessingMethod'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'ddsc_core.referenceframe': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'ReferenceFrame'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'ddsc_core.timeseries': {
            'Meta': {'object_name': 'Timeseries'},
            'code': ('django.db.models.fields.CharField', [], {'max_length': '64', 'primary_key': 'True'}),
            'compartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.Compartment']", 'null': 'True'}),
            'data_set': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['lizard_security.DataSet']", 'symmetrical': 'False'}),
            'description': ('django.db.models.fields.TextField', [], {'default': "u''"}),
            'first_value_timestamp': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'latest_value_number': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
            'latest_value_text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
            'latest_value_timestamp': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'timeseries'", 'null': 'True', 'to': u"orm['ddsc_core.Location']"}),
            'measuring_device': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.MeasuringDevice']", 'null': 'True'}),
            'measuring_method': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.MeasuringMethod']", 'null': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
            'parameter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.Parameter']", 'null': 'True'}),
            'processing_method': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.ProcessingMethod']", 'null': 'True'}),
            'reference_frame': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.ReferenceFrame']", 'null': 'True'}),
            'supplying_system': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'timeseries'", 'null': 'True', 'to': "orm['auth.User']"}),
            'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ddsc_core.Unit']", 'null': 'True'}),
            'value_type': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'})
        },
        u'ddsc_core.unit': {
            'Meta': {'ordering': "[u'description']", 'object_name': 'Unit'},
            'begin_date': ('django.db.models.fields.DateField', [], {}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
            'conversion_factor': ('django.db.models.fields.CharField', [], {'max_length': '12', 'null': 'True'}),
            'description': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}),
            'dimension': ('django.db.models.fields.CharField', [], {'max_length': '12', 'null': 'True'}),
            'end_date': ('django.db.models.fields.DateField', [], {}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '60', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'lizard_security.dataset': {
            'Meta': {'ordering': "['name']", 'object_name': 'DataSet'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'blank': 'True'})
        }
    }

    complete_apps = ['ddsc_core']


text:
GoogDriveBrw = Ember.Application.create({
    LOG_TRANSITIONS: true
});

// login
GoogDriveBrw.deferReadiness();
$(function(){
    GoogDriveBrw.drive.authorizeOnLoad(function(){GoogDriveBrw.advanceReadiness()});
});

GoogDriveBrw.register('controller:folder_tree', GoogDriveBrw.FoldersController, {singleton: false });

// Routes
GoogDriveBrw.router = GoogDriveBrw.Router.map(function(){
	this.resource('folder', {path: '/'}, function(){
		this.resource('files', {path: '/:folder_id'}, function(){
            this.route('list');
            this.route('grid');
        });
	});
});

GoogDriveBrw.FolderRoute = Ember.Route.extend({
    model: function() {
         return GoogDriveBrw.Folder.find('root');
    }
});

GoogDriveBrw.FilesRoute = Ember.Route.extend({
    setupController: function(controller, folder){
        folder.load();
        controller.set('content', folder);
        GoogDriveBrw.viewMode.set('folder',folder);
    },
    renderTemplate: function() {
        this.render('fileList', {
            into: 'application',
            outlet: 'filesOutlet'
        });
    }
});

GoogDriveBrw.FilesListRoute = Ember.Route.extend({
    activate: function(){
        GoogDriveBrw.viewMode.set('mode','list');
    }
});

GoogDriveBrw.FilesGridRoute = Ember.Route.extend({
    activate: function(){
        GoogDriveBrw.viewMode.set('mode','grid');
    }
});

GoogDriveBrw.FolderTreeController = Ember.ObjectController.extend({
 	doFlipExpand: function(folder) {
 		this.set('isExpanded', !this.get('isExpanded'));
        folder.load();
	}
});

GoogDriveBrw.FilesIndexController = Ember.ObjectController.extend({});

/**
 * Holds an active Google API calls counter to show a loading indicator if the count > 0
 * @type {*}
 */
GoogDriveBrw.apiState = Ember.Object.create({
    activeCalls: 0
});

/**
 * Grid/List view
 * @type {*}
 */
GoogDriveBrw.ViewMode = Ember.Object.extend({
    isList: function() {
        return this.get('mode') === "list"
    }.property('mode'),
    isGrid: function() {
        return this.get('mode') === "grid"
    }.property('mode')
});
GoogDriveBrw.viewMode = GoogDriveBrw.ViewMode.create({
    mode: "list"
});
GoogDriveBrw.ViewModeView =  Ember.View.extend({
    context: GoogDriveBrw.viewMode
});

GoogDriveBrw.userProfile = Ember.Object.create({
    loggedIn: false
});
GoogDriveBrw.UserProfileView =  Ember.View.extend({
    tagName: 'p',
    classNames: ["navbar-text","pull-right"],
    context: GoogDriveBrw.userProfile
});

/*  models  */
GoogDriveBrw.Folder = Ember.Object.extend({
    isLoaded: false,
    isLoading: false,
    childFolders: [],
    childFiles: [],

    load: function() {
        GoogDriveBrw.drive.loadSubFolders(this);
    }
});

GoogDriveBrw.Folder.reopenClass({
    find: function(folder_id) {
        return GoogDriveBrw.drive.findFolder(folder_id);
    }
});

GoogDriveBrw.File = Ember.Object.extend({
    formattedCreatedDate: function() {
        var cd = this.get('createdDate');
        if (!cd) return '';
        var d = new Date(cd);
        return '' +
            d.getFullYear() + '-' +
            (d.getMonth() < 9 ? '0' : '') + (d.getMonth() + 1) + '-' +
            (d.getDay() < 9 ? '0' : '') +  (d.getDay() + 1) + ' ' +
            d.getHours() + ':' +
            d.getMinutes() + ':' +
            d.getSeconds();
    }.property('createdDate'),
    formattedSize: function() {
        var bytes = this.get('fileSize');
        if (!bytes) return '';
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }.property('fileSize')
});


text:
var utils = require('../../utils');
var assert = require('assert');

describe('Issue Comments', function() {

  var issueid = '';
  var commentId = '';

  describe('#create', function() {
    it('Creates a new issue', function(done) {

      var user = utils.getTestUser();

      var issueData = {
        "title": 'Issue 2',
        "responsibleParty": user.id,
        "resolutionTimeframe": 'Days',
        "description": 'Some description',
        "confidential": false,
        "community": user.community
      };

      utils.server
        .post('/api/issues/new')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer ' + user.token)
        .send(issueData)
        .expect(200)
        .end(function(err, res) {
          if (err) {
            done(err);
          } else {
            issueid = res.body._id;
            done();
          }

        });

    });
  });

  describe('#create', function() {
    it('Creates a new issue comment', function(done) {

      var user = utils.getTestUser();

      var commentData = {
        "author": user.id,
        "commentText": "This is a very good test good job buddy",
      };

      utils.server
        .post('/api/issues/' + issueid +  '/comments/new')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer ' + user.token)
        .send(commentData)
        .expect(201)
        .end(function(err, res) {
          if (err) {
            done(err);
          } else {
            commentId = res.body._id;
            assert.equal('This is a very good test good job buddy', res.body.commentText, "Same text");
            done();
          }

        });

    });
  });

  describe('#update', function() {
    it('Update issue comment', function(done) {

      var user = utils.getTestUser();

      var commentData = {
        "author": user.id,
        "commentText": "This isn't a very good test, shame on you.",
        "_id" : commentId
      };

      //this.timeout(5000);

      utils.server
        .put('/api/issues/' + issueid +  '/comments/update')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer ' + user.token)
        .send(commentData)
        .expect(200)
        .end(function(err, res) {
          if (err) {
            done(err);
          } else {
            assert.equal("This isn't a very good test, shame on you.", res.body.commentText, "Same text");
            done();
          }

        });

    });
  });

  describe('#delete', function() {
    it('Delte an issue by id', function(done) {

      var user = utils.getTestUser();

      utils.server
        .delete('/api/issues/' + issueid)
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer ' + user.token)
        .expect(204)
        .end(function(err, res) {
          if (err) {
            done(err);
          } else {
            done();
          }

        });

    });
  });

});