text:
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Emby.ApiClient.Model;
using Emby.ApiClient.Net;

namespace Emby.ApiClient
{
    /// <summary>
    /// Provides api methods that are usable on all platforms
    /// </summary>
    public abstract class BaseApiClient : IDisposable
    {
        /// <summary>
        /// Gets the logger.
        /// </summary>
        /// <value>The logger.</value>
        internal ILogger Logger { get; private set; }

        /// <summary>
        /// Gets the json serializer.
        /// </summary>
        /// <value>The json serializer.</value>
        public IJsonSerializer JsonSerializer { get; set; }

        public IDevice Device { get; private set; }

        /// <summary>
        ///  If specified this will be used as a default when an explicit value is not specified.
        /// </summary>
        public int? ImageQuality { get; set; }

        protected BaseApiClient(ILogger logger, IJsonSerializer jsonSerializer, string serverAddress, string clientName, IDevice device, string applicationVersion)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (jsonSerializer == null)
            {
                throw new ArgumentNullException("jsonSerializer");
            }
            if (string.IsNullOrEmpty(serverAddress))
            {
                throw new ArgumentNullException("serverAddress");
            }

            JsonSerializer = jsonSerializer;
            Logger = logger;

            ClientName = clientName;
            Device = device;
            ApplicationVersion = applicationVersion;
            ServerAddress = serverAddress;
        }

        protected BaseApiClient(ILogger logger, IJsonSerializer jsonSerializer, string serverAddress, string accessToken)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (jsonSerializer == null)
            {
                throw new ArgumentNullException("jsonSerializer");
            }
            if (string.IsNullOrEmpty(serverAddress))
            {
                throw new ArgumentNullException("serverAddress");
            }

            JsonSerializer = jsonSerializer;
            Logger = logger;

            AccessToken = accessToken;
            ServerAddress = serverAddress;
        }

        /// <summary>
        /// Gets the name of the server host.
        /// </summary>
        /// <value>The name of the server host.</value>
        public string ServerAddress { get; protected set; }

        /// <summary>
        /// Changes the server location.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <param name="keepExistingAuth"></param>
        public void ChangeServerLocation(string address, bool keepExistingAuth = false)
        {
            ServerAddress = address;

            if (!keepExistingAuth)
            {
                SetAuthenticationInfo(null, null);
            }
        }

        /// <summary>
        /// Gets or sets the type of the client.
        /// </summary>
        /// <value>The type of the client.</value>
        public string ClientName { get; set; }

        /// <summary>
        /// Gets or sets the name of the device.
        /// </summary>
        /// <value>The name of the device.</value>
        public string DeviceName
        {
            get { return Device?.DeviceName; }
        }

        /// <summary>
        /// Gets or sets the application version.
        /// </summary>
        /// <value>The application version.</value>
        public string ApplicationVersion { get; set; }

        /// <summary>
        /// Gets or sets the device id.
        /// </summary>
        /// <value>The device id.</value>
        public string DeviceId
        {
            get { return Device?.DeviceId; }
        }

        /// <summary>
        /// Gets or sets the access token.
        /// </summary>
        /// <value>The access token.</value>
        public string AccessToken { get; private set; }

        /// <summary>
        /// Gets or sets the current user id.
        /// </summary>
        /// <value>The current user id.</value>
        public string CurrentUserId { get; private set; }

        /// <summary>
        /// Gets the current api url based on hostname and port.
        /// </summary>
        /// <value>The API URL.</value>
        public string ApiUrl
        {
            get
            {
                return ServerAddress + "/emby";
            }
        }

        /// <summary>
        /// Gets the name of the authorization scheme.
        /// </summary>
        /// <value>The name of the authorization scheme.</value>
        protected string AuthorizationScheme
        {
            get { return "MediaBrowser"; }
        }

        /// <summary>
        /// Gets the authorization header parameter.
        /// </summary>
        /// <value>The authorization header parameter.</value>
        protected string AuthorizationParameter
        {
            get
            {
                if (string.IsNullOrEmpty(ClientName) && string.IsNullOrEmpty(DeviceId) && string.IsNullOrEmpty(DeviceName))
                {
                    return string.Empty;
                }

                var header = string.Format("Client=\"{0}\", DeviceId=\"{1}\", Device=\"{2}\", Version=\"{3}\"", ClientName, DeviceId, DeviceName, ApplicationVersion);

                if (!string.IsNullOrEmpty(CurrentUserId))
                {
                    header += string.Format(", UserId=\"{0}\"", CurrentUserId);
                }

                return header;
            }
        }

        /// <summary>
        /// Gets the API URL.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">handler</exception>
        public string GetApiUrl(string handler)
        {
            return GetApiUrl(handler, new QueryStringDictionary());
        }

        public void SetAuthenticationInfo(string accessToken, string userId)
        {
            CurrentUserId = userId;
            AccessToken = accessToken;
            ResetHttpHeaders();
        }

        public void ClearAuthenticationInfo()
        {
            CurrentUserId = null;
            AccessToken = null;
            ResetHttpHeaders();
        }

        public void SetAuthenticationInfo(string accessToken)
        {
            CurrentUserId = null;
            AccessToken = accessToken;
            ResetHttpHeaders();
        }

        protected void ResetHttpHeaders()
        {
            HttpHeaders.SetAccessToken(AccessToken);

            var authValue = AuthorizationParameter;

            if (string.IsNullOrEmpty(authValue))
            {
                ClearHttpRequestHeader("Authorization");
                SetAuthorizationHttpRequestHeader(null, null);
            }
            else
            {
                SetAuthorizationHttpRequestHeader(AuthorizationScheme, authValue);
            }
        }

        protected readonly HttpHeaders HttpHeaders = new HttpHeaders();
        private void SetAuthorizationHttpRequestHeader(string scheme, string parameter)
        {
            HttpHeaders.AuthorizationScheme = scheme;
            HttpHeaders.AuthorizationParameter = parameter;
        }

        private void ClearHttpRequestHeader(string name)
        {
            HttpHeaders.Remove(name);
        }

        /// <summary>
        /// Gets the API URL.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="queryString">The query string.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">handler</exception>
        protected string GetApiUrl(string handler, QueryStringDictionary queryString)
        {
            if (string.IsNullOrEmpty(handler))
            {
                throw new ArgumentNullException("handler");
            }

            if (queryString == null)
            {
                throw new ArgumentNullException("queryString");
            }

            return queryString.GetUrl(ApiUrl + "/" + handler);
        }

        public string GetSubtitleUrl(SubtitleDownloadOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrEmpty(options.MediaSourceId))
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrEmpty(options.ItemId))
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrEmpty(options.Format))
            {
                throw new ArgumentNullException("options");
            }

            return GetApiUrl("Videos/" + options.ItemId + "/" + options.MediaSourceId + "/Subtitles/" + options.StreamIndex + "/Stream." + options.Format);
        }

        /// <summary>
        /// Creates a url to return a list of items
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">query</exception>
        protected string GetItemListUrl(ItemQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var dict = new QueryStringDictionary { };

            dict.AddIfNotNullOrEmpty("ParentId", query.ParentId);

            dict.AddIfNotNull("StartIndex", query.StartIndex);

            dict.AddIfNotNull("Limit", query.Limit);

            dict.AddIfNotNull("SortBy", query.SortBy);

            if (!query.EnableTotalRecordCount)
            {
                dict.Add("EnableTotalRecordCount", query.EnableTotalRecordCount);
            }

            if (query.SortOrder.HasValue)
            {
                dict["sortOrder"] = query.SortOrder.ToString();
            }

            if (query.SeriesStatuses != null)
            {
                dict.Add("SeriesStatuses", query.SeriesStatuses.Select(f => f.ToString()));
            }

            if (query.Fields != null)
            {
                dict.Add("fields", query.Fields.Select(f => f.ToString()));
            }
            if (query.Filters != null)
            {
                dict.Add("Filters", query.Filters.Select(f => f.ToString()));
            }
            if (query.ImageTypes != null)
            {
                dict.Add("ImageTypes", query.ImageTypes.Select(f => f.ToString()));
            }

            dict.AddIfNotNull("Is3D", query.Is3D);
            if (query.VideoTypes != null)
            {
                dict.Add("VideoTypes", query.VideoTypes.Select(f => f.ToString()));
            }
            if (query.AirDays != null)
            {
                dict.Add("AirDays", query.AirDays.Select(f => f.ToString()));
            }

            dict.AddIfNotNullOrEmpty("MinOfficialRating", query.MinOfficialRating);
            dict.AddIfNotNullOrEmpty("MaxOfficialRating", query.MaxOfficialRating);

            dict.Add("recursive", query.Recursive);

            dict.AddIfNotNull("MinIndexNumber", query.MinIndexNumber);

            dict.AddIfNotNull("EnableImages", query.EnableImages);
            if (query.EnableImageTypes != null)
            {
                dict.Add("EnableImageTypes", query.EnableImageTypes.Select(f => f.ToString()));
            }
            dict.AddIfNotNull("ImageTypeLimit", query.ImageTypeLimit);
            dict.AddIfNotNull("CollapseBoxSetItems", query.CollapseBoxSetItems);
            dict.AddIfNotNull("MediaTypes", query.MediaTypes);
            dict.AddIfNotNull("Genres", query.Genres, "|");
            dict.AddIfNotNull("Ids", query.Ids);
            dict.AddIfNotNull("StudioIds", query.StudioIds, "|");
            dict.AddIfNotNull("ExcludeItemTypes", query.ExcludeItemTypes);
            dict.AddIfNotNull("IncludeItemTypes", query.IncludeItemTypes);
            dict.AddIfNotNull("ArtistIds", query.ArtistIds);

            dict.AddIfNotNull("IsPlayed", query.IsPlayed);
            dict.AddIfNotNull("IsInBoxSet", query.IsInBoxSet);

            dict.AddIfNotNull("PersonIds", query.PersonIds);
            dict.AddIfNotNull("PersonTypes", query.PersonTypes);

            dict.AddIfNotNull("Years", query.Years);

            dict.AddIfNotNull("ParentIndexNumber", query.ParentIndexNumber);
            dict.AddIfNotNull("IsHD", query.IsHD);
            dict.AddIfNotNull("HasParentalRating", query.HasParentalRating);

            dict.AddIfNotNullOrEmpty("SearchTerm", query.SearchTerm);

            dict.AddIfNotNull("MinCriticRating", query.MinCriticRating);
            dict.AddIfNotNull("MinCommunityRating", query.MinCommunityRating);

            dict.AddIfNotNull("MinPlayers", query.MinPlayers);
            dict.AddIfNotNull("MaxPlayers", query.MaxPlayers);
            dict.AddIfNotNullOrEmpty("NameStartsWithOrGreater", query.NameStartsWithOrGreater);
            dict.AddIfNotNullOrEmpty("AlbumArtistStartsWithOrGreater", query.AlbumArtistStartsWithOrGreater);

            if (query.LocationTypes != null && query.LocationTypes.Length > 0)
            {
                dict.Add("LocationTypes", query.LocationTypes.Select(f => f.ToString()));
            }
            if (query.ExcludeLocationTypes != null && query.ExcludeLocationTypes.Length > 0)
            {
                dict.Add("ExcludeLocationTypes", query.ExcludeLocationTypes.Select(f => f.ToString()));
            }

            dict.AddIfNotNull("IsMissing", query.IsMissing);
            dict.AddIfNotNull("IsUnaired", query.IsUnaired);
            dict.AddIfNotNull("IsVirtualUnaired", query.IsVirtualUnaired);

            dict.AddIfNotNull("AiredDuringSeason", query.AiredDuringSeason);

            return GetApiUrl("Users/" + query.UserId + "/Items", dict);
        }

        /// <summary>
        /// Gets the next up.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">query</exception>
        protected string GetNextUpUrl(NextUpQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var dict = new QueryStringDictionary { };

            if (query.Fields != null)
            {
                dict.Add("fields", query.Fields.Select(f => f.ToString()));
            }

            dict.Add("ParentId", query.ParentId);

            dict.AddIfNotNull("Limit", query.Limit);

            dict.AddIfNotNull("StartIndex", query.StartIndex);

            dict.AddIfNotNullOrEmpty("SeriesId", query.SeriesId);

            dict.Add("UserId", query.UserId);

            dict.AddIfNotNull("EnableImages", query.EnableImages);
            if (query.EnableImageTypes != null)
            {
                dict.Add("EnableImageTypes", query.EnableImageTypes.Select(f => f.ToString()));
            }
            dict.AddIfNotNull("ImageTypeLimit", query.ImageTypeLimit);

            return GetApiUrl("Shows/NextUp", dict);
        }

        /// <summary>
        /// Gets the similar item list URL.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="type">The type.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// query
        /// or
        /// type
        /// </exception>
        protected string GetSimilarItemListUrl(SimilarItemsQuery query, string type)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            if (string.IsNullOrEmpty(type))
            {
                throw new ArgumentNullException("type");
            }

            var dict = new QueryStringDictionary { };

            dict.AddIfNotNull("Limit", query.Limit);
            dict.AddIfNotNullOrEmpty("UserId", query.UserId);

            if (query.Fields != null)
            {
                dict.Add("fields", query.Fields.Select(f => f.ToString()));
            }

            if (string.IsNullOrEmpty(query.Id))
            {
                throw new ArgumentNullException("query");
            }

            return GetApiUrl(type + "/" + query.Id + "/Similar", dict);
        }

        /// <summary>
        /// Gets the instant mix URL.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="type">The type.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// query
        /// or
        /// type
        /// </exception>
        protected string GetInstantMixUrl(SimilarItemsQuery query, string type)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            if (string.IsNullOrEmpty(type))
            {
                throw new ArgumentNullException("type");
            }

            var dict = new QueryStringDictionary { };

            dict.AddIfNotNull("Limit", query.Limit);
            dict.AddIfNotNullOrEmpty("UserId", query.UserId);

            if (query.Fields != null)
            {
                dict.Add("fields", query.Fields.Select(f => f.ToString()));
            }

            if (string.IsNullOrEmpty(query.Id))
            {
                throw new ArgumentNullException("query");
            }

            return GetApiUrl(type + "/" + query.Id + "/InstantMix", dict);
        }

        /// <summary>
        /// Gets the item by name list URL.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="query">The query.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">query</exception>
        protected string GetItemByNameListUrl(string type, ItemsByNameQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var dict = new QueryStringDictionary { };

            dict.AddIfNotNullOrEmpty("ParentId", query.ParentId);

            dict.Add("UserId", query.UserId);
            dict.AddIfNotNull("StartIndex", query.StartIndex);

            dict.AddIfNotNull("Limit", query.Limit);

            dict.AddIfNotNull("SortBy", query.SortBy);

            if (query.SortOrder.HasValue)
            {
                dict["sortOrder"] = query.SortOrder.ToString();
            }

            dict.AddIfNotNull("IsPlayed", query.IsPlayed);

            if (query.Fields != null)
            {
                dict.Add("fields", query.Fields.Select(f => f.ToString()));
            }

            if (query.Filters != null)
            {
                dict.Add("Filters", query.Filters.Select(f => f.ToString()));
            }

            if (query.ImageTypes != null)
            {
                dict.Add("ImageTypes", query.ImageTypes.Select(f => f.ToString()));
            }

            dict.Add("recursive", query.Recursive);

            dict.AddIfNotNull("MediaTypes", query.MediaTypes);
            dict.AddIfNotNull("ExcludeItemTypes", query.ExcludeItemTypes);
            dict.AddIfNotNull("IncludeItemTypes", query.IncludeItemTypes);

            dict.AddIfNotNullOrEmpty("NameLessThan", query.NameLessThan);
            dict.AddIfNotNullOrEmpty("NameStartsWithOrGreater", query.NameStartsWithOrGreater);

            dict.AddIfNotNull("EnableImages", query.EnableImages);
            if (query.EnableImageTypes != null)
            {
                dict.Add("EnableImageTypes", query.EnableImageTypes.Select(f => f.ToString()));
            }
            dict.AddIfNotNull("ImageTypeLimit", query.ImageTypeLimit);

            return GetApiUrl(type, dict);
        }

        /// <summary>
        /// Gets the image URL.
        /// </summary>
        /// <param name="baseUrl">The base URL.</param>
        /// <param name="options">The options.</param>
        /// <param name="queryParams">The query params.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">options</exception>
        private string GetImageUrl(string baseUrl, ImageOptions options, QueryStringDictionary queryParams)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (queryParams == null)
            {
                throw new ArgumentNullException("queryParams");
            }

            if (options.ImageIndex.HasValue)
            {
                baseUrl += "/" + options.ImageIndex.Value;
            }

            queryParams.AddIfNotNull("Width", options.Width);
            queryParams.AddIfNotNull("Height", options.Height);
            queryParams.AddIfNotNull("MaxWidth", options.MaxWidth);
            queryParams.AddIfNotNull("MaxHeight", options.MaxHeight);
            queryParams.AddIfNotNull("Quality", options.Quality ?? ImageQuality);

            queryParams.AddIfNotNullOrEmpty("Tag", options.Tag);

            queryParams.AddIfNotNull("CropWhitespace", options.CropWhitespace);
            queryParams.Add("EnableImageEnhancers", options.EnableImageEnhancers);

            if (options.Format.HasValue)
            {
                queryParams.Add("Format", options.Format.ToString());
            }

            if (options.AddPlayedIndicator)
            {
                queryParams.Add("AddPlayedIndicator", true);
            }
            queryParams.AddIfNotNull("PercentPlayed", options.PercentPlayed);
            queryParams.AddIfNotNullOrEmpty("BackgroundColor", options.BackgroundColor);

            return GetApiUrl(baseUrl, queryParams);
        }

        /// <summary>
        /// Gets the image URL.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public string GetImageUrl(BaseItemDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.Tag = GetImageTag(item, options);

            return GetImageUrl(item.Id, options);
        }

        public string GetImageUrl(ChannelInfoDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.Tag = item.ImageTags[options.ImageType];

            return GetImageUrl(item.Id, options);
        }

        /// <summary>
        /// Gets an image url that can be used to download an image from the api
        /// </summary>
        /// <param name="itemId">The Id of the item</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">itemId</exception>
        public string GetImageUrl(string itemId, ImageOptions options)
        {
            if (string.IsNullOrEmpty(itemId))
            {
                throw new ArgumentNullException("itemId");
            }

            var url = "Items/" + itemId + "/Images/" + options.ImageType;

            return GetImageUrl(url, options, new QueryStringDictionary());
        }

        /// <summary>
        /// Gets the user image URL.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">user</exception>
        public string GetUserImageUrl(UserDto user, ImageOptions options)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.Tag = user.PrimaryImageTag;

            return GetUserImageUrl(user.Id, options);
        }

        /// <summary>
        /// Gets an image url that can be used to download an image from the api
        /// </summary>
        /// <param name="userId">The Id of the user</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">userId</exception>
        public string GetUserImageUrl(string userId, ImageOptions options)
        {
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException("userId");
            }

            var url = "Users/" + userId + "/Images/" + options.ImageType;

            return GetImageUrl(url, options, new QueryStringDictionary());
        }

        /// <summary>
        /// Gets the person image URL.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public string GetPersonImageUrl(BaseItemPerson item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.Tag = item.PrimaryImageTag;

            return GetImageUrl(item.Id, options);
        }

        /// <summary>
        /// Gets the image tag.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        private string GetImageTag(BaseItemDto item, ImageOptions options)
        {
            if (options.ImageType == ImageType.Backdrop)
            {
                return item.BackdropImageTags[options.ImageIndex ?? 0];
            }

            if (options.ImageType == ImageType.Screenshot)
            {
                return item.ScreenshotImageTags[options.ImageIndex ?? 0];
            }

            if (options.ImageType == ImageType.Chapter)
            {
                return item.Chapters[options.ImageIndex ?? 0].ImageTag;
            }

            return item.ImageTags[options.ImageType];
        }

        /// <summary>
        /// This is a helper to get a list of backdrop url's from a given ApiBaseItemWrapper. If the actual item does not have any backdrops it will return backdrops from the first parent that does.
        /// </summary>
        /// <param name="item">A given item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String[][].</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public string[] GetBackdropImageUrls(BaseItemDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.ImageType = ImageType.Backdrop;

            string backdropItemId;
            string[] backdropImageTags;

            if (item.BackdropImageTags == null || item.BackdropImageTags.Length == 0)
            {
                backdropItemId = item.ParentBackdropItemId;
                backdropImageTags = item.ParentBackdropImageTags;
            }
            else
            {
                backdropItemId = item.Id;
                backdropImageTags = item.BackdropImageTags;
            }

            if (string.IsNullOrEmpty(backdropItemId))
            {
                return new string[] { };
            }

            var files = new string[backdropImageTags.Length];

            for (var i = 0; i < backdropImageTags.Length; i++)
            {
                options.ImageIndex = i;
                options.Tag = backdropImageTags[i];

                files[i] = GetImageUrl(backdropItemId, options);
            }

            return files;
        }

        /// <summary>
        /// This is a helper to get the logo image url from a given ApiBaseItemWrapper. If the actual item does not have a logo, it will return the logo from the first parent that does, or null.
        /// </summary>
        /// <param name="item">A given item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public string GetLogoImageUrl(BaseItemDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.ImageType = ImageType.Logo;

            var logoItemId = HasLogo(item) ? item.Id : item.ParentLogoItemId;
            var imageTag = HasLogo(item) ? item.ImageTags[ImageType.Logo] : item.ParentLogoImageTag;

            if (!string.IsNullOrEmpty(logoItemId))
            {
                options.Tag = imageTag;

                return GetImageUrl(logoItemId, options);
            }

            return null;
        }

        public string GetThumbImageUrl(BaseItemDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.ImageType = ImageType.Thumb;

            var itemId = HasThumb(item) ? item.Id : item.SeriesThumbImageTag != null ? item.SeriesId : item.ParentThumbItemId;
            var imageTag = HasThumb(item) ? item.ImageTags[ImageType.Thumb] : item.SeriesThumbImageTag ?? item.ParentThumbImageTag;

            if (!string.IsNullOrEmpty(itemId))
            {
                options.Tag = imageTag;

                return GetImageUrl(itemId, options);
            }

            return null;
        }

        /// <summary>
        /// This is a helper to get the art image url from a given BaseItemDto. If the actual item does not have a logo, it will return the logo from the first parent that does, or null.
        /// </summary>
        /// <param name="item">A given item.</param>
        /// <param name="options">The options.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public string GetArtImageUrl(BaseItemDto item, ImageOptions options)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.ImageType = ImageType.Art;

            var artItemId = HasArtImage(item) ? item.Id : item.ParentArtItemId;
            var imageTag = HasArtImage(item) ? item.ImageTags[ImageType.Art] : item.ParentArtImageTag;

            if (!string.IsNullOrEmpty(artItemId))
            {
                options.Tag = imageTag;

                return GetImageUrl(artItemId, options);
            }

            return null;
        }

        public bool HasArtImage(BaseItemDto item)
        {
            return item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Art);
        }
        public bool HasLogo(BaseItemDto item)
        {
            return item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Logo);
        }
        public bool HasThumb(BaseItemDto item)
        {
            return item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Thumb);
        }

        /// <summary>
        /// Deserializes from stream.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream">The stream.</param>
        /// <returns>``0.</returns>
        protected T DeserializeFromStream<T>(Stream stream)
            where T : class
        {
            return (T)DeserializeFromStream(stream, typeof(T));
        }

        /// <summary>
        /// Deserializes from stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="type">The type.</param>
        /// <returns>System.Object.</returns>
        /// <exception cref="System.NotImplementedException"></exception>
        protected object DeserializeFromStream(Stream stream, Type type)
        {
            return JsonSerializer.DeserializeFromStream(stream, type);
        }

        /// <summary>
        /// Serializers to json.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns>System.String.</returns>
        protected string SerializeToJson(object obj)
        {
            return JsonSerializer.SerializeToString(obj);
        }

        /// <summary>
        /// Adds the data format.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns>System.String.</returns>
        protected string AddDataFormat(string url)
        {
            const string format = "json";

            if (url.IndexOf('?') == -1)
            {
                url += "?format=" + format;
            }
            else
            {
                url += "&format=" + format;
            }

            return url;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {

        }
    }
}


text:
require 'spec_helper'

RSpec.describe 'Mercatox integration specs' do
  let(:client) { Cryptoexchange::Client.new }
  let(:eth_btc_pair) { Cryptoexchange::Models::MarketPair.new(base: 'ETH', target: 'BTC', market: 'mercatox') }

  it 'fetch pairs' do
    pairs = client.pairs('mercatox')
    expect(pairs).not_to be_empty

    pair = pairs.first
    expect(pair.base).to_not be_empty
    expect(pair.target).to_not be_empty
    expect(pair.market).to eq 'mercatox'
  end

  it 'fetch ticker' do
    ticker = client.ticker(eth_btc_pair)

    expect(ticker.base).to eq 'ETH'
    expect(ticker.target).to eq 'BTC'
    expect(ticker.market).to eq 'mercatox'
    expect(ticker.last).to be_a Numeric
    expect(ticker.bid).to be_a Numeric
    expect(ticker.ask).to be_a Numeric
    expect(ticker.high).to be_a Numeric
    expect(ticker.volume).to be_a Numeric
    expect(ticker.timestamp).to be nil

    expect(ticker.payload).to_not be nil
  end

  it 'fetch order book' do
    order_book = client.order_book(eth_btc_pair)

    expect(order_book.base).to eq 'ETH'
    expect(order_book.target).to eq 'BTC'
    expect(order_book.market).to eq 'mercatox'

    expect(order_book.asks).to_not be_empty
    expect(order_book.bids).to_not be_empty
    expect(order_book.asks.first.price).to_not be_nil
    expect(order_book.bids.first.amount).to_not be_nil
    expect(order_book.bids.first.timestamp).to be_nil
    expect(order_book.asks.count).to be >= 1
    expect(order_book.bids.count).to be >= 1
    expect(order_book.timestamp).to be_nil
    expect(order_book.payload).to_not be nil
  end
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
    value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _httpStatusCodes = require('http-status-codes');

var _httpStatusCodes2 = _interopRequireDefault(_httpStatusCodes);

var _BaseProvision2 = require('../BaseProvision');

var _BaseProvision3 = _interopRequireDefault(_BaseProvision2);

var _q = require('q');

var _q2 = _interopRequireDefault(_q);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var ERROR_VALUE_NOT_ALLOWED = 'value is not allowed. The value should be formatted as follows: ';
var ERROR_DATASTREAM_NOT_ALLOWED = 'Datastream is not allowed';
var schema_base = '/og_basic_types.json';

/**
 * This class allow set simple values.
 */

var SimpleBuilder = (function (_BaseProvision) {
    _inherits(SimpleBuilder, _BaseProvision);

    /**
     * @param {!InternalOpenGateAPI} ogapi - this is ogapi instance
     * @param {!string} resource - this is the resource url where can be create/delete/update/read the entity
     * @param {!array} [allowedDatastreams] - Allowed datastreams to add into the new entity
     * @param {!array} [definedSchemas] - Jsonschema about all OpenGate specific types
     * @param {!Validator} [jsonSchemaValidator] - Json schema validator tool
     */

    function SimpleBuilder(ogapi, resource, allowedDatastreams, definedSchemas, jsonSchemaValidator, timeout) {
        _classCallCheck(this, SimpleBuilder);

        _get(Object.getPrototypeOf(SimpleBuilder.prototype), 'constructor', this).call(this, ogapi, "/organizations/" + resource, timeout);
        if (typeof this._getEntityKey !== "function") {
            throw new Error("Must override method:  _getEntityKey");
        }
        this._setUrlParameters({
            flattened: true
        });
        this._entity = {};
        this._allowedDatastreams = allowedDatastreams;
        this._definedSchemas = definedSchemas;
        this._jsonSchemaValidator = jsonSchemaValidator;
    }

    _createClass(SimpleBuilder, [{
        key: '_buildURL',
        value: function _buildURL() {
            return this._resource + "/" + this.getEntityKey();
        }
    }, {
        key: '_validate',
        value: function _validate() {
            var _this = this;
            var errors = [];
            Object.keys(this._entity).forEach(function (_id) {
                if (_id != 'resourceType') {
                    (function () {
                        if (!_this._definedSchemas[_id]) {
                            throw new Error(ERROR_DATASTREAM_NOT_ALLOWED + ': ' + _id);
                        }
                        var jSchema = _this._definedSchemas[_id].value;
                        if (_this._entity[_id].constructor === Array) {
                            _this._entity[_id].forEach(function (item) {
                                var value = item._value._current.value;
                                if (!_this._jsonSchemaValidator.validate(schema_base, value)) {
                                    errors.push(_id + ' [' + value + '] ' + ERROR_VALUE_NOT_ALLOWED + JSON.stringify(jSchema));
                                }
                            });
                        } else {
                            var value = _this._entity[_id]._value._current.value;
                            if (!_this._jsonSchemaValidator.validate(schema_base, value)) {
                                errors.push(_id + ' [' + value + '] ' + ERROR_VALUE_NOT_ALLOWED + JSON.stringify(jSchema));
                            }
                        }
                    })();
                }
            });

            if (errors.length > 0) {
                throw new Error(JSON.stringify(errors).replace(new RegExp("\"", 'g'), ""));
            }
        }
    }, {
        key: '_composeElement',
        value: function _composeElement() {
            this._validate();
            return this._entity;
        }

        /**
         * @return {string} - Entity identifier
         */
    }, {
        key: 'getEntityKey',
        value: function getEntityKey() {
            return this._getEntityKey() !== null ? this._getEntityKey()._value._current.value : null;
        }

        /**
         * Set new datastream value
         *
         * @param {!string} _id - Datastream identifier
         * @param {!objecr} val - Datastream value. If this value is null then datastream value will be removed.
         */
    }, {
        key: 'with',
        value: function _with(_id, val) {
            if (val === undefined || val.length === 0) {
                // Si es un array vacío debe continuar
                if (!_lodash2['default'].isArray(val)) {
                    delete this._entity[_id];
                    return this;
                }
            }

            if (this.getAllowedDatastreams().filter(function (ds) {
                return ds.identifier === _id;
            }).length !== 1) {
                console.warn('Datastream not found or operations can not be performed on it. This value will be ignored. Datastream Name: ' + _id);
                return this;
            }
            this._entity[_id] = {
                '_value': {
                    '_current': {
                        'value': val
                    }
                }
            };
            return this;
        }

        /**
         * @return {array} - Allowed Datastream definition array
         */
    }, {
        key: 'getAllowedDatastreams',
        value: function getAllowedDatastreams() {
            return this._allowedDatastreams;
        }
    }, {
        key: 'initFromFlattened',
        value: function initFromFlattened(_flattenedEntityData) {
            var _this = this;
            if (_flattenedEntityData && Object.keys(_flattenedEntityData).length > 0) {
                Object.keys(_flattenedEntityData).forEach(function (_id) {
                    if (_id.toLowerCase().startsWith("provision")) {
                        var _content = _flattenedEntityData[_id];
                        if (Array.isArray(_content)) {
                            _content = _content[0];
                        }
                        _this['with'](_id, _content._value._current.value);
                    }
                });
            }
        }
    }, {
        key: '_initFromJson',
        value: function _initFromJson(_jsonEntityData, _path) {
            var _this = this;
            if (_jsonEntityData) {
                var keys = Object.keys(_jsonEntityData);
                keys.forEach(function (key) {
                    var obj = _jsonEntityData[key];
                    var _current = obj._current;
                    var path = _path ? _path + '.' + key : key;
                    if (_current) {
                        _this['with'](path, _current.value);
                    } else {
                        if (Array.isArray(obj)) {
                            _this._initFromJson(obj[0], path + '[]');
                        } else {
                            _this._initFromJson(obj, path);
                        }
                    }
                });
            }
        }
    }, {
        key: 'initFromJson',
        value: function initFromJson(_jsonEntityData) {
            var _this = this;
            var provision = {};
            if (_jsonEntityData && (provision = _jsonEntityData.provision)) {
                _this._initFromJson(provision, 'provision');
            }
        }

        /**
         * This invoke a request to OpenGate North API and the callback is managed by promises
         * This function deletes a entity of provision
         * @return {Promise}
         * @property {function (result:object, statusCode:number)} then - When request it is OK
         * @property {function (error:string)} catch - When request it is NOK
         */
    }, {
        key: 'deleteAll',
        value: function deleteAll() {
            var defered = _q2['default'].defer();
            var promise = defered.promise;
            this._setUrlParameters({
                full: true
            });
            this._ogapi.Napi['delete'](this._buildURL(), this._timeout, this._getExtraHeaders(), this._getUrlParameters()).then(function (res) {
                if (res.statusCode === _httpStatusCodes2['default'].OK) {
                    defered.resolve({
                        statusCode: res.statusCode
                    });
                } else {
                    defered.reject({
                        errors: res.errors,
                        statusCode: res.statusCode
                    });
                }
            })['catch'](function (error) {
                defered.reject(error);
            });
            return promise;
        }

        /**
         * This invoke a request to OpenGate North API and the callback is managed by promises
         * This function updates a entity of provision
         * @return {Promise}
         * @property {function (result:object, statusCode:number)} then - When request it is OK
         * @property {function (error:string)} catch - When request it is NOK
         * @example
         *  ogapi.organizationsBuilder().update()
         */
    }, {
        key: 'update',
        value: function update() {
            var defered = _q2['default'].defer();
            var promise = defered.promise;

            this._ogapi.Napi.put(this._buildURL(), this._composeUpdateElement(), this._timeout, this._getExtraHeaders(), this._getUrlParameters()).then(function (res) {
                if (res.statusCode === 200) {
                    defered.resolve({
                        statusCode: res.statusCode
                    });
                } else if (res.status === 200) {
                    defered.resolve({
                        statusCode: res.status
                    });
                } else {
                    defered.reject({
                        errors: res.errors,
                        statusCode: res.statusCode
                    });
                }
            })['catch'](function (error) {
                defered.reject(error);
            });
            return promise;
        }

        /**
         * This invoke a request to OpenGate North API and the callback is managed by promises
         * This function patch a entity of provision
         * @return {Promise}
         * @property {function (result:object, statusCode:number)} then - When request it is OK
         * @property {function (error:string)} catch - When request it is NOK
         * @example
         *  ogapi.organizationsBuilder().update()
         */
    }, {
        key: 'patch',
        value: function patch() {
            var defered = _q2['default'].defer();
            var promise = defered.promise;

            this._ogapi.Napi.patch(this._buildURL(), this._composeUpdateElement(), this._timeout, this._getExtraHeaders(), this._getUrlParameters()).then(function (res) {
                if (res.statusCode === 200) {
                    defered.resolve({
                        statusCode: res.statusCode
                    });
                } else if (res.status === 200) {
                    defered.resolve({
                        statusCode: res.status
                    });
                } else {
                    defered.reject({
                        errors: res.errors,
                        statusCode: res.statusCode
                    });
                }
            })['catch'](function (error) {
                defered.reject(error);
            });
            return promise;
        }
    }]);

    return SimpleBuilder;
})(_BaseProvision3['default']);

exports['default'] = SimpleBuilder;
module.exports = exports['default'];
//# sourceMappingURL=SimpleBuilder.js.map


text:
//
//  LFSAskForRewiewService.h
//  FXStreet
//
//  Created by Lluís Gómez Hernando on 18/12/13.
//  Copyright (c) 2013 Lafosca. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol LFSAskForReviewServiceDataSource <NSObject>

@required

/**
 For a given action, returns the number of repetitions that must happen before showing the alert asking for a review.
 */
- (NSUInteger)necessaryRepetitionsForAction:(NSString *)action;

/**
 Returns the message to be displayed in the alert.
 */
- (NSString *)message;

/**
 Returns the title to be displayed in the alert.
 */
- (NSString *)title;

/**
 Returns the title for the positive answer button of the alert.
 */
- (NSString *)positiveButtonTitle;

/**
 Returns the title for the negative answer button of the alert.
 */
- (NSString *)negativeButtonTitle;

@end

@protocol LFSAskForReviewServiceDelegate <NSObject>

@required

/**
 Handles user's positive response to the ask for review alert.
 */
- (void)userResponseWasPositive;

/**
 Handles user's negative response to the ask for review alert.
 */
- (void)userResponseWasNegative;
@end

@interface LFSAskForReviewService : NSObject

@property (strong, nonatomic) id<LFSAskForReviewServiceDataSource>dataSource;
@property (strong, nonatomic) id<LFSAskForReviewServiceDelegate>delegate;

//Singleton
+ (LFSAskForReviewService *)sharedService;

//Method to call when the user action that could trigger the ask for review alert happened.
- (void)askIfNecessaryAfterUserAction:(NSString *)action;

@end


text:
@section('scripts')

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

@stop

@section('module')

   @if($status=='estatus-A')

 Se ha prestado un archivo

  @endif
    @if($status=='estatus-B')

 Archivo devuelto correctamente

  @endif
 @if($status=='validar')

El campo persona y folio son obligatorios

  @endif
 @if($status=='prestamo')

Este archivo esta en prestamo

  @endif

       Nuevo

Prestamo de documentos

                        Folio
                        Fecha salida
                        Fecha de regreso
                        Comentario
                        Persona
                        Estatus
                        Operación

                       @foreach($archivos as $archivo)

                        {{{$archivo->folio}}}
                        {{{$archivo->fecha_salida}}}
                        {{{$archivo->fecha_regreso}}}
                        {{{$archivo->comentario}}}
                        {{{$archivo->nombre}}}
                         @if ( $archivo->activo == 1 )
                          Prestado
                        @else
                        Devuelto
                          @endif
                         @if($archivo->activo == 1)
                        id}}" data-toggle="modal" data-target="#entrega" title="Devolver archivo"  class="btn btn-xs btn-danger"  >
                        @else
                        id )}}">
                         @endif

                      @endforeach

                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Registrar un prestamo

{{ Form::open(array('action' => 'ArchivoDocumentosControlador@postRegistro', 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'post', 'id' => 'new_prestamo','files' => true )) }}

                                  Folio

                                    <input type="text" class="form-control"  name="folio" required>

                                  Personas

                                    <select class="form-control persona chosen-select" name="persona_id">
                                      <option value="0">Seleccione</option>
                                     @foreach($personas as $persona)
                                      <option value="{{{$persona->id}}}">{{{$persona->nombre}}}</option>
                                      @endforeach
                                    </select>

             Fecha prestamo

                    <input data-format="yyyy-MM-dd" type='text' class="form-control" name="fecha_salida" />

                                  Comentarios

                                    <textarea type="text" class="form-control"  name="comentario" ></textarea>

                  <button type="button" class="btn btn-default" data-dismiss="modal" aria-hidden="true">Cancelar</button>
                    <button type="submit"  class="btn btn-primary">Guardar</button>

   {{form::close()}}

                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Registrar un prestamo

     {{ Form::open(array('action' => 'ArchivoDocumentosControlador@postEntrega', 'class' => 'form-horizontal', 'role' => 'form', 'id' => 'registro')) }}

                     <input  type="hidden" id="entrega" name="archivo_id">

                                  Fecha regreso

 <input type="text" id="datepicker"  placeholder="Seleccione fecha" name="fecha_regreso">

                  <button type="button" class="btn btn-default" data-dismiss="modal" aria-hidden="true">Cancelar</button>
                    <button type="submit"  class="btn btn-primary">Guardar</button>

   {{form::close()}}

@stop


text:
class Persona():

    def __init__(self, edad, nombre, sexo, nivel):
        self.edad = edad
        self.nombre = nombre
        self.sexo = sexo
        self.nivel = nivel

    def imprimir(self):
        print(self.edad // self.nivel)

    def nombrar(self):
        if self.nombre == "Jesus":
            print("Nada")
        if self.nombre == "Gabriel":
            print(self.nivel)
        if 1==0:
            pass
        else:
            print("No es ninguna de las anteriores")

gabriel = Persona(3, "Gabriel", "Femenino", 1)
jesus = Persona(4, "Jesus", "Masculino", 2)

gabriel.nombrar()


text:
package cmd

import (
	"github.com/google/go-containerregistry/pkg/crane"
	"github.com/spf13/cobra"
)

// NewCmdCopy creates a new cobra.Command for the copy subcommand.
func NewCmdCopy(options *[]crane.Option) *cobra.Command {
	return &cobra.Command{
		Use:     "copy SRC DST",
		Aliases: []string{"cp"},
		Short:   "Efficiently copy a remote image from src to dst while retaining the digest value",
		Args:    cobra.ExactArgs(2),
		RunE: func(_ *cobra.Command, args []string) error {
			src, dst := args[0], args[1]
			return crane.Copy(src, dst, *options...)
		},
	}
}


text:
<!doctype HTML>

  <title>Blog: Hong Shick Pak</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="author" content="Hong Shick Pak">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="keywords" content="Michael Pak, Hong Shick Pak, Hong, Shick, Pak, Michael, hspak, blog">
  <meta name="description" content="Hspak: {{ index .Params "description" | default "Blog of Hong Shick Pak" }}">
  <meta property="og:url" content="{{ .URL | absURL }}">
  <meta property="og:type" content="website">
  <meta property="og:site_name" content="Hspak">
  <meta property="og:title" content="{{ index .Params "title" }}">
  <meta property="og:description" content="Hspak: {{ index .Params "description" | default "Blog of Hong Shick Pak" }}">
  <meta property="twitter:creator" content="@hspasta">
  {{ range .AlternativeOutputFormats -}}
    {{ printf `<link rel="%s" type="%s" href="%s" title="%s" />` .Rel .MediaType.Type .Permalink $.Site.Title | safeHTML }}
  {{ end -}}
  <link rel="canonical" href="{{ .Site.BaseURL }}">
  <link rel="stylesheet" href="{{ "css/style.css" | absURL }}" />

Blog


text:
Backup and restore PostgreSQL databases based on duplicity. The modules makes sure a database dump is include in the
referenced duplicity backup and restores this previously taken dump in case the existing database is empty.

##Usage

Make sure, the parent backup directory (`/var/backups`) is properly existing:

```
file { '/var/backups':
  ensure => directory,
  owner  => 'root',
  group  => 'root',
  mode   => '0644',
}
```

Now you're ready to manage a database:

```
duplicity_postgresql::database { 'my-database':
  profile => 'system',
}
```

This will create a dump of the PostgreSQL database `my-database` each time the backup profile `system` is run. The dump
will be keep in the default backup directory. If the database is existing but empty, the dump will be restored. In case
the dump file is missing, Puppet will attempt to restore the file from the last backup.

If you just want to backup the database but don't restore it, set the `ensure` parameter to `backup`:

```
duplicity_postgresql::database { 'my-database':
  ensure  => backup,
  profile => 'system',
}
```

##Limitations

The module has been tested on the following operating systems. Testing and patches for other platforms are welcome.

* Debian Linux 6.0 (Squeeze)

[![Build Status](https://travis-ci.org/tohuwabohu/tohuwabohu-duplicity_postgresql.png?branch=master)](https://travis-ci.org/tohuwabohu/tohuwabohu-duplicity_postgresql)

##Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<head>
  <link rel="stylesheet" href="/packages/fullcalendar_fullcalendar/dist/fullcalendar.print.css" media="print">
</head>


text:
This is a template for chat bots, written in Javascript for Node.js.

## Features
### Input/Output
* Telegram (https://github.com/yagop/node-telegram-bot-api)
* IRC (https://github.com/martynsmith/node-irc)

### Behaviors
* Telegram/IRC two way relay

## Installation & run
1. Clone the repository
2. Run install.sh
3. Write a config.json file. You can use the [config.example.json](https://github.com/Jei/skeleton.ai/blob/master/config.example.json) as a reference.
4. Run `node main.js` (you may need to add the flag `--use-strict` depending on your node version)
5. Enjoy!

## Planned features
* Bot actions!
* Integration with [api.ai](https://api.ai/)
* Input/Output whitelist and blacklist
* Memory features
* Configuration file passed as command line argument


text:
import conversion as conv
import instruction as ins
import stack

# convert an instruction to a binary string(s)
# returns a 3-tuple of opcode, inst, format
# convert_instruction(inst)

# convert an register to a binary string
# returns a 2-tuple of binary version and decimal version
# convert_register(reg)

# convert an immediate value to a binary string
# will throw an error if the value is too large for MIPS
# convert_immediate(imm)

# takes a whole line as input and returns a binary string of the instruction
# as represented in MIPS machine code
# convert_line(line)

class Program:

	# create a new MIPS program to simulate
	# source should contain a list of mips source code, line by line
	def __init__(self, source):
		self.instructions = []
		self.machine_code = []
		self.registers = [0] * 32
		self.registers[29] = 0x1000
		self.labels = {}
		self.pc = 0
		self.memory = stack.Stack(self.registers[29])
		self.hi = 0
		self.lo = 0

		counter = 0

		# build the label dictionary ahead of time
		addr_counter = 0
		for line in source:
			# remove comments and whitespace
			tokens = line.split("#")[0].split()
			tokens = [i.split(",")[0].lstrip().rstrip() for i in tokens]
			i = 0
			while i < len(tokens):
				if tokens[i].find(":") != -1:
					self.labels[tokens[i][:-1]] = addr_counter
					tokens.pop(i)
				else:
					i += 1
			if len(tokens) > 0:
				addr_counter += ins.Instruction.SIZE

		# now create instructions
		line_counter = 0
		for line in source:
			inst = conv.convert_line(line, counter, self.labels)
			if inst != None:
				new_instruction = ins.Instruction(self, line, line_counter)
				self.machine_code.append(inst)
				self.instructions.append(new_instruction)
				counter += ins.Instruction.SIZE
			line_counter += 1
		self.inst_count = counter // 4

	def is_finished(self):
		return self.pc // 4 >= self.inst_count

	def step_once(self):
		inst = self.instructions[self.pc // 4]
		self.pc = inst.execute(self.pc, self.labels)

	def reset(self):
		self.registers = [0] * 32
		self.registers[29] = 0x1000
		self.pc = 0
		self.memory = stack.Stack(self.registers[29])
		self.hi = 0
		self.lo = 0

	def get_all_registers(self):
		return self.registers

	def get_register(self, reg):
		regi = int(reg)
		if(regi < 32 and regi >= 0):
			return self.registers[regi]
		else:
			print("Error: invalid register")

	def set_hi(self, value):
		# check that value will fit in register
		assert(len(bin(value).replace("-", "")) <= 32)
		self.hi = value

	def get_hi(self):
		return self.hi

	def set_lo(self, value):
		# check that value will fit in register
		assert(len(bin(value).replace("-", "")) <= 32)
		self.lo = value

	def get_lo(self):
		return self.lo

	def set_register(self, reg, value):
		# check that value will fit in register
		assert(len(bin(value).replace("-", "")) <= 32)

		regi = int(reg)
		if(regi < 32 and regi > 0):
			self.registers[regi] = value
		elif regi == 0:
			pass
		else:
			print("Error: invalid register")

	def get_stack(self):
		return self.memory

	def get_memory(self, reg, offset):
		pass

	def set_memory(self, reg, offset, value):
		pass


text:
var swig = require('swig');
var fs = require('fs');
var file = require('./file');

module.exports.template = function template(template, outputFileName, templateOptions, fileOptions, callback) {
  fs.realpath(template, function(err, path){
    if(err) {
      callback(err);
      return;
    }
    swig.renderFile(path, templateOptions, function(err, output){
      if(err) {
        callback(err);
      }
      else {
        file.writeFile(outputFileName, output, fileOptions, function(err){
          callback(err);
        });
      }
    });
  });
};


text:
package io.magentys.cinnamon.webdriver.conditions;

import io.magentys.cinnamon.webdriver.conditions.Condition;

public class NotCondition<T> extends Condition<T> {

    private final Condition<T> condition;

    public NotCondition(final Condition<T> condition) {
        this.condition = condition;
    }

    @Override
    public boolean apply(final T t) {
        try {
            return !condition.apply(t);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public String toString() {
        return "not(" + condition.toString() + ")";
    }

}


text:
>文档地址: [https://developer.apple.com/library/prerelease/content/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html#//apple_ref/doc/uid/TP40009503-CH2-SW7](https://developer.apple.com/library/prerelease/content/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html#//apple_ref/doc/uid/TP40009503-CH2-SW7)

</br>

Coordinate system transformations offer a way to alter your view (or its contents) quickly and easily. An affine transform is a mathematical matrix that specifies how points in one coordinate system map to points in a different coordinate system. You can apply affine transforms to your entire view to change the size, location, or orientation of the view relative to its superview. You can also use affine transforms in your drawing code to perform the same types of manipulations to individual pieces of rendered content. How you apply the affine transform therefore depends on context:

* To modify your entire view, modify the affine transform in the transform property of your view.

* To modify specific pieces of content in your view's drawRect: method, modify the affine transform associated with the active graphics context.

</br>

You typically modify the transform property of a view when you want to implement animations. For example, you could use this property to create an animation of your view rotating around its center point. You would not use this property to make permanent changes to your view, such as modifying its position or size a view within its superview's coordinate space. For that type of change, you should modify the frame rectangle of your view instead.

</br>

> Note: When modifying the transform property of your view, all transformations are performed relative to the center point of the view.

</br>

In your view's drawRect: method, you use affine transforms to position and orient the items you plan to draw. Rather than fix the position of an object at some location in your view, it is simpler to create each object relative to a fixed point, typically (0, 0), and use a transform to position the object immediately prior to drawing. That way, if the position of the object changes in your view, all you have to do is modify the transform, which is much faster and less expensive than recreating the object at its new location. You can retrieve the affine transform associated with a graphics context using the CGContextGetCTM function and you can use the related Core Graphics functions to set or modify this transform during drawing.

</br>

The current transformation matrix (CTM) is the affine transform in use at any given time. When manipulating the geometry of your entire view, the CTM is the affine transform stored in your view's transform property. Inside your drawRect: method, the CTM is the affine transform associated with the active graphics context.

</br>

The coordinate system of each subview builds upon the coordinate systems of its ancestors. So when you modify a view's transform property, that change affects the view and all of its subviews. However, these changes affect only the final rendering of the views on the screen. Because each view draws its content and lays out its subviews relative to its own bounds, it can ignore its superview's transform during drawing and layout.

</br>

Figure 1-6 demonstrates how two different rotation factors combine visually when rendered. Inside the view's drawRect: method, applying a 45 degree rotation factor to a shape causes that shape to appear rotated by 45 degrees. Applying a separate 45 degree rotation factor to the view then causes the shape to appear to be rotated by 90 degrees. The shape is still rotated by only 45 degrees relative to the view that drew it, but the view rotation makes it appear to be rotated by more.

</br>

Figure 1-6  Rotating a view and its content

</br>

![xform_rotations.jpg](https://developer.apple.com/library/prerelease/content/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/Art/xform_rotations.jpg)

</br>

> Important: If a view's transform property is not the identity transform, the value of that view's frame property is undefined and must be ignored. When applying transforms to a view, you must use the view's bounds and center properties to get the size and position of the view. The frame rectangles of any subviews are still valid because they are relative to the view's bounds.

</br>

For information about modifying your view's transform property at runtime, see Translating, Scaling, and Rotating Views. For information about how to use transforms to position content during drawing, see Drawing and Printing Guide for iOS.


text:
package setup

import (
	"archive/tar"
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"

	"github.com/go-playground/log"
)

// RestoreOptions : Define the options for restore a dump file into a database
type RestoreOptions struct {
	CustomArgs []string
}
/*
RestoreSQLFile : Calls the 'psql' to restore a gzipped file gererated by pg_dump + gzip
*/
func RestoreSQLFile(connDetail ConnectionDetails, dumpFile string, exists bool) error {
	//
	// new dumfile format:
	//
	// ---------------------------------------------------------------------
	// |                            tar file                               |
	// ---------------------------------------------------------------------
	// |   internal_dump_schema_dbview.gz | internal_dump_schema_user.gz   |
	// ---------------------------------------------------------------------

	psqlBin := "psql"
	psqlArgs := []string{"-v", "ON_ERROR_STOP=1", "-1", "-X"}
	psqlConn := formatConnectionOptions(connDetail)

	if pgsqlBinPATH != "" {
		psqlBin = fmt.Sprintf("%s/psql", pgsqlBinPATH)
	}

	psqlArgs = append(psqlArgs, psqlConn...)

	if connDetail.Password != "" {
		err := os.Setenv("PGPASSWORD", connDetail.Password)

		if err != nil {
			return err
		}
	}

	log.Debugf("%s %#v\n", psqlBin, psqlArgs)

	f, err := os.Open(dumpFile)
	defer f.Close()

	if err != nil {
		return err
	}

	tarFile := tar.NewReader(f)

	for {
		var out bytes.Buffer
		var stderr bytes.Buffer
		psqlCmd := exec.Command(psqlBin, psqlArgs...)
		psqlCmd.Stdout = &out
		psqlCmd.Stderr = &stderr

		hdr, err := tarFile.Next()

		if err == io.EOF {
			break
		}

		if err != nil {
			return err
		}

		log.Debugf("restoring: %s", hdr.Name)
		if exists && strings.HasPrefix(hdr.Name, "internal_dump_schema_dbview") {
			log.Warn("dbview schema already exists, ignoring to restore it")
			continue
		} else {
			reader, err := gzip.NewReader(tarFile)

			if err != nil {
				return err
			}

			psqlCmd.Stdin = reader

			if err := psqlCmd.Run(); err != nil {
				return fmt.Errorf(
					fmt.Sprintf(
						"%s. %s\nCMD: %s %s",
						fmt.Sprint(err),
						stderr.String(),
						psqlBin,
						psqlArgs))
			}
		}
	}

	return nil
}

/*
RestoreDumpFile : Calls the 'pg_restore' to restore a dump file gererated by pg_dump
*/
func RestoreDumpFile(connDetail ConnectionDetails, dumpFile string, options RestoreOptions) error {

	pgRestoreBin := "pg_restore"

	if pgsqlBinPATH != "" {
		pgRestoreBin = fmt.Sprintf("%s/pg_restore", pgsqlBinPATH)
	}

	// conn := formatConnectionOptions(connDetail)
	args := formatConnectionOptions(connDetail)

	args = append(args, options.CustomArgs...)
	args = append(args, dumpFile)

	if connDetail.Password != "" {
		err := os.Setenv("PGPASSWORD", connDetail.Password)

		if err != nil {
			return err
		}
	}

	log.Debugf("%s %#v\n", pgRestoreBin, args)

	cmd := exec.Command(pgRestoreBin, args...)

	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf(
			fmt.Sprintf(
				"%s. %s\nCMD: %s %s",
				fmt.Sprint(err),
				stderr.String(),
				pgRestoreBin,
				args))
	}

	return nil
}

func formatConnectionOptions(connDetail ConnectionDetails) []string {

	out := []string{}

	if connDetail.Username != "" {
		out = append(out, "--username="+connDetail.Username)
	}
	if connDetail.Host != "" {
		out = append(out, "--host="+connDetail.Host)
	}
	if connDetail.Database != "" {
		out = append(out, "--dbname="+connDetail.Database)
	}
	if connDetail.Port > 0 {
		out = append(out, fmt.Sprintf("--port=%d", connDetail.Port))
	}

	return out
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OptionsColor_1 = require("./OptionsColor");
var LineLinked_1 = require("./LineLinked/LineLinked");
var Move_1 = require("./Move");
var ParticlesNumber_1 = require("./ParticlesNumber");
var Opacity_1 = require("./Opacity/Opacity");
var Shape_1 = require("./Shape/Shape");
var Size_1 = require("./Size/Size");
var Rotate_1 = require("./Rotate/Rotate");
var Shadow_1 = require("./Shadow");
var Stroke_1 = require("./Stroke");
var Collisions_1 = require("./Collisions");
var Twinkle_1 = require("./Twinkle/Twinkle");
var Particles = (function () {
    function Particles() {
        this.collisions = new Collisions_1.Collisions();
        this.color = new OptionsColor_1.OptionsColor();
        this.lineLinked = new LineLinked_1.LineLinked();
        this.move = new Move_1.Move();
        this.number = new ParticlesNumber_1.ParticlesNumber();
        this.opacity = new Opacity_1.Opacity();
        this.rotate = new Rotate_1.Rotate();
        this.shadow = new Shadow_1.Shadow();
        this.shape = new Shape_1.Shape();
        this.size = new Size_1.Size();
        this.stroke = new Stroke_1.Stroke();
        this.twinkle = new Twinkle_1.Twinkle();
    }
    Object.defineProperty(Particles.prototype, "line_linked", {
        get: function () {
            return this.lineLinked;
        },
        set: function (value) {
            this.lineLinked = value;
        },
        enumerable: true,
        configurable: true
    });
    Particles.prototype.load = function (data) {
        var _a, _b, _c, _d, _e, _f;
        if (data !== undefined) {
            if (data.color !== undefined) {
                if (data.color instanceof Array) {
                    this.color = data.color.map(function (s) { return OptionsColor_1.OptionsColor.create(undefined, s); });
                }
                else {
                    if (this.color instanceof Array) {
                        this.color = new OptionsColor_1.OptionsColor();
                    }
                    this.color = OptionsColor_1.OptionsColor.create(this.color, data.color);
                }
            }
            var lineLinked = (_a = data.lineLinked) !== null && _a !== void 0 ? _a : data.line_linked;
            if (lineLinked !== undefined) {
                this.lineLinked.load(lineLinked);
            }
            this.move.load(data.move);
            this.number.load(data.number);
            this.opacity.load(data.opacity);
            this.rotate.load(data.rotate);
            this.shape.load(data.shape);
            this.size.load(data.size);
            this.shadow.load(data.shadow);
            this.twinkle.load(data.twinkle);
            var collisions = (_c = (_b = data.move) === null || _b === void 0 ? void 0 : _b.collisions) !== null && _c !== void 0 ? _c : (_d = data.move) === null || _d === void 0 ? void 0 : _d.bounce;
            if (collisions !== undefined) {
                this.collisions.enable = collisions;
            }
            this.collisions.load(data.collisions);
            var strokeToLoad = (_e = data.stroke) !== null && _e !== void 0 ? _e : (_f = data.shape) === null || _f === void 0 ? void 0 : _f.stroke;
            if (strokeToLoad !== undefined) {
                if (strokeToLoad instanceof Array) {
                    this.stroke = strokeToLoad.map(function (s) {
                        var tmp = new Stroke_1.Stroke();
                        tmp.load(s);
                        return tmp;
                    });
                }
                else {
                    if (this.stroke instanceof Array) {
                        this.stroke = new Stroke_1.Stroke();
                    }
                    this.stroke.load(strokeToLoad);
                }
            }
        }
    };
    return Particles;
}());
exports.Particles = Particles;


text:
package direct.traffic.archivespark.specific.warc

/**
  * Created by boris on 26.09.17.
  */
import java.io.InputStream

import de.l3s.archivespark.dataspecs.DataEnrichRoot
import de.l3s.archivespark.dataspecs.access.DataAccessor
import de.l3s.archivespark.enrich.RootEnrichFunc
import de.l3s.archivespark.enrich.dataloads.ByteContentLoad
import de.l3s.archivespark.specific.warc.{CdxRecord, RawArchiveRecord, WarcRecord}
import de.l3s.archivespark.specific.warc.enrichfunctions.WarcPayload

class WarcJRecord[CdxJson <: MinimumJCdxJson ](cdx: JCdxRecord[CdxJson], filename: String, data: DataAccessor[InputStream]) extends DataEnrichRoot[JCdxRecord[CdxJson], RawArchiveRecord](cdx) with ByteContentLoad {
  override def access[R >: Null](action: RawArchiveRecord => R): R = {
    data.access{ stream =>
      val record = RawArchiveRecord(filename, stream)
      if (record != null) action(record)
      else null
    }
  }

  override def defaultEnrichFunction(field: String): Option[RootEnrichFunc[_]] = {
    field match {
      case ByteContentLoad.Field => Some(WarcPayload)
      case _ => None
    }
  }
}

object WarcJRecord {
  implicit def warcJRecordToCdxRecord[CdxJson <: MinimumJCdxJson  ](record: WarcJRecord[CdxJson]): JCdxRecord[CdxJson] = record.get
}