text:
namespace ConoHaNet.Objects.Servers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using Newtonsoft.Json;
    using Providers;

    ///
    /// Extends <see cref="SimpleServer"/> with detailed information about a server.
    ///
    /// <seealso cref="IComputeProvider.GetDetails"/>
    /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Get_Server_Details-d1e2623.html">Get Server Details (OpenStack Compute API v2 and Extensions Reference)</seealso>
    /// <threadsafety static="true" instance="false"/>
    [JsonObject(MemberSerialization.OptIn)]
    public class Server : SimpleServer
    {
        private SimpleServerImage _image;

        ///
        /// Gets the disk configuration used for creating, rebuilding, or resizing the server.
        /// If the value was not explicitly specified in the create, rebuild, or resize request,
        /// the server inherits the value from the image it was created from.
        ///
        /// <remarks>
        /// <note>This property is defined by the Rackspace-specific Disk Configuration Extension to the OpenStack Compute API.</note>
        /// </remarks>
        /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute">Disk Configuration Extension (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso>
        [JsonProperty("OS-DCF:diskConfig")]
        public DiskConfiguration DiskConfig { get; private set; }

        ///
        /// Gets the power state for the server.
        ///
        /// <remarks>
        /// <note>This property is defined by the Rackspace-specific Extended Status Extension to the OpenStack Compute API.</note>
        /// </remarks>
        /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#power_state">OS-EXT-STS:power_state (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso>
        [JsonProperty("OS-EXT-STS:power_state")]
        public PowerState PowerState { get; private set; }

        ///
        /// Gets the task state for the server.
        ///
        /// <remarks>
        /// <note>This property is defined by the Rackspace-specific Extended Status Extension to the OpenStack Compute API.</note>
        /// </remarks>
        /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#task_state">OS-EXT-STS:task_state (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso>
        [JsonProperty("OS-EXT-STS:task_state")]
        public TaskState TaskState { get; private set; }

        ///
        /// Gets the virtual machine (VM) state for the server.
        ///
        /// <remarks>
        /// <note>This property is defined by the Rackspace-specific Extended Status Extension to the OpenStack Compute API.</note>
        /// </remarks>
        /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#vm_state">OS-EXT-STS:vm_state (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso>
        [JsonProperty("OS-EXT-STS:vm_state")]
        public VirtualMachineState VMState { get; private set; }

        ///
        /// Gets the public IP version 4 access address.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("accessIPv4")]
        public string AccessIPv4 { get; private set; }

        ///
        /// Gets the public IP version 6 access address.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("accessIPv6")]
        public string AccessIPv6 { get; private set; }

        ///
        /// Gets the user ID for the server.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("user_id")]
        public string UserId { get; private set; }

        ///
        /// Gets basic information about the image the server was created from.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("image")]
        public SimpleServerImage Image
        {
            get
            {
                // this is handled in the getter because the Provider/Region/Identity
                // properties of the current instance might not be set at the point
                // this property is set
                if (_image != null)
                {
                    _image.Provider = Provider;
                    _image.Region = Region;
                    _image.Identity = Identity;
                }

                return _image;
            }

            private set
            {
                _image = value;
            }
        }

        ///
        /// Gets the server status.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("status")]
        public ServerState Status
        {
            get;
            private set;
        }

        ///
        /// Gets basic information about the flavor for the server.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("flavor")]
        public Flavor Flavor { get; private set; }

        ///
        /// Gets the public and private IP addresses for the server.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("addresses")]
        public ServerAddresses Addresses { get; private set; }

        ///
        /// Gets the time stamp for the creation date.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("created")]
        public DateTimeOffset Created { get; private set; }

        ///
        /// Gets the host ID for the server.
        ///
        /// <remarks>
        /// The compute provisioning algorithm has an anti-affinity property that attempts
        /// to spread customer VMs across hosts. Under certain situations, VMs from the
        /// same customer might be placed on the same host. The Host ID represents the host
        /// your server runs on and can be used to determine this scenario if it is relevant
        /// to your application.
        ///
        /// <para><see cref="HostId"/> is unique per account and is not globally unique.</para>
        /// </remarks>
        [JsonProperty("hostId")]
        public string HostId { get; private set; }

        ///
        /// Gets the build completion progress, as a percentage.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        /// <value>A percentage from 0 to 100 (inclusive) representing the build completion progress.</value>
        [JsonProperty("progress")]
        public int Progress { get; private set; }

        ///
        /// Gets the tenant ID of the server.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        /// <seealso cref="Tenant.Id"/>
        [JsonProperty("tenant_id")]
        public string TenantId { get; private set; }

        ///
        /// Gets the time stamp for the last update.
        /// <note type="warning">The value of this property is not defined by OpenStack, and may not be consistent across vendors.</note>
        ///
        [JsonProperty("updated")]
        public DateTimeOffset Updated { get; private set; }

        /// <inheritdoc/>
        protected override void UpdateThis(ServerBase server)
        {
            if (server == null)
                throw new ArgumentNullException("server");

            base.UpdateThis(server);

            var details = server as Server;

            if (details == null)
                return;

            DiskConfig = details.DiskConfig;
            PowerState = details.PowerState;
            TaskState = details.TaskState;
            VMState = details.VMState;
            AccessIPv4 = details.AccessIPv4;
            AccessIPv6 = details.AccessIPv6;
            UserId = details.UserId;
            Image = details.Image;
            Status = details.Status;
            Flavor = details.Flavor;
            Addresses = details.Addresses;
            Created = details.Created;
            HostId = details.HostId;
            Progress = details.Progress;
            TenantId = details.TenantId;
            Updated = details.Updated;
        }

        ///
        /// Lists the volume attachments for the server.
        ///
        /// <returns>A collection of <see cref="ServerVolume"/> objects describing the volumes attached to the server.</returns>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.ListServerVolumes"/>
        /// <seealso href="http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Volume_Attachments.html">List Volume Attachments (Rackspace Next Generation Cloud Servers Developer Guide - API v2)</seealso>
        public IEnumerable<ServerVolume> GetVolumes()
        {
            return Provider.ListServerVolumes(Id, Region, Identity);
        }
        ///
        /// Gets the metadata associated with the server.
        ///
        /// <returns>A <see cref="Metadata"/> object containing the metadata associated with the server.</returns>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.ListServerMetadata"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/List_Metadata-d1e5089.html">List Metadata (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public Metadata GetMetadata()
        {
            //return Provider.ListServerMetadata(Id, Region, Identity);
            return this.ExtensionData["metadata"] != null ? this.ExtensionData["metadata"].ToObject<Metadata>() : null;
        }

        ///
        /// Sets the metadata associated with the server, replacing any existing metadata.
        ///
        /// <param name="metadata">The metadata to associate with the server.</param>
        /// <returns><see langword="true"/> if the metadata for the server was successfully updated; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="metadata"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="metadata"/> contains any values with empty keys.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.SetServerMetadata"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Create_or_Replace_Metadata-d1e5358.html">Set Metadata (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool SetMetadata(Metadata metadata)
        {
            return Provider.SetServerMetadata(Id, metadata, Region, Identity);
        }

        ///
        /// Updates the metadata for the server.
        ///
        /// <remarks>
        /// For each item in <paramref name="metadata"/>, if the key exists, the value is updated; otherwise, the item is added.
        /// </remarks>
        /// <param name="metadata">The server metadata to update.</param>
        /// <returns><see langword="true"/> if the metadata for the server was successfully updated; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="metadata"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="metadata"/> contains any values with empty keys.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.UpdateServerMetadata"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Update_Metadata-d1e5208.html">Update Metadata (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool AddMetadata(Metadata metadata)
        {
            return Provider.UpdateServerMetadata(Id, metadata, Region, Identity);
        }

        ///
        /// Adds or updates the value for the specified metadata item.
        ///
        /// <param name="key">The metadata key.</param>
        /// <param name="value">The new value for the metadata item.</param>
        /// <returns><see langword="true"/> if the metadata for the server was successfully updated; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="key"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="value"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">If <paramref name="key"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.SetServerMetadataItem"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Create_or_Update_a_Metadata_Item-d1e5633.html">Set Metadata Item (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool AddMetadata(string key, string value)
        {
            return Provider.SetServerMetadataItem(Id, key, value, Region, Identity);
        }

        ///
        /// Updates the metadata for the server.
        ///
        /// <remarks>
        /// For each item in <paramref name="metadata"/>, if the key exists, the value is updated; otherwise, the item is added.
        /// </remarks>
        /// <param name="metadata">The server metadata to update.</param>
        /// <returns><see langword="true"/> if the metadata for the server was successfully updated; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="metadata"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="metadata"/> contains any values with empty keys.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.UpdateServerMetadata"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Update_Metadata-d1e5208.html">Update Metadata (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool UpdateMetadata(Metadata metadata)
        {
            return Provider.UpdateServerMetadata(Id, metadata, Region, Identity);
        }

        ///
        /// Deletes the specified metadata items from the server.
        ///
        /// <remarks>
        /// <note>
        /// This method ignores the values in <paramref name="metadata"/>. Metadata items are
        /// removed whether or not their current values match those in <paramref name="metadata"/>.
        /// </note>
        /// </remarks>
        /// <param name="metadata">A collection of metadata items to delete.</param>
        /// <returns><see langword="true"/> if all of the metadata item were removed; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="metadata"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="metadata"/> contains a null or empty key.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.DeleteServerMetadataItem"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Delete_Metadata_Item-d1e5790.html">Delete Metadata Item (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool DeleteMetadata(Metadata metadata)
        {
            if (metadata == null)
                throw new ArgumentNullException("metadata");

            bool success = true;
            foreach (var item in metadata)
            {
                if (string.IsNullOrEmpty(item.Key))
                    throw new ArgumentException("metadata cannot contain any empty keys");

                success &= DeleteMetadataItem(item.Key);
            }

            return success;
        }

        ///
        /// Deletes the specified metadata item from the server.
        ///
        /// <param name="key">The metadata key.</param>
        /// <returns><see langword="true"/> if the metadata item was removed; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="key"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="key"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.DeleteServerMetadataItem"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Delete_Metadata_Item-d1e5790.html">Delete Metadata Item (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool DeleteMetadataItem(string key)
        {
            return Provider.DeleteServerMetadataItem(Id, key, Region, Identity);
        }

        ///
        /// Sets the value for the specified metadata item. If the key already exists, it is updated; otherwise, a new metadata item is added.
        ///
        /// <param name="key">The metadata key.</param>
        /// <param name="value">The new value for the metadata item.</param>
        /// <returns><see langword="true"/> if the metadata for the server was successfully updated; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="key"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="value"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">If <paramref name="key"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.SetServerMetadataItem"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Create_or_Update_a_Metadata_Item-d1e5633.html">Set Metadata Item (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool UpdateMetadataItem(string key, string value)
        {
            return Provider.SetServerMetadataItem(Id, key, value, Region, Identity);
        }

        ///
        /// Lists all networks and server addresses associated with a server.
        ///
        /// <returns>A <see cref="ServerAddresses"/> object containing the list of network addresses for the server.</returns>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.ListAddresses"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/List_Addresses-d1e3014.html">List Addresses (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public ServerAddresses ListAddresses()
        {
            return Provider.ListAddresses(Id, Region, Identity);
        }

        ///
        /// Lists addresses for the server associated with the specified network.
        ///
        /// <param name="networkLabel">The network label. This is obtained from <see cref="CloudNetwork.Label">CloudNetwork.Label</see>.</param>
        /// <returns>A collection of <see cref="IPAddress"/> containing the network addresses associated with the server on the specified network.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="networkLabel"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="networkLabel"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.ListAddressesByNetwork"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/List_Addresses_by_Network-d1e3118.html">List Addresses by Network (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public IEnumerable<IPAddress> ListAddressesByNetwork(string networkLabel)
        {
            if (networkLabel == null)
                throw new ArgumentNullException("networkLabel");
            if (string.IsNullOrEmpty(networkLabel))
                throw new ArgumentException("networkLabel cannot be empty");

            return Provider.ListAddressesByNetwork(Id, networkLabel, Region, Identity);
        }

        ///
        /// Creates a new snapshot image for the server at its current state.
        ///
        /// <remarks>
        /// The server snapshot process is completed asynchronously. To wait for the image
        /// to be completed, you may call <see cref="SimpleServerImage.WaitForActive"/> on the
        /// returned image.
        /// </remarks>
        /// <param name="imageName">Name of the new image.</param>
        /// <param name="metadata">The metadata to associate to the new image.</param>
        /// <returns>A <see cref="ServerImage"/> object containing the details of the new image if the image creation process was successfully started; otherwise, <see langword="null"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="imageName"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="imageName"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Create_Image-d1e4655.html">Create Image (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public ServerImage Snapshot(string imageName, Metadata metadata = null)
        {
            if (!Provider.CreateImage(Id, imageName, metadata, Region, Identity))
                return null;

            return Provider.ListImagesWithDetails(Id, imageName, imageType: ImageType.Snapshot)
                        .OrderByDescending(i => i.Created)
                        .FirstOrDefault();
        }

        ///
        /// Marks the server for asynchronous deletion.
        ///
        /// <remarks>
        /// The server deletion operation is completed asynchronously. The <see cref="ServerBase.WaitForDeleted"/>
        /// method may be used to block execution until the server is finally deleted.
        /// </remarks>
        /// <returns><see langword="true"/> if the server was successfully marked for deletion; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.DeleteServer"/>
        /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Delete_Server-d1e2883.html">Delete Server (OpenStack Compute API v2 and Extensions Reference)</seealso>
        public bool Delete()
        {
            return Provider.DeleteServer(Id, Region, Identity);
        }

        ///
        /// Lists the virtual interfaces for the server.
        ///
        /// <returns>A collection of <see cref="VirtualInterface"/> objects describing the virtual interfaces for the server.</returns>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.ListVirtualInterfaces"/>
        /// <seealso href="http://docs.rackspace.com/networks/api/v2/cn-devguide/content/list_virt_interfaces.html">List Virtual Interfaces (Rackspace Cloud Networks Developer Guide - OpenStack Networking API v2)</seealso>
        public IEnumerable<VirtualInterface> ListVirtualInterfaces()
        {
            return Provider.ListVirtualInterfaces(Id, Region, Identity);
        }

        ///
        /// Creates a virtual interface for the specified network and attaches the network to the server.
        ///
        /// <param name="networkId">The network ID. This is obtained from <see cref="CloudNetwork.Id">CloudNetwork.Id</see>.</param>
        /// <returns>A <see cref="VirtualInterface"/> object containing the details of the newly-created virtual network.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="networkId"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="networkId"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.CreateVirtualInterface"/>
        /// <seealso href="http://docs.rackspace.com/networks/api/v2/cn-devguide/content/api_create_virtual_interface.html">Create Virtual Interface (Rackspace Cloud Networks Developer Guide - OpenStack Networking API v2)</seealso>
        public VirtualInterface CreateVirtualInterface(string networkId)
        {
            return Provider.CreateVirtualInterface(Id, networkId, Region, Identity);
        }

        ///
        /// Deletes the specified virtual interface from the server.
        ///
        /// <param name="virtualInterfaceId">The virtual interface ID. This is obtained from <see cref="VirtualInterface.Id">VirtualInterface.Id</see>.</param>
        /// <returns><see langword="true"/> if the virtual interface was successfully removed from the server; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="virtualInterfaceId"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="virtualInterfaceId"/> is empty.</exception>
        /// <exception cref="net.openstack.Core.Exceptions.Response.ResponseException">If the REST API request failed.</exception>
        /// <seealso cref="IComputeProvider.DeleteVirtualInterface"/>
        /// <seealso href="http://docs.rackspace.com/networks/api/v2/cn-devguide/content/delete_virt_interface_api.html">Delete Virtual Interface (Rackspace Cloud Networks Developer Guide - OpenStack Networking API v2)</seealso>
        public bool DeleteVirtualInterface(string virtualInterfaceId)
        {
            return Provider.DeleteVirtualInterface(Id, virtualInterfaceId, Region, Identity);
        }

        //public IEnumerable<string> GetServerGlobalIps()
        //{
        //    var ports = Provider.ListInterfaceAttachments(Id, Region);
        //    List<string> ips = new List<string>();
        //    foreach (var port in ports)
        //        foreach (var ip in port.FixedIPs)
        //        {
        //            if (ip.IpAddress.Contains(".")
        //                && !ip.IpAddress.StartsWith("10.")
        //                && !ip.IpAddress.StartsWith("172.")
        //                && !ip.IpAddress.StartsWith("192.168."))
        //                ips.Add(ip.IpAddress);
        //        }
        //    return ips;
        //}

    }
}


text:
/**
 * @preserve
 * Project: Bootstrap Hover Dropdown
 * Author: Cameron Spear
 * Version: v2.1.3
 * Contributors: Mattia Larentis
 * Dependencies: Bootstrap's Dropdown plugin, jQuery
 * Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
 * License: MIT
 * Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
 */
! function (e, n) {
	var o = e();
	e.fn.dropdownHover = function (t) {
		return "ontouchstart" in document ? this : (o = o.add(this.parent()), this.each(function () {
			function r() {
				n.clearTimeout(a), n.clearTimeout(i), i = n.setTimeout(function () {
					o.find(":focus").blur(), f.instantlyCloseOthers === !0 && o.removeClass("open"), n.clearTimeout(i), d.attr("aria-expanded", "true"), s.addClass("open"), d.trigger(l)
				}, f.hoverDelay)
			}
			var a, i, d = e(this),
				s = d.parent(),
				u = {
					delay: 500,
					hoverDelay: 0,
					instantlyCloseOthers: !0
				},
				h = {
					delay: e(this).data("delay"),
					hoverDelay: e(this).data("hover-delay"),
					instantlyCloseOthers: e(this).data("close-others")
				},
				l = "show.bs.dropdown",
				c = "hide.bs.dropdown",
				f = e.extend(!0, {}, u, t, h);
			s.hover(function (e) {
				return s.hasClass("open") || d.is(e.target) ? void r(e) : !0
			}, function () {
				n.clearTimeout(i), a = n.setTimeout(function () {
					d.attr("aria-expanded", "false"), s.removeClass("open"), d.trigger(c)
				}, f.delay)
			}), d.hover(function (e) {
				return s.hasClass("open") || s.is(e.target) ? void r(e) : !0
			}), s.find(".dropdown-submenu").each(function () {
				var o, t = e(this);
				t.hover(function () {
					n.clearTimeout(o), t.children(".dropdown-menu").show(), t.siblings().children(".dropdown-menu").hide()
				}, function () {
					var e = t.children(".dropdown-menu");
					o = n.setTimeout(function () {
						e.hide()
					}, f.delay)
				})
			})
		}))
	}, e(document).ready(function () {
		e('[data-hover="dropdown"]').dropdownHover()
	})
}(jQuery, window);

redpajama_set_name: RedPajamaGithub


text:
import sys
import platform
import os
import datetime
import os.path
import socket
import re

def checkPythonVersion():
    # This script depends on libraries like json and urllib2 which require 2.6 or 2.7
    #   so test for one of those, and exit if not found.
    pyver = platform.python_version()
    if ((not pyver.startswith('2.6')) and (not pyver.startswith('2.7'))):
        print >> sys.stderr, "Python version %s is not supported, need 2.6.x or 2.7.x" % pyver
        sys.exit(1)

def checkPidRunning(pid):
    if (platform.system() != "Windows"):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True
    else:
        return True

def checkLockFile(filename):
    pid = str(os.getpid())
    if (os.path.isfile(filename)):
        errMsg = "Lock file (%s) exists" % filename
        pid = file(filename, 'r').readlines()[0].strip()
        if (checkPidRunning(int(pid))):
            print >> sys.stderr, "%s... Exiting" % errMsg
        else:
            print >> sys.stderr, "%s, but PID (%s) not running." % (errMsg, pid)
            print >> sys.stderr, "Deleting stale lock file. Try running script again."
            os.remove(filename)
        sys.exit(1)
    else:
        file(filename, 'w').write(pid)

def convertAuthFilenameToConfig(filename):
    basename = os.path.basename(filename)
    return basename.replace(".auth", ".config")

def processAuthFile(filename, progDir):
    if (not os.path.exists(filename)):
        filename = os.path.join(progDir, filename)
        if (not os.path.exists(filename)):
            return (None, "Auth file %s does not exist" % filename)
    fp = open(filename)
    lines = fp.readlines()
    fp.close()
    credentials = []
    for line in lines:
        str = line.strip()
        if not str.startswith("#"):
            fields = str.split("|")
            if (len(fields) == 2):
                if (len(credentials) < 5):
                    credential = {'id': fields[0], 'secret': fields[1]}
                    credentials.append(credential)
                else:
                    print >> sys.stderr, "Ignoring id=%s, only 5 accounts allowed" % fields[0]
    if (len(credentials) == 0):
        return (None, "Empty auth file, no credentials found in %s" % filename)
    else:
        return (credentials, None)

def verifyISO8601(tstr):
    if (tstr == None) or (len(tstr) == 0):
        return (False, "Empty timestamp, ISO8601 format required")
    iso_regex = "\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{4})?)?$"
    m = re.match(iso_regex, tstr)
    if (m == None):
        return (False, "Timestamp (%s) does not match ISO8601 format" % tstr)
    return (True, "")

def formatTimeAsISO8601(dt):
    tuple = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)
    return "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ" % tuple

def getNowAsISO8601():
    return formatTimeAsISO8601(datetime.datetime.utcnow())

def getHostname():
    return socket.gethostname()

monthNames = ["???", "Jan", "Feb", "Mar", "Apr",
              "May", "Jun", "Jul", "Aug", "Sep",
              "Oct", "Nov", "Dec"]

def getSyslogTime():
    now = datetime.datetime.now()
    tuple = (monthNames[now.month], now.day, now.hour, now.minute, now.second)
    return "%s %2d %02d:%02d:%02d" % tuple

# Jan  6 19:05:30 percheron cpapi:
def getSyslogPrefix():
    return "%s %s cpapi: " % (getSyslogTime(), getHostname())


text:
home = ENV['HOME']

directory "#{home}/.atom" do
  recursive true
end

file "#{home}/.atom/config.cson" do
  action :create_if_missing
  content '"*":
  core:
    telemetryConsent: "no"
  welcome:
    showOnStartup: false'
end

atom_apm 'linter'
atom_apm 'linter-rubocop'
atom_apm 'linter-ui-default'
atom_apm 'uninstall linter-rubocop' do
  plugin 'linter-rubocop'
  action :uninstall
end

atom_apm 'disable linter' do
  plugin 'linter'
  action :disable
end

atom_apm 'disable linter-ui-default' do
  plugin 'linter-ui-default'
  action :disable
end
atom_apm 'enable linter-ui-default' do
  plugin 'linter-ui-default'
  action :enable
end


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// AnalyticsInfo File system analytics information summarizing all descendents of a specific directory.
//
// swagger:model analytics_info
type AnalyticsInfo struct {

	// by accessed time
	ByAccessedTime *AnalyticsInfoByAccessedTime `json:"by_accessed_time,omitempty"`

	// by modified time
	ByModifiedTime *AnalyticsInfoByModifiedTime `json:"by_modified_time,omitempty"`

	// Number of bytes used on-disk
	// Example: 15436648448
	BytesUsed int64 `json:"bytes_used,omitempty"`

	// Number of descendants
	// Example: 21134
	FileCount int64 `json:"file_count,omitempty"`

	// Number of sub directories
	// Example: 35
	SubdirCount int64 `json:"subdir_count,omitempty"`
}

// Validate validates this analytics info
func (m *AnalyticsInfo) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateByAccessedTime(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateByModifiedTime(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfo) validateByAccessedTime(formats strfmt.Registry) error {
	if swag.IsZero(m.ByAccessedTime) { // not required
		return nil
	}

	if m.ByAccessedTime != nil {
		if err := m.ByAccessedTime.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_accessed_time")
			}
			return err
		}
	}

	return nil
}

func (m *AnalyticsInfo) validateByModifiedTime(formats strfmt.Registry) error {
	if swag.IsZero(m.ByModifiedTime) { // not required
		return nil
	}

	if m.ByModifiedTime != nil {
		if err := m.ByModifiedTime.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_modified_time")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this analytics info based on the context it is used
func (m *AnalyticsInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateByAccessedTime(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateByModifiedTime(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfo) contextValidateByAccessedTime(ctx context.Context, formats strfmt.Registry) error {

	if m.ByAccessedTime != nil {
		if err := m.ByAccessedTime.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_accessed_time")
			}
			return err
		}
	}

	return nil
}

func (m *AnalyticsInfo) contextValidateByModifiedTime(ctx context.Context, formats strfmt.Registry) error {

	if m.ByModifiedTime != nil {
		if err := m.ByModifiedTime.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_modified_time")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AnalyticsInfo) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AnalyticsInfo) UnmarshalBinary(b []byte) error {
	var res AnalyticsInfo
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// AnalyticsInfoByAccessedTime File system analytics information, broken down by date of last access.
//
// swagger:model AnalyticsInfoByAccessedTime
type AnalyticsInfoByAccessedTime struct {

	// bytes used
	BytesUsed *AnalyticsInfoByAccessedTimeBytesUsed `json:"bytes_used,omitempty"`
}

// Validate validates this analytics info by accessed time
func (m *AnalyticsInfoByAccessedTime) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateBytesUsed(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByAccessedTime) validateBytesUsed(formats strfmt.Registry) error {
	if swag.IsZero(m.BytesUsed) { // not required
		return nil
	}

	if m.BytesUsed != nil {
		if err := m.BytesUsed.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_accessed_time" + "." + "bytes_used")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this analytics info by accessed time based on the context it is used
func (m *AnalyticsInfoByAccessedTime) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateBytesUsed(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByAccessedTime) contextValidateBytesUsed(ctx context.Context, formats strfmt.Registry) error {

	if m.BytesUsed != nil {
		if err := m.BytesUsed.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_accessed_time" + "." + "bytes_used")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AnalyticsInfoByAccessedTime) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AnalyticsInfoByAccessedTime) UnmarshalBinary(b []byte) error {
	var res AnalyticsInfoByAccessedTime
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// AnalyticsInfoByAccessedTimeBytesUsed Number of bytes used on-disk, broken down by date of last access.
//
// swagger:model AnalyticsInfoByAccessedTimeBytesUsed
type AnalyticsInfoByAccessedTimeBytesUsed struct {

	// labels
	Labels AnalyticsHistogramByTimeLabels `json:"labels,omitempty"`

	// The newest time label with a non-zero histogram value.
	NewestLabel AnalyticsHistogramTimeLabel `json:"newest_label,omitempty"`

	// The oldest time label with a non-zero histogram value.
	OldestLabel AnalyticsHistogramTimeLabel `json:"oldest_label,omitempty"`

	// Percentages for this histogram
	// Example: ["0.1","11.24","0.18","15.75","0.75","83.5","0"]
	Percentages []float64 `json:"percentages,omitempty"`

	// Values for this histogram
	// Example: ["15925248","1735569408","27672576","2430595072","116105216","12889948160","0"]
	Values []int64 `json:"values,omitempty"`
}

// Validate validates this analytics info by accessed time bytes used
func (m *AnalyticsInfoByAccessedTimeBytesUsed) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLabels(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateNewestLabel(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateOldestLabel(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) validateLabels(formats strfmt.Registry) error {
	if swag.IsZero(m.Labels) { // not required
		return nil
	}

	if err := m.Labels.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "labels")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) validateNewestLabel(formats strfmt.Registry) error {
	if swag.IsZero(m.NewestLabel) { // not required
		return nil
	}

	if err := m.NewestLabel.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "newest_label")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) validateOldestLabel(formats strfmt.Registry) error {
	if swag.IsZero(m.OldestLabel) { // not required
		return nil
	}

	if err := m.OldestLabel.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "oldest_label")
		}
		return err
	}

	return nil
}

// ContextValidate validate this analytics info by accessed time bytes used based on the context it is used
func (m *AnalyticsInfoByAccessedTimeBytesUsed) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLabels(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateNewestLabel(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateOldestLabel(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) contextValidateLabels(ctx context.Context, formats strfmt.Registry) error {

	if err := m.Labels.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "labels")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) contextValidateNewestLabel(ctx context.Context, formats strfmt.Registry) error {

	if err := m.NewestLabel.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "newest_label")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByAccessedTimeBytesUsed) contextValidateOldestLabel(ctx context.Context, formats strfmt.Registry) error {

	if err := m.OldestLabel.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_accessed_time" + "." + "bytes_used" + "." + "oldest_label")
		}
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AnalyticsInfoByAccessedTimeBytesUsed) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AnalyticsInfoByAccessedTimeBytesUsed) UnmarshalBinary(b []byte) error {
	var res AnalyticsInfoByAccessedTimeBytesUsed
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// AnalyticsInfoByModifiedTime File system analytics information, broken down by date of last modification.
//
// swagger:model AnalyticsInfoByModifiedTime
type AnalyticsInfoByModifiedTime struct {

	// bytes used
	BytesUsed *AnalyticsInfoByModifiedTimeBytesUsed `json:"bytes_used,omitempty"`
}

// Validate validates this analytics info by modified time
func (m *AnalyticsInfoByModifiedTime) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateBytesUsed(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByModifiedTime) validateBytesUsed(formats strfmt.Registry) error {
	if swag.IsZero(m.BytesUsed) { // not required
		return nil
	}

	if m.BytesUsed != nil {
		if err := m.BytesUsed.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_modified_time" + "." + "bytes_used")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this analytics info by modified time based on the context it is used
func (m *AnalyticsInfoByModifiedTime) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateBytesUsed(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByModifiedTime) contextValidateBytesUsed(ctx context.Context, formats strfmt.Registry) error {

	if m.BytesUsed != nil {
		if err := m.BytesUsed.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("by_modified_time" + "." + "bytes_used")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AnalyticsInfoByModifiedTime) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AnalyticsInfoByModifiedTime) UnmarshalBinary(b []byte) error {
	var res AnalyticsInfoByModifiedTime
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// AnalyticsInfoByModifiedTimeBytesUsed Number of bytes used on-disk, broken down by date of last modification.
//
// swagger:model AnalyticsInfoByModifiedTimeBytesUsed
type AnalyticsInfoByModifiedTimeBytesUsed struct {

	// labels
	Labels AnalyticsHistogramByTimeLabels `json:"labels,omitempty"`

	// The newest time label with a non-zero histogram value.
	NewestLabel AnalyticsHistogramTimeLabel `json:"newest_label,omitempty"`

	// The oldest time label with a non-zero histogram value.
	OldestLabel AnalyticsHistogramTimeLabel `json:"oldest_label,omitempty"`

	// Percentages for this histogram
	// Example: ["0.1","11.24","0.18","15.75","0.75","83.5","0"]
	Percentages []float64 `json:"percentages,omitempty"`

	// Values for this histogram
	// Example: ["15925248","1735569408","27672576","2430595072","116105216","12889948160","0"]
	Values []int64 `json:"values,omitempty"`
}

// Validate validates this analytics info by modified time bytes used
func (m *AnalyticsInfoByModifiedTimeBytesUsed) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLabels(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateNewestLabel(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateOldestLabel(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) validateLabels(formats strfmt.Registry) error {
	if swag.IsZero(m.Labels) { // not required
		return nil
	}

	if err := m.Labels.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "labels")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) validateNewestLabel(formats strfmt.Registry) error {
	if swag.IsZero(m.NewestLabel) { // not required
		return nil
	}

	if err := m.NewestLabel.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "newest_label")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) validateOldestLabel(formats strfmt.Registry) error {
	if swag.IsZero(m.OldestLabel) { // not required
		return nil
	}

	if err := m.OldestLabel.Validate(formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "oldest_label")
		}
		return err
	}

	return nil
}

// ContextValidate validate this analytics info by modified time bytes used based on the context it is used
func (m *AnalyticsInfoByModifiedTimeBytesUsed) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLabels(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateNewestLabel(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateOldestLabel(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) contextValidateLabels(ctx context.Context, formats strfmt.Registry) error {

	if err := m.Labels.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "labels")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) contextValidateNewestLabel(ctx context.Context, formats strfmt.Registry) error {

	if err := m.NewestLabel.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "newest_label")
		}
		return err
	}

	return nil
}

func (m *AnalyticsInfoByModifiedTimeBytesUsed) contextValidateOldestLabel(ctx context.Context, formats strfmt.Registry) error {

	if err := m.OldestLabel.ContextValidate(ctx, formats); err != nil {
		if ve, ok := err.(*errors.Validation); ok {
			return ve.ValidateName("by_modified_time" + "." + "bytes_used" + "." + "oldest_label")
		}
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AnalyticsInfoByModifiedTimeBytesUsed) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AnalyticsInfoByModifiedTimeBytesUsed) UnmarshalBinary(b []byte) error {
	var res AnalyticsInfoByModifiedTimeBytesUsed
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for InvalidPropertyType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="InvalidPropertyType">
 *   <complexContent>
 *     <extension base="{urn:vim25}VAppPropertyFault">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InvalidPropertyType")
public class InvalidPropertyType
    extends VAppPropertyFault
{

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Chytridiopsis socius Schneider

### Remarks
null


text:
package com.rabbit.dto.search;

import java.util.List;

/**
 * 多属性规格
 * @author ztiny
 * @Date 2015-12-19
 */
public class SpecificationsEntity {

	//规格名称对应的值
	private String specValue;
	//SKU的集合
	private List<String> skus;

	public String getSpecValue() {
		return specValue;
	}
	public void setSpecValue(String specValue) {
		this.specValue = specValue;
	}
	public List<String> getSkus() {
		return skus;
	}
	public void setSkus(List<String> skus) {
		this.skus = skus;
	}

}


text:
package FX.controller;

import FX.Window;
import FX.view.GridOverlay;
import app.conf.Configuration;
import javafx.animation.*;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.WritableValue;
import javafx.fxml.FXML;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.HashMap;

/**
 * Controller for the toolbar.
 *
 * @author Mcdostone
 */
public class ToolbarController {

    @FXML private GridPane toolbarGrid;
    @FXML private Button settingsButton;
    @FXML private Button sortingButton;
    @FXML private Button lockButton;
    @FXML private Button gridButton;
    @FXML private Button fullscreenButton;
    @FXML private Button logsButton;
    @FXML private Button infosButton;

    private boolean toolbarLocked;
    private boolean infosVisible;
    private Animation currentAnimation;
    private Animation infosAnimation;

    private HashMap<String, Parent> binds;

    public ToolbarController() {
        this.toolbarLocked = Configuration.getInstance().lockToolbar();
        this.binds = new HashMap<>();
    }

    @FXML
    public void initialize() {
        this.settingsButton.setOnAction(  event ->  Window.getWM().openSettingsWindow()  );
        this.logsButton.setOnAction(  event ->  Window.getWM().openLogsWindows()  );
        this.fullscreenButton.setOnAction(  event ->  Window.getWM().toggleFullscreen()  );
        this.gridButton.setOnAction(event -> {
            Node grid = this.binds.get("grid");
            grid.setVisible(!grid.isVisible());
            ToolbarController.applyActiveStyle(gridButton, grid.isVisible());
        });
        this.infosButton.setOnAction(event -> {
            if(infosVisible)
                hideInfos();
            else
                showInfos();
            ToolbarController.applyActiveStyle(infosButton, this.infosVisible);
        });
        this.lockButton.setOnAction(event -> {
            lockButton.setId((toolbarLocked ? "unlocked" : "locked"));
            toolbarLocked = !toolbarLocked;
            ToolbarController.applyActiveStyle(lockButton, toolbarLocked);
            if (!toolbarLocked)
                hideToolbar();
        });
        this.sortingButton.setOnAction(event -> {
            Parent p = this.binds.get("sorting");
            p.setVisible(!p.isVisible());
            ToolbarController.applyActiveStyle(this.sortingButton, p.isVisible());
        });

        Window.getWM().getFullsreenProperty().addListener((observable, oldValue, newValue) -> ToolbarController.applyActiveStyle(fullscreenButton, newValue));
    }

    public void register(String componentName, Pane component) {
        this.binds.put(componentName, component);
        switch(componentName) {
            case "grid":
                ToolbarController.applyActiveStyle(this.gridButton, Configuration.getInstance().showGridAtStartup());
                break;
            case "infos":
                this.infosVisible = component.isVisible();
                ToolbarController.applyActiveStyle(this.infosButton, this.infosVisible);

                if(!this.infosVisible)
                    component.setTranslateX(component.getPrefWidth());
                break;
        }

    }

    private void hideInfos() {
        if (this.infosAnimation != null)
            this.infosAnimation.stop();
        Node infos = this.binds.get("infos");
        Timeline timeline = new Timeline();
        infosVisible = false;
        KeyValue hidden = new KeyValue(infos.translateXProperty(), infos.getBoundsInParent().getWidth(), Interpolator.EASE_BOTH);
        KeyFrame keyFrame = new KeyFrame(Duration.millis(400), hidden);
        timeline.getKeyFrames().add(keyFrame);
        timeline.setOnFinished(event -> infos.setVisible(false));
        this.infosAnimation = timeline;

        timeline.play();
    }

    private void showInfos() {
        if (this.infosAnimation != null)
            this.infosAnimation.stop();
        Node infos = this.binds.get("infos");
        infos.setVisible(true);
        this.infosVisible = true;
        Timeline timeline = new Timeline();
        KeyValue hidden = new KeyValue(infos.translateXProperty(), 0, Interpolator.EASE_OUT);
        KeyFrame keyFrame = new KeyFrame(Duration.millis(200), hidden);
        timeline.getKeyFrames().add(keyFrame);
        this.infosAnimation = timeline;

        timeline.play();
    }

    public void hideToolbar() {
        Parent toolbar = this.toolbarGrid.getParent();
        if (!this.toolbarLocked) {
            if (this.currentAnimation != null)
                this.currentAnimation.stop();

            Timeline timeline = new Timeline();
            KeyValue hidden = new KeyValue(toolbar.translateYProperty(), toolbar.getBoundsInParent().getHeight(), Interpolator.EASE_BOTH);
            KeyFrame keyFrame = new KeyFrame(Duration.millis(400), hidden);
            timeline.getKeyFrames().add(keyFrame);
            timeline.setOnFinished(event -> toolbar.setVisible(false));
            Timeline empty = new Timeline();
            empty.getKeyFrames().add(new KeyFrame(Duration.millis((toolbar.getTranslateY() == 0.0) ? 200 : 0)));
            SequentialTransition sequence = new SequentialTransition(empty, timeline);
            this.currentAnimation = sequence;

            this.toolbarGrid.getParent().getParent().getParent().requestFocus();
            sequence.play();
        }
    }

    public void showToolbar() {
        Parent toolbar = this.toolbarGrid.getParent();
        if(!this.toolbarLocked) {
            if(this.currentAnimation != null)
                this.currentAnimation.stop();

            toolbar.setVisible(true);
            Timeline timeline = new Timeline();
            KeyValue show = new KeyValue(toolbar.translateYProperty(), 0, Interpolator.EASE_IN);
            KeyFrame keyFrame  = new KeyFrame(Duration.millis(200), show);
            timeline.getKeyFrames().add(keyFrame);
            this.currentAnimation = timeline;

            timeline.play();
        }
    }

    private static void applyActiveStyle(Button p, boolean add) {
        if (add)
            p.getStyleClass().add("active");
        else
            p.getStyleClass().remove("active");
    }

}


text:
<?php

namespace ZendTest\Http;

use PHPUnit\Framework\TestCase;
use Zend\Http\Cookies;
use Zend\Http\Header\SetCookie;
use Zend\Http\Headers;
use Zend\Http\PhpEnvironment\Request;
use Zend\Http\Response;

class CookiesTest extends TestCase
{
    public function testFromResponseInSetCookie()
    {
        $response = new Response();
        $headers = new Headers();
        $header = new SetCookie('foo', 'bar');
        $header->setDomain('www.zend.com');
        $header->setPath('/');
        $headers->addHeader($header);
        $response->setHeaders($headers);

        $response = Cookies::fromResponse($response, 'http://www.zend.com');
        $this->assertSame($header, $response->getCookie('http://www.zend.com', 'foo'));
    }

    public function testFromResponseInCookie()
    {
        $response = new Response();
        $headers = new Headers();
        $header = new SetCookie('foo', 'bar');
        $header->setDomain('www.zend.com');
        $header->setPath('/');
        $headers->addHeader($header);
        $response->setHeaders($headers);

        $response = Cookies::fromResponse($response, 'http://www.zend.com');
        $this->assertSame($header, $response->getCookie('http://www.zend.com', 'foo'));
    }

    public function testRequestCanHaveArrayCookies()
    {
        $_COOKIE = [
            'test' => [
                'a' => 'value_a',
                'b' => 'value_b',
            ],
        ];
        $request = new Request();
        $fieldValue = $request->getCookie('test')->getFieldValue();
        $this->assertSame('test[a]=value_a; test[b]=value_b', $fieldValue);

        $_COOKIE = [
            'test' => [
                'a' => [
                    'a1' => 'va1',
                    'a2' => 'va2',
                ],
                'b' => [
                    'b1' => 'vb1',
                    'b2' => 'vb2',
                ],
            ],
        ];
        $request = new Request();
        $fieldValue = $request->getCookie('test')->getFieldValue();
        $this->assertSame('test[a][a1]=va1; test[a][a2]=va2; test[b][b1]=vb1; test[b][b2]=vb2', $fieldValue);
    }
}


text:
BBEdit Codeless Language Module for Xcode .pbxproj files
==============================

This is a [BBEdit](http://www.barebones.com/products/bbedit/index.html) Codeless
Language Module for [Xcode](https://developer.apple.com/xcode/) project files. It provides some amount of syntax highlighting
and code folding for project.pbxproj files inside .xcodeproj file bundles.
It also works with [TextWrangler](http://www.barebones.com/products/textwrangler/).

For more information see the documentation for [Codeless Language Modules](http://www.barebones.com/support/develop/clm.html).

Installation
=============================

  * For BBEdit, copy the pbxproj.plist file to:

		~/Library/Application Support/BBEdit/Language Modules/

	For TextWrangler, copy the pbxproj.plist file to:

		~/Library/Application Support/TextWrangler/Language Modules/

  * Restart BBEdit or TextWrangler.

Areas For Improvement
===========================

  * Use function name mapping for identifiers. This will fill the function name popup with items in the file.


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;

namespace Azure.ResourceManager.SecurityCenter
{
    /// <summary>
    /// A class representing a collection of <see cref="RegulatoryComplianceControlResource" /> and their operations.
    /// Each <see cref="RegulatoryComplianceControlResource" /> in the collection will belong to the same instance of <see cref="RegulatoryComplianceStandardResource" />.
    /// To get a <see cref="RegulatoryComplianceControlCollection" /> instance call the GetRegulatoryComplianceControls method from an instance of <see cref="RegulatoryComplianceStandardResource" />.
    /// </summary>
    public partial class RegulatoryComplianceControlCollection : ArmCollection, IEnumerable<RegulatoryComplianceControlResource>, IAsyncEnumerable<RegulatoryComplianceControlResource>
    {
        private readonly ClientDiagnostics _regulatoryComplianceControlClientDiagnostics;
        private readonly RegulatoryComplianceControlsRestOperations _regulatoryComplianceControlRestClient;

        /// <summary> Initializes a new instance of the <see cref="RegulatoryComplianceControlCollection"/> class for mocking. </summary>
        protected RegulatoryComplianceControlCollection()
        {
        }

        /// <summary> Initializes a new instance of the <see cref="RegulatoryComplianceControlCollection"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
        internal RegulatoryComplianceControlCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _regulatoryComplianceControlClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.SecurityCenter", RegulatoryComplianceControlResource.ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(RegulatoryComplianceControlResource.ResourceType, out string regulatoryComplianceControlApiVersion);
            _regulatoryComplianceControlRestClient = new RegulatoryComplianceControlsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, regulatoryComplianceControlApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != RegulatoryComplianceStandardResource.ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, RegulatoryComplianceStandardResource.ResourceType), nameof(id));
        }

        /// <summary>
        /// Selected regulatory compliance control details and state
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls/{regulatoryComplianceControlName}
        /// Operation Id: RegulatoryComplianceControls_Get
        /// </summary>
        /// <param name="regulatoryComplianceControlName"> Name of the regulatory compliance control object. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="regulatoryComplianceControlName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="regulatoryComplianceControlName"/> is null. </exception>
        public virtual async Task<Response<RegulatoryComplianceControlResource>> GetAsync(string regulatoryComplianceControlName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(regulatoryComplianceControlName, nameof(regulatoryComplianceControlName));

            using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.Get");
            scope.Start();
            try
            {
                var response = await _regulatoryComplianceControlRestClient.GetAsync(Id.SubscriptionId, Id.Name, regulatoryComplianceControlName, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new RegulatoryComplianceControlResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Selected regulatory compliance control details and state
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls/{regulatoryComplianceControlName}
        /// Operation Id: RegulatoryComplianceControls_Get
        /// </summary>
        /// <param name="regulatoryComplianceControlName"> Name of the regulatory compliance control object. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="regulatoryComplianceControlName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="regulatoryComplianceControlName"/> is null. </exception>
        public virtual Response<RegulatoryComplianceControlResource> Get(string regulatoryComplianceControlName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(regulatoryComplianceControlName, nameof(regulatoryComplianceControlName));

            using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.Get");
            scope.Start();
            try
            {
                var response = _regulatoryComplianceControlRestClient.Get(Id.SubscriptionId, Id.Name, regulatoryComplianceControlName, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new RegulatoryComplianceControlResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// All supported regulatory compliance controls details and state for selected standard
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls
        /// Operation Id: RegulatoryComplianceControls_List
        /// </summary>
        /// <param name="filter"> OData filter. Optional. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="RegulatoryComplianceControlResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual AsyncPageable<RegulatoryComplianceControlResource> GetAllAsync(string filter = null, CancellationToken cancellationToken = default)
        {
            async Task<Page<RegulatoryComplianceControlResource>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.GetAll");
                scope.Start();
                try
                {
                    var response = await _regulatoryComplianceControlRestClient.ListAsync(Id.SubscriptionId, Id.Name, filter, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value.Select(value => new RegulatoryComplianceControlResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<RegulatoryComplianceControlResource>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.GetAll");
                scope.Start();
                try
                {
                    var response = await _regulatoryComplianceControlRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.Name, filter, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value.Select(value => new RegulatoryComplianceControlResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary>
        /// All supported regulatory compliance controls details and state for selected standard
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls
        /// Operation Id: RegulatoryComplianceControls_List
        /// </summary>
        /// <param name="filter"> OData filter. Optional. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="RegulatoryComplianceControlResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual Pageable<RegulatoryComplianceControlResource> GetAll(string filter = null, CancellationToken cancellationToken = default)
        {
            Page<RegulatoryComplianceControlResource> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.GetAll");
                scope.Start();
                try
                {
                    var response = _regulatoryComplianceControlRestClient.List(Id.SubscriptionId, Id.Name, filter, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value.Select(value => new RegulatoryComplianceControlResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<RegulatoryComplianceControlResource> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.GetAll");
                scope.Start();
                try
                {
                    var response = _regulatoryComplianceControlRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.Name, filter, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value.Select(value => new RegulatoryComplianceControlResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary>
        /// Checks to see if the resource exists in azure.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls/{regulatoryComplianceControlName}
        /// Operation Id: RegulatoryComplianceControls_Get
        /// </summary>
        /// <param name="regulatoryComplianceControlName"> Name of the regulatory compliance control object. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="regulatoryComplianceControlName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="regulatoryComplianceControlName"/> is null. </exception>
        public virtual async Task<Response<bool>> ExistsAsync(string regulatoryComplianceControlName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(regulatoryComplianceControlName, nameof(regulatoryComplianceControlName));

            using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.Exists");
            scope.Start();
            try
            {
                var response = await _regulatoryComplianceControlRestClient.GetAsync(Id.SubscriptionId, Id.Name, regulatoryComplianceControlName, cancellationToken: cancellationToken).ConfigureAwait(false);
                return Response.FromValue(response.Value != null, response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Checks to see if the resource exists in azure.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Security/regulatoryComplianceStandards/{regulatoryComplianceStandardName}/regulatoryComplianceControls/{regulatoryComplianceControlName}
        /// Operation Id: RegulatoryComplianceControls_Get
        /// </summary>
        /// <param name="regulatoryComplianceControlName"> Name of the regulatory compliance control object. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="regulatoryComplianceControlName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="regulatoryComplianceControlName"/> is null. </exception>
        public virtual Response<bool> Exists(string regulatoryComplianceControlName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(regulatoryComplianceControlName, nameof(regulatoryComplianceControlName));

            using var scope = _regulatoryComplianceControlClientDiagnostics.CreateScope("RegulatoryComplianceControlCollection.Exists");
            scope.Start();
            try
            {
                var response = _regulatoryComplianceControlRestClient.Get(Id.SubscriptionId, Id.Name, regulatoryComplianceControlName, cancellationToken: cancellationToken);
                return Response.FromValue(response.Value != null, response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        IEnumerator<RegulatoryComplianceControlResource> IEnumerable<RegulatoryComplianceControlResource>.GetEnumerator()
        {
            return GetAll().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetAll().GetEnumerator();
        }

        IAsyncEnumerator<RegulatoryComplianceControlResource> IAsyncEnumerable<RegulatoryComplianceControlResource>.GetAsyncEnumerator(CancellationToken cancellationToken)
        {
            return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
        }
    }
}


text:
'use strict';

// Configuring the Cities module
angular.module('cities').run(['Menus',
	function(Menus) {
		// Set top bar menu items
		Menus.addMenuItem('topbar', 'Cities', 'cities', '', '/cities');
		// Menus.addSubMenuItem('topbar', 'cities', 'List Cities', 'cities');
		// Menus.addSubMenuItem('topbar', 'cities', 'New City', 'cities/create');
	}
]);


text:
<?php

namespace Frontman;

/**
 * Frontman proxy class
 *
 * @package    Frontman
 * @author     Hassan Khan <contact@hassankhan.me>
 * @link       https://github.com/hassankhan/frontman/
 * @license    MIT
 * @since      0.1
 */
class Proxy implements ProxyInterface
{
    /**
     * @var array
     */
    protected static $realClasses = array();

    /**
     * Since we don't need a constructor for the proxy class, we just set its
     * visibility to private
     * @codeCoverageIgnore
     */
    private function __construct()
    {
    }

    /**
     * {@inheritDoc}
     * @codeCoverageIgnore
     */
    public static function getRealClass()
    {
        return '';
    }

    /**
     * {@inheritDoc}
     * @codeCoverageIgnore
     */
    public static function getConstructorArguments()
    {
        return array();
    }

    /**
     * This method calls the root class with `$arguments` as parameters and
     * returns its result
     *
     * @param  string $method
     * @param  mixed  $arguments
     *
     * @return mixed
     *
     * @throws BadMethodCallException If an undefined method is called
     */
    public static function __callStatic($method, $arguments)
    {
        $realClass = static::getRealClass();
        if (!isset(self::$realClasses[$realClass])) {
            self::$realClasses[$realClass] = new $realClass(static::getConstructorArguments());
        }

        $objectMethod = array(self::$realClasses[$realClass], $method);
        if (is_callable($objectMethod)) {
            return call_user_func_array($objectMethod, $arguments);
        }

        throw new \BadMethodCallException("Method $method does not exist");
    }
}


text:
import {
  async,
  inject
} from '@angular/core/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {RioNavigator} from './navigator.component';
import {TestBed} from '@angular/core/testing/test_bed';
import {RioNavigatorModule} from './navigator.module';

describe('Component: Navigator', () => {
  let fixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        RioNavigatorModule
      ],
      declarations: [
        RioNavigatorTestController
      ],
      providers: [
        RioNavigator
      ]
    });
    fixture = TestBed.createComponent(RioNavigatorTestController);
    fixture.detectChanges();
  });

  it('should inject the component', inject([RioNavigator],
    (component: RioNavigator) => {
      expect(component).toBeTruthy();
    }));

  it('should create the component', async(inject([], () => {
    fixture.whenStable().then(() => {
      fixture.autoDetectChanges();
      let query = fixture.debugElement
        .query(By.directive(RioNavigator));
      expect(query).toBeTruthy();
      expect(query.componentInstance).toBeTruthy();
    });
  })));
});

@Component({
  selector: 'test',
  template: `
    <rio-navigator></rio-navigator>
  `
})
class RioNavigatorTestController { }


text:
package smt

import smt.db.Connection
import smt.migration.{Direction, Script, MigrationInfo}
import scalaz.{\/-, \/}
import sbt.{Level, Logger}

class ConnectionMock extends Connection {

  var addCount: Int = 0

  def init(logger: Logger)(): String \/ Unit = \/-(())

  def state(logger: Logger): String \/ Seq[MigrationInfo] = \/-(Seq())

  def downs(logger: Logger)(hash: Seq[Byte]): String \/ Seq[Script] = \/-(Seq())

  def add(logger: Logger)(migrationInfo: MigrationInfo): String \/ Unit = {
    addCount = addCount + 1
    \/-(())
  }

  def addDowns(logger: Logger)(migHash: Seq[Byte], downs: Seq[Script]): String \/ Unit = \/-(())

  def remove(logger: Logger)(hash: Seq[Byte]): String \/ Unit = \/-(())

  def removeDowns(logger: Logger)(migHash: Seq[Byte]): String \/ Unit = \/-(())

  def applyScript(logger: Logger)(script: Script, direction: Direction): String \/ Unit = \/-(())

  def testScript(logger: Logger)(script: Script): String \/ Unit = \/-(())

  def close(logger: Logger)(): String \/ Unit = \/-(())

  def acquireLock(logger: Logger)(): String \/ String  = \/-("lock")

  def releaseLock(logger: Logger)(lock: String): String \/ Unit = \/-(())
}