text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Instance.Discovery;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.TelemetryCore.Internal.Events;
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Client.TelemetryCore;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.Identity.Client.TelemetryCore.TelemetryClient;
using System.Net.Http;

namespace Microsoft.Identity.Client.Internal.Requests
{
    /// <summary>
    /// Base class for all flows. Use by implementing <see cref="ExecuteAsync(CancellationToken)"/>
    /// and optionally calling protected helper methods such as SendTokenRequestAsync, which know
    /// how to use all params when making the request.
    /// </summary>
    internal abstract class RequestBase
    {
        internal AuthenticationRequestParameters AuthenticationRequestParameters { get; }
        internal ICacheSessionManager CacheManager => AuthenticationRequestParameters.CacheSessionManager;
        internal IServiceBundle ServiceBundle { get; }

        protected RequestBase(
            IServiceBundle serviceBundle,
            AuthenticationRequestParameters authenticationRequestParameters,
            IAcquireTokenParameters acquireTokenParameters)
        {
            ServiceBundle = serviceBundle ??
                throw new ArgumentNullException(nameof(serviceBundle));

            AuthenticationRequestParameters = authenticationRequestParameters ??
                throw new ArgumentNullException(nameof(authenticationRequestParameters));

            if (acquireTokenParameters == null)
            {
                throw new ArgumentNullException(nameof(acquireTokenParameters));
            }

            ValidateScopeInput(authenticationRequestParameters.Scope);
            acquireTokenParameters.LogParameters(AuthenticationRequestParameters.RequestContext.Logger);
        }

        /// <summary>
        /// Return a custom set of scopes to override the default MSAL logic of merging
        /// input scopes with reserved scopes (openid, profile etc.)
        /// Leave as is / return null otherwise
        /// </summary>
        protected virtual SortedSet<string> GetOverriddenScopes(ISet<string> inputScopes)
        {
            return null;
        }

        private void ValidateScopeInput(ISet<string> scopesToValidate)
        {
            if (scopesToValidate.Contains(AuthenticationRequestParameters.AppConfig.ClientId))
            {
                throw new ArgumentException("API does not accept client id as a user-provided scope");
            }
        }

        protected abstract Task<AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken);

        public async Task<AuthenticationResult> RunAsync(CancellationToken cancellationToken = default)
        {
            Stopwatch sw = Stopwatch.StartNew();

            ApiEvent apiEvent = InitializeApiEvent(AuthenticationRequestParameters.Account?.HomeAccountId?.Identifier);
            AuthenticationRequestParameters.RequestContext.ApiEvent = apiEvent;
            MsalTelemetryEventDetails telemetryEventDetails = new MsalTelemetryEventDetails(TelemetryConstants.AcquireTokenEventName);
            ITelemetryClient[] telemetryClients = AuthenticationRequestParameters.RequestContext.ServiceBundle.Config.TelemetryClients;

            using (AuthenticationRequestParameters.RequestContext.CreateTelemetryHelper(apiEvent))
            {
                try
                {
                    AuthenticationRequestParameters.LogParameters();
                    LogRequestStarted(AuthenticationRequestParameters);

                    AuthenticationResult authenticationResult = await ExecuteAsync(cancellationToken).ConfigureAwait(false);
                    LogReturnedToken(authenticationResult);
                    UpdateTelemetry(sw, apiEvent, authenticationResult);
                    LogMetricsFromAuthResult(authenticationResult, AuthenticationRequestParameters.RequestContext.Logger);
                    LogSuccessfulTelemetryToClient(authenticationResult, telemetryEventDetails, telemetryClients);

                    return authenticationResult;
                }
                catch (MsalException ex)
                {
                    apiEvent.ApiErrorCode = ex.ErrorCode;
                    AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(ex);
                    LogErrorTelemetryToClient(ex.ErrorCode, telemetryEventDetails, telemetryClients);
                    throw;
                }
                catch (Exception ex)
                {
                    apiEvent.ApiErrorCode = ex.GetType().Name;
                    AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(ex);
                    throw;
                }
                finally
                {
                    telemetryClients.TrackEvent(telemetryEventDetails);
                }
            }
        }

        private void LogErrorTelemetryToClient(string errorCode, MsalTelemetryEventDetails telemetryEventDetails, ITelemetryClient[] telemetryClients)
        {
            if (telemetryClients.HasEnabledClients(TelemetryConstants.AcquireTokenEventName))
            {
                telemetryEventDetails.SetProperty(TelemetryConstants.Succeeded, false);
                telemetryEventDetails.SetProperty(TelemetryConstants.ErrorCode, errorCode);
            }
        }

        private void LogSuccessfulTelemetryToClient(AuthenticationResult authenticationResult, MsalTelemetryEventDetails telemetryEventDetails, ITelemetryClient[] telemetryClients)
        {
            if (telemetryClients.HasEnabledClients(TelemetryConstants.AcquireTokenEventName))
            {
                telemetryEventDetails.SetProperty(TelemetryConstants.CacheInfoTelemetry, Convert.ToInt64(authenticationResult.AuthenticationResultMetadata.CacheRefreshReason));
                telemetryEventDetails.SetProperty(TelemetryConstants.TokenSource, Convert.ToInt64(authenticationResult.AuthenticationResultMetadata.TokenSource));
                telemetryEventDetails.SetProperty(TelemetryConstants.Duration, authenticationResult.AuthenticationResultMetadata.DurationTotalInMs);
                telemetryEventDetails.SetProperty(TelemetryConstants.DurationInCache, authenticationResult.AuthenticationResultMetadata.DurationInCacheInMs);
                telemetryEventDetails.SetProperty(TelemetryConstants.DurationInHttp, authenticationResult.AuthenticationResultMetadata.DurationInHttpInMs);
                telemetryEventDetails.SetProperty(TelemetryConstants.Succeeded, true);
                telemetryEventDetails.SetProperty(TelemetryConstants.PopToken, authenticationResult.TokenType.Equals(Constants.PoPTokenType));
                telemetryEventDetails.SetProperty(TelemetryConstants.RemainingLifetime, (authenticationResult.ExpiresOn - DateTime.Now).TotalMilliseconds);
                telemetryEventDetails.SetProperty(TelemetryConstants.ActivityId, authenticationResult.CorrelationId);
            }
        }

        private static void LogMetricsFromAuthResult(AuthenticationResult authenticationResult, ILoggerAdapter logger)
        {
            var sb = new StringBuilder(250);
            sb.AppendLine();
            sb.Append("[LogMetricsFromAuthResult] Cache Refresh Reason: ");
            sb.AppendLine(authenticationResult.AuthenticationResultMetadata.CacheRefreshReason.ToString());
            sb.Append("[LogMetricsFromAuthResult] DurationInCacheInMs: ");
            sb.AppendLine(authenticationResult.AuthenticationResultMetadata.DurationInCacheInMs.ToString());
            sb.Append("[LogMetricsFromAuthResult] DurationTotalInMs: ");
            sb.AppendLine(authenticationResult.AuthenticationResultMetadata.DurationTotalInMs.ToString());
            sb.Append("[LogMetricsFromAuthResult] DurationInHttpInMs: ");
            sb.AppendLine(authenticationResult.AuthenticationResultMetadata.DurationInHttpInMs.ToString());
            logger.Always(sb.ToString());
            logger.AlwaysPii($"[LogMetricsFromAuthResult] TokenEndpoint: {authenticationResult.AuthenticationResultMetadata.TokenEndpoint ?? ""}",
                                "TokenEndpoint: ****");
        }

        private static void UpdateTelemetry(Stopwatch sw, ApiEvent apiEvent, AuthenticationResult authenticationResult)
        {
            authenticationResult.AuthenticationResultMetadata.DurationTotalInMs = sw.ElapsedMilliseconds;
            authenticationResult.AuthenticationResultMetadata.DurationInHttpInMs = apiEvent.DurationInHttpInMs;
            authenticationResult.AuthenticationResultMetadata.DurationInCacheInMs = apiEvent.DurationInCacheInMs;
            authenticationResult.AuthenticationResultMetadata.TokenEndpoint = apiEvent.TokenEndpoint;
            authenticationResult.AuthenticationResultMetadata.CacheRefreshReason = apiEvent.CacheInfo;
            authenticationResult.AuthenticationResultMetadata.RegionDetails = CreateRegionDetails(apiEvent);

            Metrics.IncrementTotalDurationInMs(authenticationResult.AuthenticationResultMetadata.DurationTotalInMs);
        }

        protected virtual void EnrichTelemetryApiEvent(ApiEvent apiEvent)
        {
            // In base classes have them override this to add their properties/fields to the event.
        }

        private ApiEvent InitializeApiEvent(string accountId)
        {
            ApiEvent apiEvent = new ApiEvent(AuthenticationRequestParameters.RequestContext.CorrelationId)
            {
                ApiId = AuthenticationRequestParameters.ApiId,
            };

            apiEvent.IsTokenCacheSerialized = AuthenticationRequestParameters.CacheSessionManager.TokenCacheInternal.IsExternalSerializationConfiguredByUser();
            apiEvent.IsLegacyCacheEnabled = AuthenticationRequestParameters.RequestContext.ServiceBundle.Config.LegacyCacheCompatibilityEnabled;
            apiEvent.CacheInfo = CacheRefreshReason.NotApplicable;
            apiEvent.TokenType = AuthenticationRequestParameters.AuthenticationScheme.TelemetryTokenType;

            // Give derived classes the ability to add or modify fields in the telemetry as needed.
            EnrichTelemetryApiEvent(apiEvent);

            return apiEvent;
        }

        protected async Task<AuthenticationResult> CacheTokenResponseAndCreateAuthenticationResultAsync(MsalTokenResponse msalTokenResponse)
        {
            // developer passed in user object.
            AuthenticationRequestParameters.RequestContext.Logger.Info("Checking client info returned from the server..");

            ClientInfo fromServer = null;

            if (!AuthenticationRequestParameters.IsClientCredentialRequest &&
                AuthenticationRequestParameters.ApiId != ApiEvent.ApiIds.AcquireTokenByRefreshToken &&
                AuthenticationRequestParameters.AuthorityInfo.AuthorityType != AuthorityType.Adfs &&
                !(msalTokenResponse.ClientInfo is null))
            {
                //client_info is not returned from client credential flows because there is no user present.
                fromServer = ClientInfo.CreateFromJson(msalTokenResponse.ClientInfo);
            }

            ValidateAccountIdentifiers(fromServer);

            AuthenticationRequestParameters.RequestContext.Logger.Info("Saving token response to cache..");

            var tuple = await CacheManager.SaveTokenResponseAsync(msalTokenResponse).ConfigureAwait(false);
            var atItem = tuple.Item1;
            var idtItem = tuple.Item2;
            Account account = tuple.Item3;

            return new AuthenticationResult(
                atItem,
                idtItem,
                AuthenticationRequestParameters.AuthenticationScheme,
                AuthenticationRequestParameters.RequestContext.CorrelationId,
                msalTokenResponse.TokenSource,
                AuthenticationRequestParameters.RequestContext.ApiEvent,
                account,
                msalTokenResponse.SpaAuthCode);
        }

        private void ValidateAccountIdentifiers(ClientInfo fromServer)
        {
            if (fromServer == null ||
                AuthenticationRequestParameters?.Account?.HomeAccountId == null ||
                PublicClientApplication.IsOperatingSystemAccount(AuthenticationRequestParameters?.Account))
            {
                return;
            }

            if (AuthenticationRequestParameters.AuthorityInfo.AuthorityType == AuthorityType.B2C &&
                fromServer.UniqueTenantIdentifier.Equals(AuthenticationRequestParameters.Account.HomeAccountId.TenantId,
                    StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (fromServer.UniqueObjectIdentifier.Equals(AuthenticationRequestParameters.Account.HomeAccountId.ObjectId,
                    StringComparison.OrdinalIgnoreCase) &&
                fromServer.UniqueTenantIdentifier.Equals(AuthenticationRequestParameters.Account.HomeAccountId.TenantId,
                    StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            AuthenticationRequestParameters.RequestContext.Logger.Error("Returned user identifiers do not match the sent user identifier");

            AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Returned user identifiers (uid:{0} utid:{1}) does not match the sent user identifier (uid:{2} utid:{3})",
                    fromServer.UniqueObjectIdentifier,
                    fromServer.UniqueTenantIdentifier,
                    AuthenticationRequestParameters.Account.HomeAccountId.ObjectId,
                    AuthenticationRequestParameters.Account.HomeAccountId.TenantId),
                string.Empty);

            throw new MsalClientException(MsalError.UserMismatch, MsalErrorMessage.UserMismatchSaveToken);
        }

        protected Task ResolveAuthorityAsync()
        {
            return AuthenticationRequestParameters.AuthorityManager.RunInstanceDiscoveryAndValidationAsync();
        }

        internal Task<MsalTokenResponse> SendTokenRequestAsync(
            IDictionary<string, string> additionalBodyParameters,
            CancellationToken cancellationToken)
        {
            var tokenResponse = SendTokenRequestAsync(
                AuthenticationRequestParameters.Authority.GetTokenEndpoint(),
                additionalBodyParameters,
                cancellationToken);
            Metrics.IncrementTotalAccessTokensFromIdP();
            return tokenResponse;
        }

        protected Task<MsalTokenResponse> SendTokenRequestAsync(
            string tokenEndpoint,
            IDictionary<string, string> additionalBodyParameters,
            CancellationToken cancellationToken)
        {
            string scopes = GetOverriddenScopes(AuthenticationRequestParameters.Scope).AsSingleString();
            var tokenClient = new TokenClient(AuthenticationRequestParameters);

            var CcsHeader = GetCcsHeader(additionalBodyParameters);
            if (CcsHeader != null && !string.IsNullOrEmpty(CcsHeader.Value.Key))
            {
                tokenClient.AddHeaderToClient(CcsHeader.Value.Key, CcsHeader.Value.Value);
            }

            return tokenClient.SendTokenRequestAsync(
                additionalBodyParameters,
                scopes,
                tokenEndpoint,
                cancellationToken);
        }

        //The AAD backup authentication system header is used by the AAD backup authentication system service
        //to help route requests to resources in Azure during requests to speed up authentication.
        //It consists of either the ObjectId.TenantId or the upn of the account signing in.
        //See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2525
        protected virtual KeyValuePair<string, string>? GetCcsHeader(IDictionary<string, string> additionalBodyParameters)
        {
            if (AuthenticationRequestParameters?.Account?.HomeAccountId != null)
            {
                if (!String.IsNullOrEmpty(AuthenticationRequestParameters.Account.HomeAccountId.Identifier))
                {
                    var userObjectId = AuthenticationRequestParameters.Account.HomeAccountId.ObjectId;
                    var userTenantID = AuthenticationRequestParameters.Account.HomeAccountId.TenantId;
                    string OidCcsHeader = CoreHelpers.GetCcsClientInfoHint(userObjectId, userTenantID);

                    return new KeyValuePair<string, string>(Constants.CcsRoutingHintHeader, OidCcsHeader);
                }

                if (!String.IsNullOrEmpty(AuthenticationRequestParameters.Account.Username))
                {
                    return GetCcsUpnHeader(AuthenticationRequestParameters.Account.Username);
                }
            }

            if (additionalBodyParameters.ContainsKey(OAuth2Parameter.Username))
            {
                return GetCcsUpnHeader(additionalBodyParameters[OAuth2Parameter.Username]);
            }

            if (!String.IsNullOrEmpty(AuthenticationRequestParameters.LoginHint))
            {
                return GetCcsUpnHeader(AuthenticationRequestParameters.LoginHint);
            }

            return null;
        }

        protected KeyValuePair<string, string>? GetCcsUpnHeader(string upnHeader)
        {
            if (AuthenticationRequestParameters.Authority.AuthorityInfo.AuthorityType == AuthorityType.B2C)
            {
                return null;
            }

            string OidCcsHeader = CoreHelpers.GetCcsUpnHint(upnHeader);

            return new KeyValuePair<string, string>(Constants.CcsRoutingHintHeader, OidCcsHeader) as KeyValuePair<string, string>?;
        }

        private void LogRequestStarted(AuthenticationRequestParameters authenticationRequestParameters)
        {
            if (authenticationRequestParameters.RequestContext.Logger.IsLoggingEnabled(LogLevel.Info))
            {
                string logFormat = "=== Token Acquisition ({3}) started:\n\tAuthority: {0}\n\tScope: {1}\n\tClientId: {2}\n\t";
                string scopes = authenticationRequestParameters.Scope.AsSingleString();
                string messageWithPii = string.Format(
                    CultureInfo.InvariantCulture,
                    logFormat,
                    authenticationRequestParameters.AuthorityInfo?.CanonicalAuthority,
                    scopes,
                    authenticationRequestParameters.AppConfig.ClientId,
                    GetType().Name);

                string messageWithoutPii = string.Format(
                    CultureInfo.InvariantCulture,
                    "=== Token Acquisition ({0}) started:\n\t Scopes: {1}",
                    GetType().Name,
                    scopes);

                if (authenticationRequestParameters.AuthorityInfo != null &&
                    KnownMetadataProvider.IsKnownEnvironment(authenticationRequestParameters.AuthorityInfo?.Host))
                {
                    messageWithoutPii += string.Format(
                        CultureInfo.CurrentCulture,
                        "\n\tAuthority Host: {0}",
                        authenticationRequestParameters.AuthorityInfo?.Host);
                }

                authenticationRequestParameters.RequestContext.Logger.InfoPii(messageWithPii, messageWithoutPii);
            }

            if (authenticationRequestParameters.AppConfig.IsConfidentialClient &&
                !authenticationRequestParameters.IsClientCredentialRequest &&
                !CacheManager.TokenCacheInternal.IsAppSubscribedToSerializationEvents())
            {
                authenticationRequestParameters.RequestContext.Logger.Warning(
                    "Only in-memory caching is used. The cache is not persisted and will be lost if the machine is restarted. It also does not scale for a web app or web API, where the number of users can grow large. In production, web apps and web APIs should use distributed caching like Redis. See https://aka.ms/msal-net-cca-token-cache-serialization");
            }
        }

        private void LogReturnedToken(AuthenticationResult result)
        {
            if (result.AccessToken != null &&
                AuthenticationRequestParameters.RequestContext.Logger.IsLoggingEnabled(LogLevel.Info))
            {
                string scopes = string.Join(" ", result.Scopes);

                AuthenticationRequestParameters.RequestContext.Logger.Info("\n\t=== Token Acquisition finished successfully:");
                AuthenticationRequestParameters.RequestContext.Logger.InfoPii(
                        $" AT expiration time: {result.ExpiresOn}, scopes: {scopes}. " +
                            $"source: {result.AuthenticationResultMetadata.TokenSource}",
                        $" AT expiration time: {result.ExpiresOn}, scopes: {scopes}. " +
                            $"source: {result.AuthenticationResultMetadata.TokenSource}");

                if (result.AuthenticationResultMetadata.TokenSource != TokenSource.Cache)
                {
                    Uri canonicalAuthority = AuthenticationRequestParameters.AuthorityInfo.CanonicalAuthority;

                    AuthenticationRequestParameters.RequestContext.Logger.InfoPii(
                        $"Fetched access token from host {canonicalAuthority.Host}. Endpoint: {canonicalAuthority}. ",
                        $"Fetched access token from host {canonicalAuthority.Host}. ");
                }
            }
        }

        internal async Task<AuthenticationResult> HandleTokenRefreshErrorAsync(MsalServiceException e, MsalAccessTokenCacheItem cachedAccessTokenItem)
        {
            var logger = AuthenticationRequestParameters.RequestContext.Logger;

            logger.Warning($"Fetching a new AT failed. Is exception retry-able? {e.IsRetryable}. Is there an AT in the cache that is usable? {cachedAccessTokenItem != null}");

            if (cachedAccessTokenItem != null && e.IsRetryable)
            {
                logger.Info("Returning existing access token. It is not expired, but should be refreshed. ");

                var idToken = await CacheManager.GetIdTokenCacheItemAsync(cachedAccessTokenItem).ConfigureAwait(false);
                var account = await CacheManager.GetAccountAssociatedWithAccessTokenAsync(cachedAccessTokenItem).ConfigureAwait(false);

                return new AuthenticationResult(
                    cachedAccessTokenItem,
                    idToken,
                    AuthenticationRequestParameters.AuthenticationScheme,
                    AuthenticationRequestParameters.RequestContext.CorrelationId,
                    TokenSource.Cache,
                    AuthenticationRequestParameters.RequestContext.ApiEvent,
                    account);
            }

            logger.Warning("Either the exception does not indicate a problem with AAD or the token cache does not have an AT that is usable. ");
            throw e;
        }

        /// <summary>
        /// Creates the region Details
        /// </summary>
        /// <param name="apiEvent"></param>
        /// <returns></returns>
        private static RegionDetails CreateRegionDetails(ApiEvent apiEvent)
        {
            return new RegionDetails(
                apiEvent.RegionOutcome,
                apiEvent.RegionUsed,
                apiEvent.RegionDiscoveryFailureReason);
        }
    }
}


text:
@class KMWordPressPost;
@class KMWordPressPostComment;

@interface KMCommentListViewController : KMViewController <UITableViewDelegate, SSPullToRefreshViewDelegate>
- (id)initWithPost:(KMWordPressPost *)post withFullScreen:(BOOL)fullscreen;
- (void)replyToComment:(KMWordPressPostComment *)comment;
- (void)showWebPage:(NSURL *)URL;
@end

redpajama_set_name: RedPajamaGithub


text:
<?php if(!defined('access') or !access) die('This file cannot be directly accessed.'); ?>
<?php include_theme_header(); ?>

Terms of service

This is an example page for your chevereto site. You can edit this file located in /content/themes/Peafowl/pages/tos.php

How to setup/delete more pages?

Edit the pages_config.php file located on the same directory mentioned above. This file is the one that setups the pages, just read the notes and follow the comments on it.

How to change the visual style?

Just edit/add your CSS rules on style.css and write the HTML on each page.

What about JavaScript?

Easy as you may guess... Just open header.php and paste your scripts beetwen the <head> and </head> tag. Some scripts need to be in the <body> tag, just use whatever fits your needs. By the way, you don't need to include jQuery because it loads by default on Chevereto.

More help

If you need more help we suggest you to try this alternatives:

Read the Chevereto documentation.

Go to the community for opened topics or post a new issue.

<?php include_theme_footer(); ?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>KnowledgePathBuilder</title>
<meta name="date" content="2012-05-11">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cz.cuni.mff.d3s.deeco.knowledge

Class KnowledgePathBuilder

java.lang.Object

cz.cuni.mff.d3s.deeco.knowledge.KnowledgePathBuilder

public class KnowledgePathBuilder
extends java.lang.Object

Class providing utility functions for dealing with knowledge paths.

Author:

Michal Kit

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
PATH_DELIMITER

Constructor Summary

Constructors

Constructor and Description

KnowledgePathBuilder()

Method Summary

Methods

Modifier and Type
Method and Description

static java.lang.String
appendToRoot(java.lang.String root,
            java.lang.String tail)

Static function appending a new part (tail) to the existing one (root).

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

PATH_DELIMITER

public static final java.lang.String PATH_DELIMITER

See Also:

Constant Field Values

Constructor Detail

KnowledgePathBuilder

public KnowledgePathBuilder()

Method Detail

appendToRoot

public static java.lang.String appendToRoot(java.lang.String root,
                            java.lang.String tail)

Static function appending a new part (tail) to the existing one (root).
 New instance of String object is returned.

Parameters:

root - head part of the path

tail - tail path of the path

Returns:

full path

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
(function($) {

  $(function() {

    addEventOnRequestBlock();

    var donateBtn = document.getElementsByClassName('donation-btn');

    if(donateBtn) {

      for(var i=0; i<donateBtn.length; i++) {

        donateBtn[i].addEventListener('popupLoad', function() {
          addEventOnRequestBlock();
        });

      }

    }

    function addEventOnRequestBlock(){

      var donateForm = $('.donate-form');

      $('.donate-form__price-btn', donateForm).on('click', function() {
        var $this = $(this);
        $('.donate-form__price-btn', donateForm).removeClass('active');
        $this.addClass('active');
        $('.donate-form__input', donateForm).val($this.data('price'));
      });

    }

  });

})(jQuery);


text:
using System;
using bv.common.Core;

namespace eidss.model.Schema
{
    public partial class ActivityParameter
    {
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return varValue != null ? varValue.ToString() : String.Empty;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static string ToString(ActivityParameter activityParameter)
        {
            return
                activityParameter != null
                    ? activityParameter.varValue != null ? activityParameter.varValue.ToString() : String.Empty
                    : String.Empty;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetUserValue()
        {
            return Utils.IsEmpty(strNameValue) ? ToString() : strNameValue;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public int ToInt()
        {
            return varValue != null ? Convert.ToInt32(varValue) : 0;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static int ToInt(ActivityParameter activityParameter)
        {
            return
                activityParameter != null
                    ? activityParameter.varValue != null ? Convert.ToInt32(activityParameter.varValue) : 0
                    : 0;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public DateTime ToDateTime()
        {
            return varValue != null ? Convert.ToDateTime(varValue) : DateTime.Now;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static DateTime ToDateTime(ActivityParameter activityParameter)
        {
            return
                activityParameter != null
                    ? activityParameter.varValue != null ? Convert.ToDateTime(activityParameter.varValue) : DateTime.Now
                    : DateTime.Now;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public long ToLong()
        {
            return varValue != null ? Convert.ToInt64(varValue) : 0;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static long ToLong(ActivityParameter activityParameter)
        {
            long result = 0;
            if ((activityParameter != null) && (activityParameter.varValue != null))
            {
                result = activityParameter.varValue.ToString().Length > 0
                             ? Convert.ToInt64(activityParameter.varValue)
                             : 0;
            }

            return result;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public DateTime ToDate()
        {
            return varValue != null ? Convert.ToDateTime(varValue).Date : DateTime.Now.Date;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static DateTime ToDate(ActivityParameter activityParameter)
        {
            return
                activityParameter != null
                    ? activityParameter.varValue != null
                          ? Convert.ToDateTime(activityParameter.varValue).Date
                          : DateTime.Now.Date
                    : DateTime.Now.Date;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool ToBool()
        {
            return varValue != null && Convert.ToBoolean(varValue);
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static bool ToBool(ActivityParameter activityParameter)
        {
            return
                activityParameter != null && (activityParameter.varValue != null && Convert.ToBoolean(activityParameter.varValue));
        }

        /// <summary>
        /// Увеличивает значение поля, чтобы указать движку, что объект поменялся (это костыль, пока не работает правильно движок)
        /// </summary>
        public void IncreaseFakeField()
        {
            if (Utils.IsEmpty(FakeField))
                FakeField = 1;
            else
                FakeField++;
        }

        /// <summary>
        /// Выставляется в true, если этому параметру присваивались какие-то реальные значения
        /// </summary>
        public bool HasRealChanges { get; set; }
    }
}


text:
<?php

namespace Bolt\Events;

final class ControllerEvents
{
    const MOUNT = 'controller.mount';

    private function __construct()
    {
    }
}


text:
require 'test_helper'

describe Hbc::DSL do
  it "lets you set url, homepage, and version" do
    test_cask = Hbc.load('basic-cask')
    test_cask.url.to_s.must_equal 'http://example.com/TestCask.dmg'
    test_cask.homepage.must_equal 'http://example.com/'
    test_cask.version.to_s.must_equal '1.2.3'
  end

  describe "when a Cask includes an unknown method" do
    UnexpectedMethodCask = Class.new(Hbc::Cask)
    attempt_unknown_method = nil

    before do
      attempt_unknown_method = lambda {
        UnexpectedMethodCask.class_eval do
          future_feature :not_yet_on_your_machine
        end
      }
    end

    it "prints a warning that it has encountered an unexpected method" do
      expected = r = Regexp.compile(<<-EOREGEX.undent.lines.map(&:chomp).join(''))
        (?m)
        Warning:
        .*
        Unexpected method 'future_feature' called on Cask unexpected-method-cask\\.
        .*
        brew update; brew cleanup; brew cask cleanup
        .*
        https://github.com/caskroom/homebrew-cask#reporting-bugs
      EOREGEX

      TestHelper.must_output(self, attempt_unknown_method, expected)
    end

    it "will simply warn, not throw an exception" do
      begin
        capture_subprocess_io { attempt_unknown_method.call }
      rescue Exception => e
        flunk("Wanted unexpected method to simply warn, but got exception #{e}")
      end
    end
  end

  describe "header line" do
    it "requires a valid header format" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-header-format')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include 'Bad header line: parse failed'
    end

    it "requires the header token to match the file name" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-header-token-mismatch')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include 'Bad header line:'
      err.message.must_include 'does not match file name'
    end

    it "does not require a DSL version in the header" do
      test_cask = Hbc.load('no-dsl-version')
      test_cask.url.to_s.must_equal 'http://example.com/TestCask.dmg'
      test_cask.homepage.must_equal 'http://example.com/'
      test_cask.version.to_s.must_equal '1.2.3'
    end
  end

  describe "name stanza" do
    it "lets you set the full name via a name stanza" do
      NameCask = Class.new(Hbc::Cask)
      NameCask.class_eval do
        name 'Proper Name'
      end
      instance = NameCask.new
      instance.full_name.must_equal [
                                     'Proper Name',
                                    ]
    end

    it "Accepts an array value to the name stanza" do
      ArrayNameCask = Class.new(Hbc::Cask)
      ArrayNameCask.class_eval do
        name ['Proper Name', 'Alternate Name']
      end
      instance = ArrayNameCask.new
      instance.full_name.must_equal [
                                     'Proper Name',
                                     'Alternate Name',
                                    ]
    end

    it "Accepts multiple name stanzas" do
      MultiNameCask = Class.new(Hbc::Cask)
      MultiNameCask.class_eval do
        name 'Proper Name'
        name 'Alternate Name'
      end
      instance = MultiNameCask.new
      instance.full_name.must_equal [
                                     'Proper Name',
                                     'Alternate Name',
                                    ]
    end
  end

  describe "sha256 stanza" do
    it "lets you set checksum via sha256" do
      ChecksumCask = Class.new(Hbc::Cask)
      ChecksumCask.class_eval do
        sha256 'imasha2'
      end
      instance = ChecksumCask.new
      instance.sha256.must_equal 'imasha2'
    end
  end

  describe "app stanza" do
    it "allows you to specify app stanzas" do
      CaskWithApps = Class.new(Hbc::Cask)
      CaskWithApps.class_eval do
        app 'Foo.app'
        app 'Bar.app'
      end

      instance = CaskWithApps.new
      Array(instance.artifacts[:app]).must_equal [['Foo.app'], ['Bar.app']]
    end

    it "allow app stanzas to be empty" do
      CaskWithNoApps = Class.new(Hbc::Cask)

      instance = CaskWithNoApps.new
      Array(instance.artifacts[:app]).must_equal %w[]
    end
  end

  describe "caveats stanza" do
    it "allows caveats to be specified via a method define" do
      PlainCask = Class.new(Hbc::Cask)

      instance = PlainCask.new

      instance.caveats.must_be :empty?

      CaskWithCaveats = Class.new(Hbc::Cask)
      CaskWithCaveats.class_eval do
        def caveats; <<-EOS.undent
          When you install this Cask, you probably want to know this.
          EOS
        end
      end

      instance = CaskWithCaveats.new

      instance.caveats.must_equal "When you install this Cask, you probably want to know this.\n"
    end
  end

  describe "pkg stanza" do
    it "allows installable pkgs to be specified" do
      CaskWithPkgs = Class.new(Hbc::Cask)
      CaskWithPkgs.class_eval do
        pkg 'Foo.pkg'
        pkg 'Bar.pkg'
      end

      instance = CaskWithPkgs.new
      Array(instance.artifacts[:pkg]).must_equal [['Foo.pkg'], ['Bar.pkg']]
    end
  end

  describe "url stanza" do
    it "prevents defining multiple urls" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-two-url')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'url' stanza may only appear once"
    end
  end

  describe "homepage stanza" do
    it "prevents defining multiple homepages" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-two-homepage')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'homepage' stanza may only appear once"
    end
  end

  describe "version stanza" do
    it "prevents defining multiple versions" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-two-version')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'version' stanza may only appear once"
    end
  end

  describe "appcast stanza" do
    it "allows appcasts to be specified" do
      cask = Hbc.load('with-appcast')
      cask.appcast.to_s.must_match %r{^http}
    end

    it "prevents defining multiple appcasts" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-appcast-multiple')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'appcast' stanza may only appear once"
    end

    it "refuses to load invalid appcast URLs" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-appcast-url')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "gpg stanza" do
    it "allows gpg stanza to be specified" do
      cask = Hbc.load('with-gpg')
      cask.gpg.to_s.must_match %r{\S}
    end

    it "allows gpg stanza to be specified with :key_url" do
      cask = Hbc.load('with-gpg-key-url')
      cask.gpg.to_s.must_match %r{\S}
    end

    it "prevents specifying gpg stanza multiple times" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-multiple-stanzas')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'gpg' stanza may only appear once"
    end

    it "prevents missing gpg key parameters" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-missing-key')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'gpg' stanza must include exactly one"
    end

    it "prevents conflicting gpg key parameters" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-conflicting-keys')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'gpg' stanza must include exactly one"
    end

    it "refuses to load invalid gpg signature URLs" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-signature-url')
      }.must_raise(Hbc::CaskInvalidError)
    end

    it "refuses to load invalid gpg key URLs" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-key-url')
      }.must_raise(Hbc::CaskInvalidError)
    end

    it "refuses to load invalid gpg key IDs" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-key-id')
      }.must_raise(Hbc::CaskInvalidError)
    end

    it "refuses to load if gpg parameter is unknown" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-gpg-parameter')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "depends_on stanza" do
    it "refuses to load with an invalid depends_on key" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-depends-on-key')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "depends_on :formula" do
    it "allows depends_on :formula to be specified" do
      cask = Hbc.load('with-depends-on-formula')
      cask.depends_on.formula.wont_be_nil
    end

    it "allows multiple depends_on :formula to be specified" do
      cask = Hbc.load('with-depends-on-formula-multiple')
      cask.depends_on.formula.wont_be_nil
    end
  end

  describe "depends_on :cask" do
    it "allows depends_on :cask to be specified" do
      cask = Hbc.load('with-depends-on-cask')
      cask.depends_on.cask.wont_be_nil
    end

    it "allows multiple depends_on :cask to be specified" do
      cask = Hbc.load('with-depends-on-cask-multiple')
      cask.depends_on.cask.wont_be_nil
    end
  end

  describe "depends_on :macos" do
    it "allows depends_on :macos to be specified" do
      cask = Hbc.load('with-depends-on-macos-string')
      cask.depends_on.macos.wont_be_nil
    end
    it "refuses to load with an invalid depends_on :macos value" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-depends-on-macos-bad-release')
      }.must_raise(Hbc::CaskInvalidError)
    end
    it "refuses to load with conflicting depends_on :macos forms" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-depends-on-macos-conflicting-forms')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "depends_on :arch" do
    it "allows depends_on :arch to be specified" do
      cask = Hbc.load('with-depends-on-arch')
      cask.depends_on.arch.wont_be_nil
    end
    it "refuses to load with an invalid depends_on :arch value" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-depends-on-arch-value')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "depends_on :x11" do
    it "allows depends_on :x11 to be specified" do
      cask = Hbc.load('with-depends-on-x11')
      cask.depends_on.x11.wont_be_nil
    end
    it "refuses to load with an invalid depends_on :x11 value" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-depends-on-x11-value')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "conflicts_with stanza" do
    it "allows conflicts_with stanza to be specified" do
      cask = Hbc.load('with-conflicts-with')
      cask.conflicts_with.formula.wont_be_nil
    end

    it "refuses to load invalid conflicts_with key" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-conflicts-with-key')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "license stanza" do
    it "allows the license to be specified" do
      cask = Hbc.load('with-license')
      cask.license.value.must_equal :gpl
    end

    it "the license has a category" do
      cask = Hbc.load('with-license')
      cask.license.category.must_equal :oss
    end

    it "prevents defining multiple license stanzas" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-license-multiple')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'license' stanza may only appear once"
    end

    it "refuses to load on invalid license value" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-license-value')
      }.must_raise(Hbc::CaskInvalidError)
    end
  end

  describe "installer stanza" do
    it "allows installer :script to be specified" do
      cask = Hbc.load('with-installer-script')
      cask.artifacts[:installer].first.script[:executable].must_equal '/usr/bin/true'
      cask.artifacts[:installer].first.script[:args].must_equal ['--flag']
      cask.artifacts[:installer].to_a[1].script[:executable].must_equal '/usr/bin/false'
      cask.artifacts[:installer].to_a[1].script[:args].must_equal ['--flag']
    end
    it "allows installer :manual to be specified" do
      cask = Hbc.load('with-installer-manual')
      cask.artifacts[:installer].first.manual.must_equal 'Caffeine.app'
    end
  end

  describe "stage_only stanza" do
    it "allows stage_only stanza to be specified" do
      cask = Hbc.load('stage-only')
      cask.artifacts[:stage_only].first.must_equal [true]
    end

    it "prevents specifying stage_only with other activatables" do
      err = lambda {
        invalid_cask = Hbc.load('invalid/invalid-stage-only-conflict')
      }.must_raise(Hbc::CaskInvalidError)
      err.message.must_include "'stage_only' must be the only activatable artifact"
    end
  end

  describe "auto_updates stanza" do
    it "allows auto_updates stanza to be specified" do
      cask = Hbc.load('auto-updates')
      cask.auto_updates.must_equal true
    end
  end
end


text:
<?php

namespace Zephir\Stubs;

use Zephir\ClassMethod;

/**
 * Stubs Generator
 */
class MethodDocBlock extends DocBlock
{
    private $parameters = array();

    private $return;

    private $shortcutName = '';

    public function __construct(ClassMethod $method, $indent = 4)
    {
        parent::__construct($method->getDocBlock(), $indent);
        $this->shortcutName = $method->isShortcut() ? $method->getShortcutName() : '';
        $this->parseMethodParameters($method);
        $this->parseLines();
        if (!$this->return) {
            $this->parseMethodReturnType($method);
        }
        if ($this->parameters) {
            $this->appendParametersLines();
        }
        if ($this->return) {
            $this->appendReturnLine();
        }
    }

    protected function parseMethodReturnType(ClassMethod $method)
    {
        $return = array();
        $returnTypes = $method->getReturnTypes();
        if ($returnTypes) {
            foreach ($returnTypes as $type) {
                if (isset($type['data-type'])) {
                    $return[] = $type['data-type'];
                }
            }
        }
        $returnClassTypes = $method->getReturnClassTypes();
        if ($returnClassTypes) {
            $return = array_merge($return, $returnClassTypes);
        }
        if ($return) {
            $this->return = array(join('|', $return), '');
        }
    }

    protected function parseLines()
    {
        $lines = array();

        foreach ($this->lines as $line) {
            if (preg_match('#^@(param|return|var) +(.*)$#', $line, $matches) === 0) {
                $lines[] = $line;
            } else {
                list(, $docType, $tokens) = $matches;

                $tokens = preg_split('/\s+/', $tokens, 3);
                $type = $tokens[0];

                if ($docType == 'var' && $this->shortcutName == 'set') {
                    $docType = 'param';
                    $name = array_keys($this->parameters);
                    $name = $name[0];
                } elseif ($docType == 'var' && $this->shortcutName == 'get') {
                    $docType = 'return';
                } else {
                    $name = isset($tokens[1]) ? '$' . $tokens[1] : '';
                }

                // TODO: there must be a better way
                if (strpos($type, 'Phalcon\\') === 0) {
                    $type = str_replace('Phalcon\\', '\Phalcon\\', $type);
                }

                $description = isset($tokens[2]) ? $tokens[2] : '';

                switch ($docType) {
                    case 'param':
                        $this->parameters[$name] = array($type, $description);
                        break;
                    case 'return':
                        $this->return = array($type, $description);
                        break;
                }
            }
        }

        $this->lines = $lines;
    }

    private function appendReturnLine()
    {
        list($type, $description) = $this->return;
        $this->lines[] = '@return ' . $type . ' ' . $description;
    }

    private function parseMethodParameters(ClassMethod $method)
    {
        $parameters = $method->getParameters();
        if (!$parameters) {
            return;
        }
        foreach ($method->getParameters() as $parameter) {
            if (isset($parameter['data-type'])) {
                if ($parameter['data-type'] == 'variable') {
                    $type = 'mixed';
                } else {
                    $type = $parameter['data-type'];
                }
            } elseif (isset($parameter['cast'])) {
                $type = $parameter['cast']['value'];
            } else {
                $type = 'mixed';
            }
            $this->parameters['$' . $parameter['name']] = array($type, '');
        }
    }

    private function appendParametersLines()
    {
        foreach ($this->parameters as $name => $parameter) {
            list($type, $description) = $parameter;
            $this->lines[] = '@param ' . $type . ' ' . $name . ' ' . $description;
        }
    }
}


text:
/* Evanelos Georganas, Alexander Heinecke (Intel Corp.)
******************************************************************************/

#ifndef GENERATOR_MATELTWISE_TRANSFORM_COMMON_X86_H
#define GENERATOR_MATELTWISE_TRANSFORM_COMMON_X86_H

#include "generator_common.h"

LIBXSMM_API_INTERN
void libxsmm_generator_transform_Xway_unpack_network_avx_avx512( libxsmm_generated_code* io_generated_code,
                                                                 const char              i_vector_name,
                                                                 const unsigned char*    i_in_idx,
                                                                 const unsigned int      i_vec_reg_src_start,
                                                                 const unsigned int      i_vec_reg_dst_start,
                                                                 const unsigned int      i_out_offset,
                                                                 const unsigned int      i_even_instr,
                                                                 const unsigned int      i_odd_instr,
                                                                 const unsigned int      i_ways );

LIBXSMM_API_INTERN
void libxsmm_generator_transform_Xway_full_load_avx_avx512( libxsmm_generated_code* io_generated_code,
                                                            const char              i_vector_name,
                                                            const unsigned int      i_gp_reg_in,
                                                            const unsigned int      i_vec_reg_dst_start,
                                                            const unsigned int      i_ld,
                                                            const unsigned int      i_ld_instr,
                                                            const unsigned int      i_ways,
                                                            const unsigned int      i_valid_ways,
                                                            const unsigned int      i_use_masking,
                                                            const unsigned int      i_mask_reg );

LIBXSMM_API_INTERN
void libxsmm_generator_transform_Xway_full_store_avx_avx512( libxsmm_generated_code* io_generated_code,
                                                             const char              i_vector_name,
                                                             const unsigned int      i_gp_reg_out,
                                                             const unsigned int      i_vec_reg_src_start,
                                                             const unsigned int      i_ld,
                                                             const unsigned int      i_st_instr,
                                                             const unsigned int      i_use_masking,
                                                             const unsigned int      i_mask_reg,
                                                             const unsigned int      i_ways );

#endif /* GENERATOR_MATELTWISE_TRANSFORM_COMMON_X86_H */


text:
package com.zayn.swiprefresh;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;

import com.zayn.loadingview.library.NestedLoadingLayout;
import com.zayn.loadingview.ui.LoadingSwipeListener;

public class CustomRefreshActivity extends AppCompatActivity {

    NestedLoadingLayout loadingLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customed_refresh);
        loadingLayout = (NestedLoadingLayout) findViewById(R.id.loadLayout);
//        loadingLayout.setContentScrollEnable(false);
        LoadingSwipeListener loadingSwipeListener = new LoadingSwipeListener();
        loadingSwipeListener.bindPullLoadView(loadingLayout, Gravity.START);

    }

}


text:
package org.cloudfoundry.operations.services;

import org.immutables.value.Value;

/**
 * A Cloud Foundry Service Plan
 */
@Value.Immutable
abstract class _ServicePlan {

    /**
     * The description
     */
    abstract String getDescription();

    /**
     * Whether the plan is free
     */
    abstract Boolean getFree();

    /**
     * The id
     */
    abstract String getId();

    /**
     * The name
     */
    abstract String getName();

}


text:
/*---------------------------------------------------------------------------*\

  FILE........: postfilter.c
  AUTHOR......: David Rowe
  DATE CREATED: 13/09/09

  Postfilter to improve sound quality for speech with high levels of
  background noise.  Unlike mixed-excitation models requires no bits
  to be transmitted to handle background noise.

\*---------------------------------------------------------------------------*/

/*
  Copyright (C) 2009 David Rowe

  All rights reserved.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License version 2.1, as
  published by the Free Software Foundation.  This program is
  distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with this program; if not, see <http://www.gnu.org/licenses/>.
*/

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "defines.h"
#include "comp.h"
#include "dump.h"
#include "postfilter.h"

/*---------------------------------------------------------------------------*\

                                DEFINES

\*---------------------------------------------------------------------------*/

#define BG_THRESH 40.0     /* only consider low levels signals for bg_est */
#define BG_BETA    0.1     /* averaging filter constant                   */
#define BG_MARGIN  6.0     /* harmonics this far above BG noise are
			      randomised.  Helped make bg noise less
			      spikey (impulsive) for mmt1, but speech was
                              perhaps a little rougher.
			   */

/*---------------------------------------------------------------------------*\

  postfilter()

  The post filter is designed to help with speech corrupted by
  background noise.  The zero phase model tends to make speech with
  background noise sound "clicky".  With high levels of background
  noise the low level inter-formant parts of the spectrum will contain
  noise rather than speech harmonics, so modelling them as voiced
  (i.e. a continuous, non-random phase track) is inaccurate.

  Some codecs (like MBE) have a mixed voicing model that breaks the
  spectrum into voiced and unvoiced regions.  Several bits/frame
  (5-12) are required to transmit the frequency selective voicing
  information.  Mixed excitation also requires accurate voicing
  estimation (parameter estimators always break occasionally under
  exceptional conditions).

  In our case we use a post filter approach which requires no
  additional bits to be transmitted.  The decoder measures the average
  level of the background noise during unvoiced frames.  If a harmonic
  is less than this level it is made unvoiced by randomising it's
  phases.

  This idea is rather experimental.  Some potential problems that may
  happen:

  1/ If someone says "aaaaaaaahhhhhhhhh" will background estimator track
     up to speech level?  This would be a bad thing.

  2/ If background noise suddenly dissapears from the source speech does
     estimate drop quickly?  What is noise suddenly re-appears?

  3/ Background noise with a non-flat sepctrum.  Current algorithm just
     comsiders scpetrum as a whole, but this could be broken up into
     bands, each with their own estimator.

  4/ Males and females with the same level of background noise.  Check
     performance the same.  Changing Wo affects width of each band, may
     affect bg energy estimates.

  5/ Not sure what happens during long periods of voiced speech
     e.g. "sshhhhhhh"

\*---------------------------------------------------------------------------*/

void postfilter(
  MODEL *model,
  float *bg_est
)
{
  int   m, uv;
  float e;

  /* determine average energy across spectrum */

  e = 0.0;
  for(m=1; m<=model->L; m++)
      e += model->A[m]*model->A[m];

  assert(e > 0.0);
  e = 10.0*log10(e/model->L);

  /* If beneath threhold, update bg estimate.  The idea
     of the threshold is to prevent updating during high level
     speech. */

  if ((e < BG_THRESH) && !model->voiced)
      *bg_est =  *bg_est*(1.0 - BG_BETA) + e*BG_BETA;

  /* now mess with phases during voiced frames to make any harmonics
     less then our background estimate unvoiced.
  */

  uv = 0;
  if (model->voiced)
      for(m=1; m<=model->L; m++)
	  if (20.0*log10(model->A[m]) < (*bg_est + BG_MARGIN)) {
	      model->phi[m] = TWO_PI*(float)rand()/RAND_MAX;
	      uv++;
	  }

#ifdef DUMP
  dump_bg(e, *bg_est, 100.0*uv/model->L);
#endif

}


text:
package www.liujijiji.cn.netty.channelInitializer;

import com.google.protobuf.MessageLite;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;

/**
 * @author liuji
 * @date 2018 - 09 - 19 13:24
 * Protocol Buffers 序列化
 * ProtobufVarint32FrameDecoder : 分隔帧;分隔数据
 */
public class ProtoBufChannelInitializer extends ChannelInitializer<Channel> {

    private final MessageLite lite;

    public ProtoBufChannelInitializer(MessageLite lite) {
        this.lite = lite;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        channel.pipeline().addLast(
                new ProtobufVarint32FrameDecoder(),
                new ProtobufEncoder(),
                new ProtobufDecoder(lite),
                new ObjectHandler()
        );
    }

    @Sharable
    public static class ObjectHandler extends SimpleChannelInboundHandler<Object> {

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object byteBuf) throws Exception {
            System.out.println("=========ProtoBufChannelInitializer=========ObjectHandler========================");
        }
    }

}


text:
class CreateRisks < ActiveRecord::Migration
  def change
    create_table :risks do |t|
      t.integer :report_id
      t.integer :marker_id

      t.timestamps
    end
  end
end


text:
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using Thinktecture.IdentityServer.Repositories;

namespace Thinktecture.IdentityServer.Web.Controllers
{
    public class HomeController : Controller
    {
        [Import]
        public IConfigurationRepository ConfigurationRepository { get; set; }

        public HomeController()
        {
            Container.Current.SatisfyImportsOnce(this);
        }

        public HomeController(IConfigurationRepository configuration)
        {
            ConfigurationRepository = configuration;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AppIntegration()
        {
            var endpoints = Endpoints.Create(
                               HttpContext.Request.Headers["Host"],
                               HttpContext.Request.ApplicationPath,
                               ConfigurationRepository.Endpoints.HttpPort,
                               ConfigurationRepository.Endpoints.HttpsPort);

            var list = new Dictionary<string, string>
            {
                { "WS-Federation", endpoints.WSFederation.AbsoluteUri },
                { "WS-Federation metadata", endpoints.WSFederationMetadata.AbsoluteUri },

                { "WS-Trust mixed (UserName)", endpoints.WSTrustMixedUserName.AbsoluteUri },
                { "WS-Trust mixed (Certificate)", endpoints.WSTrustMixedCertificate.AbsoluteUri },
                { "WS-Trust message (UserName)", endpoints.WSTrustMessageUserName.AbsoluteUri },
                { "WS-Trust message (Certificate)", endpoints.WSTrustMessageCertificate.AbsoluteUri },
                { "WS-Trust metadata", endpoints.WSTrustMex.AbsoluteUri },

                { "WRAP", endpoints.Wrap.AbsoluteUri },
                { "OAuth2", endpoints.OAuth2.AbsoluteUri },
                { "JSNotify", endpoints.JSNotify.AbsoluteUri },
                { "Simple HTTP", endpoints.SimpleHttp.AbsoluteUri },
            };

            return View(list);
        }
    }
}


text:
package org.apache.commons.imaging;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Provides information about the compliance of a specified data
 * source (byte array, file, etc.) to an image format.
 */
public class FormatCompliance {
    private final boolean failOnError;
    private final String description;
    private final List<String> comments = new ArrayList<String>();

    public FormatCompliance(final String description) {
        this.description = description;
        failOnError = false;
    }

    public FormatCompliance(final String description, final boolean failOnError) {
        this.description = description;
        this.failOnError = failOnError;
    }

    public static FormatCompliance getDefault() {
        return new FormatCompliance("ignore", false);
    }

    public void addComment(final String comment) throws ImageReadException {
        comments.add(comment);
        if (failOnError) {
            throw new ImageReadException(comment);
        }
    }

    public void addComment(final String comment, final int value) throws ImageReadException {
        addComment(comment + ": " + getValueDescription(value));
    }

    @Override
    public String toString() {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);

        dump(pw);

        return sw.getBuffer().toString();
    }

    public void dump() {
        dump(new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())));
    }

    public void dump(final PrintWriter pw) {
        pw.println("Format Compliance: " + description);

        if (comments.isEmpty()) {
            pw.println("\t" + "No comments.");
        } else {
            for (int i = 0; i < comments.size(); i++) {
                pw.println("\t" + (i + 1) + ": " + comments.get(i));
            }
        }
        pw.println("");
        pw.flush();
    }

    private String getValueDescription(final int value) {
        return value + " (" + Integer.toHexString(value) + ")";
    }

    public boolean compareBytes(final String name, final byte[] expected, final byte[] actual)
            throws ImageReadException {
        if (expected.length != actual.length) {
            addComment(name + ": " + "Unexpected length: (expected: "
                    + expected.length + ", actual: " + actual.length + ")");
            return false;
        }
        for (int i = 0; i < expected.length; i++) {
            // System.out.println("expected: "
            // + getValueDescription(expected[i]) + ", actual: "
            // + getValueDescription(actual[i]) + ")");
            if (expected[i] != actual[i]) {
                addComment(name + ": " + "Unexpected value: (expected: "
                        + getValueDescription(expected[i]) + ", actual: "
                        + getValueDescription(actual[i]) + ")");
                return false;
            }
        }

        return true;
    }

    public boolean checkBounds(final String name, final int min, final int max, final int actual)
            throws ImageReadException {
        if ((actual < min) || (actual > max)) {
            addComment(name + ": " + "bounds check: " + min + " <= " + actual
                    + " <= " + max + ": false");
            return false;
        }

        return true;
    }

    public boolean compare(final String name, final int valid, final int actual)
            throws ImageReadException {
        return compare(name, new int[] { valid, }, actual);
    }

    public boolean compare(final String name, final int[] valid, final int actual)
            throws ImageReadException {
        for (final int element : valid) {
            if (actual == element) {
                return true;
            }
        }

        final StringBuilder result = new StringBuilder(43);
        result.append(name);
        result.append(": Unexpected value: (valid: ");
        if (valid.length > 1) {
            result.append('{');
        }
        for (int i = 0; i < valid.length; i++) {
            if (i > 0) {
                result.append(", ");
            }
            result.append(getValueDescription(valid[i]));
        }
        if (valid.length > 1) {
            result.append('}');
        }
        result.append(", actual: " + getValueDescription(actual) + ")");
        addComment(result.toString());
        return false;
    }
}


text:
- I have an easy exam today, and two upcoming phone screeners. So far, so good. It hasn't been a week yet, so pretty exciting.

## Watching a webinar on Asynchronous Exceptions in Haskell

## And some Notes from LA PureScript
- Phil's talk
- purescript incremental - avoid computing unnecessarily
- compute changes in outputs from changes in inputs
- idea from paper "A Theory of Changes for Higher Order Languages". Pdf available via arxiv [here](https://arxiv.org/pdf/1312.0658.pdf).
- change structures: monoid of changes which act on carrier types (transitively)

```
class Monoid da <= Patch a da
    | a -> da
where
    patch :: a -> da -> a
```

```
class Patch a da <= Diff a da
    | a -> da
where
    diff :: a -> a -> da
```

- purescript-incremental
  - uses higher order abstract syntax
  - inspired by automatic differentiation

```
Jet functions
a -> b -> da -> db

f :: Jet a da -> Jet b db
```

- incremental dom : not having to recreate DOM every time
- translate change DOM to DOM:
  - implemental in the database
  - incremental parsing
  - incremental canvas graphics

- libraries that correlate: ```purescript-sdom``` and ```purescript-panda```
- [sdom](https://github.com/paf31/purescript-sdom)
- [panda](https://github.com/i-am-tom/purescript-panda)

- M. Trotter (purescript-react-basic).
- Michael was visiting the office from Utah. He also runs a Haskell group. You can attend
  their Google Hangouts and learn/write some Haskell [here](https://www.meetup.com/utah-haskell/events/mkxxlpyxgbvb/).

```
component :: ReactComponent ExampleProps
component = react
{
displayName : "Counter"
, initialState : {counter...}
}

_ _ _ are three arguments that correspond to props, state, set state
```

```
component::ReactComponent{}
R.dir{children: [createElement
ToggleButton
component
{on:true}
```
- T.Honeyman
- Designing Flexible Open-Source Components in Halogen
- UI components inflexible because they handle rendering.
- their corresponding repo is purescript-halogen-select (see [here](https://github.com/citizennet/purescript-halogen-select))

```
let action = onClick $ action $ Select.Raise
true -> [action class_ "highlighted"]
false -> [action]
```
- functioning component you can add to depending on your needs
- SetProps functions are event Handlers in Halogen
- Handle output messages ```a ~> case message of```
    - Emit
    - Searched Search
    - Selected Item
- Conclusion: We should design more components without render functions
- Advantages:
    - Small, simple APIs
    - Complete Design Freedom
    - Flexible & Extensible Functionality
    - new structure can be made in parent component and passed to child
- Disadvantages:
    - the user has to write their own rendering code
    - the library must impose some structure (even if minimal) eg. ```select``` still has to have an item to be selected
    - this ability may not be good for larger amounts of complexity (outputs that return other outputs, etc)
    - the library author does not know the structure of the user's HTML
- Central idea; focus on behaviors, not renderers
- Inspiration (one of): [Downshift by Paypal](https://github.com/paypal/downshift).

- Extensible Checked Exceptions with Polymorphic Variants (Nate)
- Just a heads up, it takes me a while to process Nate's talks, so I'm just going to write my notes down for this.
- Re-read in a few years, see if it's clearer then. Guy has a *deep* knowledge of some concepts that I can't currently
  grasp

```
get
:: forall m
. MonadHTTP m
=> String
=> Except HTTPError m String
```
- string or raiseError

```
write
:: forall m
. MonadFs m
=> Path
-> String
-> ExceptT FsError m Unit
```

- extend with new functionality without breaking old code
- solution: use Polymorphic Variant
- record is a structural type
- Exceptions using variant

```
type HTTPError r=
(
type HTTPServerError :: String
| r
)
r -> fill in w/ extension of shape
```

- ```inj``` lifts/ associates value with row
- to work together, must use ```+r <- open row```

- advantage: inference
- how handle exceptions
- once row is handled, eliminate type
- how: rows of handlers to list
- Union -> LHS + RHS to infer output

```
Except V excIn m a
Except V excOut m a (infer output)
```
- Exhaustive handle
- ```r``` becomes closed row of nothing

- repo: [purescript-checked-exceptions](https://github.com/natefaubion/purescript-checked-exceptions)

## Okey doke
- I'm going to read that paper and get some clarity on Phil's idea. I'd like to understand the Tags in Nate's idea a bit more.
- Back to Haskell.

## And..that's it.


text:
<?php

class b2c_promotion_conditions_order_itemsquanityallgoods{
    public $tpl_name = "当订单商品数量满X,给予优惠";
    public $whole = true;
    public $type = 'order'; //标识显示那类优惠方案 enum('goods','order'); 为空在显示全部

    public function getConfig($aData = array()) {
        $___b2ca=app::get('b2c')->_('当订单商品数量满');
        $___b2cb=app::get('b2c')->_('给予优惠');
        return <<<EOF
        $___b2ca
    <input type="hidden" name="conditions[type]" value="b2c_sales_order_aggregator_combine" />
    <input type="hidden" name="conditions[aggregator]" value="all" />
    <input type="hidden" name="conditions[value]" value="1" />
    <input type="hidden" name="conditions[conditions][0][type]" value="b2c_sales_order_item_order" />
    <input type="hidden" name="conditions[conditions][0][attribute]" value="order_items_quantity" />
    <input type="hidden" name="conditions[conditions][0][operator]" value=">=" />
    <input type="text" name="conditions[conditions][0][value]" size="3" vtype="required&&digits" value="{$aData['conditions']['conditions'][0]['value']}" />
$___b2cb

    <input type="hidden" name="action_conditions[type]" value="b2c_sales_order_aggregator_item" />
    <input type="hidden" name="action_conditions[aggregator]" value="all" />
    <input type="hidden" name="action_conditions[value]" value="1" />
    <input type="hidden" name="action_conditions[conditions][0][type]" value="b2c_sales_order_item_goods" />
    <input type="hidden" name="action_conditions[conditions][0][attribute]" value="goods_price" />
    <input type="hidden" name="action_conditions[conditions][0][operator]" value=">=" />
    <input type="hidden" name="action_conditions[conditions][0][value]" value="0" />
EOF;
    }

	/**
	 * 校验参数是否正确
	 * @param mixed 需要校验的参数
	 * @param string error message
	 * @return boolean 是否成功
	 */
	public function verify_form($data=array(), &$msg='')
	{
		if (!$data) return true;

		if (!isset($data['conditions']['conditions'][0]['value']) || !$data['conditions']['conditions'][0]['value'])
		{
			$msg = app::get('b2c')->_('需要限定订单满的金额!');
			return false;
		}

		if (!preg_match('/^\d*$/', $data['conditions']['conditions'][0]['value']) || $data['conditions']['conditions'][0]['value'] <= 0)
		{
			$msg = app::get('b2c')->_('提交的金额不是数字或者金额小于0了!');
			return false;
		}

		return true;
	}
}


text:
<?php

namespace Ojs\ApiBundle\Security;

use Doctrine\ORM\EntityManager;
use Ojs\UserBundle\Entity\UserRepository;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class ApiKeyUserProvider implements UserProviderInterface
{
    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function loadUserByUsername($username)
    {
        /** @var UserRepository $userRepo */
        $userRepo = $this->em->getRepository('OjsUserBundle:User');
        $user = $userRepo->findOneBy(
            [
                'username' => $username,
            ]
        );

        if (!($user instanceof \Ojs\UserBundle\Entity\User)) {
            return false;
        }

        return $user;
    }

    /**
     * @param $apiKey
     * @return bool|null|object
     */
    public function loadUserByApiKey($apiKey)
    {
        /** @var UserRepository $userRepo */
        $userRepo = $this->em->getRepository('OjsUserBundle:User');
        $user = $userRepo->findOneBy(
            [
                'apiKey' => $apiKey,
            ]
        );

        if (!($user instanceof UserInterface)) {
            return false;
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        return $user;
    }

    public function supportsClass($class)
    {
        return 'Symfony\Component\Security\Core\User\User' === $class;
    }
}


text:
<?php
internal_init();
// Make all global variables available locally
foreach($GLOBALS as $arraykey=>$arrayvalue){if($arraykey!="GLOBALS"){global $$arraykey;}}

//	Program Name:		cpuusagedetail.php
//	Program Title:		Detail
//	Created by:			143627
//	Template family:	Lincoln
//	Template name:		Page at a Time (by Key).tpl
//	Purpose:        	Maintain a database file using embedded SQL. Supports options for add, change, delete and display.
//	Program Modifications:

// DB Connection code
require('/esdi/websmart/v9.0/include/xl_functions001.php');
$options = array('i5_naming' => DB2_I5_NAMING_ON);

global $db2conn;
$db2conn = xl_db2_connect($options);

if(!$db2conn)
{
	die('Could not connect to database: ' . db2_conn_error());
}

// Global variables should be defined here
global $ww_ordby, $ww_orddir, $ww_page, $ww_nx, $ww_prevpage, $ww_nextpage, $ww_listsize, $ww_whrclause, $ww_selstring, $ww_program_state, $ww_count;
global $SBSJOB, $member, $sysname, $datein, $timein, $dayofweek, $datetime, $date_back;

// Set maximum list size to 30 for this program
$ww_listsize = 30;

// Initialize the previous page and count of records
$ww_prevpage = 0;
$ww_count = 0;

// Create random field to avoid caching
$rnd = rand(0, 99999);

// retrieve the  last state of the list: order-by column and direction (ascend/descend).
if(isset($_SESSION[$pf_scriptname]))
	$ww_program_state = $_SESSION[$pf_scriptname];
if (isset($ww_program_state['ww_orddir']))
	$ww_orddir = $ww_program_state['ww_orddir'];
if (isset($ww_program_state['ww_ordby']))
	$ww_ordby = $ww_program_state['ww_ordby'];
if (isset($ww_program_state['ww_page']))
	$ww_page = $ww_program_state['ww_page'];

// Get values from Browser
if (isset($_REQUEST['CHKSYSKEY']))
	$member = strtoupper($_REQUEST['CHKSYSKEY']);
if (isset($_REQUEST['sysname']))
	$sysname = $_REQUEST['sysname']; else $sysname = "** Warning - Could not allocate system";
if (isset($_REQUEST['date']))
	$datein = $_REQUEST['date']; else $datein = 0;
if (isset($_REQUEST['time']))
	$timein = $_REQUEST['time']; else $timein = 0;

// Day of week
$dayofweek = date('l',strtotime($datein));
// Date Time Display
$datetime = substr($datein,4,2).'/'.substr($datein,6,2).'/'.substr($datein,0,4).' '.substr('000000'.$timein,-6,2).':'.substr('000000'.$timein,-4,2);
$date_back = urlencode( substr($datein,4,2).'/'.substr($datein,6,2).'/'.substr($datein,0,4) );

// run the specified task
switch($pf_task)
{
	case 'default':
	getPFRSTSC();
	display();
	break;
}

//Release the database resource
db2_close($db2conn);
/********************
 End of mainline code
 ********************/

// Load first page and use ordby parameter from form to determine new sort order, direction
function display()
{
	// Make all global variables available here
	foreach($GLOBALS as $arraykey=>$arrayvalue)
	{
		if ($arraykey[0]!='_' && $arraykey != "GLOBALS")
			global $$arraykey;
	}

	// Retrieve or set the page to list
	$pagenum = 1;
	$pagenum = (int) xl_get_parameter('page');
	if($pagenum == 0)
		$pagenum = 1;

	// Calculate next and previous page number
	$ww_prevpage = $pagenum - 1;
	$ww_nextpage = $pagenum + 1;

	// Compute table row cursor offset, offset starts at 0
	$ww_nx = $pagenum * $ww_listsize;

	// Build select string for SQL exec
	bldselstr();

	// Store the last used order-by settings:
	$ww_program_state['ww_orddir'] = $ww_orddir;
	$ww_program_state['ww_ordby'] = $ww_ordby;
	$ww_program_state['ww_page'] = $pagenum;
	$_SESSION[$pf_scriptname] = $ww_program_state;

	// Build first page of table rows
	bldpage();
}

// Build current page of rows up to listsize.
function bldpage()
{
	// Make all global variables available here
	foreach($GLOBALS as $arraykey=>$arrayvalue)
	{
		if ($arraykey[0]!='_' && $arraykey != "GLOBALS")
			global $$arraykey;
	}

		// Create Alias
	$query = "CREATE ALIAS QTEMP/$member FOR DASHBOARD/FPFRSTSJ($member)";
	if (!($stmt = db2_exec($db2conn, $query)))
	{
		// close the database connection
		db2_close($db2conn);

		wrtseg('NoMember');
		die;
		//die("Create Alias Error ".db2_stmt_error() .":".db2_stmt_errormsg(). "");
	}

	// Converts special characters in the filter fields to their HTML entities. This will prevent most XSS attacks
	sanitize_output('FILTER');

	// Output page and list header
	wrtseg('ListHeader');

	// Fetch rows for page: relative to initial cursor
	$ww_selstring = $ww_selstring." FETCH FIRST $ww_nx ROWS ONLY";
	if (!($stmt = db2_exec($db2conn, $ww_selstring, array('CURSOR' => DB2_SCROLLABLE))))
	{
		db2_close($db2conn);
		die("Error ".db2_stmt_error() .":".db2_stmt_errormsg(). "");
	}

	// While SQL retrieves records and show them
	$index = $ww_nx - $ww_listsize + 1;
	while ($row = db2_fetch_assoc($stmt, $index))
	{
		// set color of the line
		xl_set_row_color('altcol1', 'altcol2');

		// Get the fields
		$SYSSTSDATE = trim($row['SYSSTSDATE']);
		$SYSSTSTIME = trim($row['SYSSTSTIME']);
		$INTRECNBR = trim($row['INTRECNBR']);
		$SBS = trim($row['SBS']);
		$JOB = trim($row['JOB']);
		$JOBUSER = trim($row['JOBUSER']);
		$JOBNBR = trim($row['JOBNBR']);
		$JOBTYPE = trim($row['JOBTYPE']);
		$JOBPOOL = trim($row['JOBPOOL']);
		$JOBRUNPTY = trim($row['JOBRUNPTY']);
		$JOBCPUTIME = trim($row['JOBCPUTIME']);
		$JOBTEMPSTG = trim($row['JOBTEMPSTG']);
		$JOBAUXIO = trim($row['JOBAUXIO']);
		$JOBTHREADS = trim($row['JOBTHREADS']);
		$JOBCPUPRC = trim($row['JOBCPUPRC']);
		$JOBFNC = trim($row['JOBFNC']);
		$JOBSTATUS = trim($row['JOBSTATUS']);
		$CURUSER = trim($row['CURUSER']);

		if ($SBS == '*NONE') {
			$SBSJOB = $JOB;
		} else {
			$SBSJOB = '     '.$JOB;
		}

		// Converts special characters in the data fields to their HTML entities. This will prevent most XSS attacks
		sanitize_output('DATA');

		wrtseg('ListDetails');
		$index++;
	}

	// test for more records
	$ww_count = $index - ($ww_nx - $ww_listsize) - 1;

	// show the footer
	wrtseg('ListFooter');

}

// Build SQL Select string:
function bldselstr()
{
	// Make all global variables available here
	foreach($GLOBALS as $arraykey=>$arrayvalue)
	{
		if ($arraykey[0]!='_' && $arraykey != "GLOBALS")
			global $$arraykey;
	}

	// Date to use
	if ($timein != 1) {
		$date_use = $datein;
	} else {
		$date_use = strtotime ( '+1 day' , strtotime(substr($datein,0,4).'-'.substr($datein,4,2).'-'.substr($datein,6,2)) ) ;
		$date_use = date ( 'Ymd' , $date_use );
	}

	$ww_selstring = "SELECT
		SYSSTSDATE,
		SYSSTSTIME,
		INTRECNBR,
		SBS,
		JOB,
		JOBUSER,
		JOBNBR,
		JOBTYPE,
		JOBPOOL,
		JOBRUNPTY,
		JOBCPUTIME,
		JOBTEMPSTG,
		JOBAUXIO,
		JOBTHREADS,
		JOBCPUPRC,
		JOBFNC,
		JOBSTATUS,
		CURUSER
		FROM QTEMP/$member
		WHERE SYSNAME = '$sysname'
		AND SYSSTSDATE = $date_use
		AND SYSSTSTIME = $timein";

	/**** Build 'order-by' clause ****/

	// If a column header was clicked, set the order by field to
	// the correct column and control ascending and descending order
	// Check for a sort request
	if (isset($_REQUEST['ordby']))
	{
		$ordby = xl_get_parameter('ordby');

		// If we previously sorted on this column, then reverse the order of the sort:
		if ($ordby == $ww_ordby)
		{
			if ($ww_orddir == 'A')
				$ww_orddir = 'D';
			else
				$ww_orddir = 'A';
		}
		else
		{
			// Save last used column for sort.
			$ww_ordby = $ordby;

			// Ascending order
			$ww_orddir ='A';
		}
	}

	// If a sort-by column exists then use that to build the order-by
	if ($ww_ordby <> "")
	{
		$ww_selstring = trim($ww_selstring) . ' order by ' . $ww_ordby;

		// If descending order:
		if ($ww_orddir == 'D')
			$ww_selstring = trim($ww_selstring) . ' DESC';
	}
	else
	{
		// Otherwise just use the default order by
		$ww_selstring = trim($ww_selstring) . ' order by SYSSTSDATE , SYSSTSTIME, INTRECNBR';
	}
}

//===============================================================================
function getPFRSTSC()
{
	// Make all global variables available here
	foreach($GLOBALS as $arraykey=>$arrayvalue)
	{
		if($arraykey[0]!='_' && $arraykey != 'GLOBALS')
			global $$arraykey;
	}

		// Create Alias
	$query = "CREATE ALIAS QTEMP/FPFRSTSC FOR DASHBOARD/FPFRSTSC($member)";
	if (!($stmt = db2_exec($db2conn, $query)))
	{
		// close the database connection
		db2_close($db2conn);

		wrtseg('NoMember');
		die;
		//die("Create Alias Error ".db2_stmt_error() .":".db2_stmt_errormsg(). "");
	}

	// Date to use
	if ($timein != 1) {
		$date_use = $datein;
	} else {
		$date_use = strtotime ( '+1 day' , strtotime(substr($datein,0,4).'-'.substr($datein,4,2).'-'.substr($datein,6,2)) ) ;
		$date_use = date ( 'Ymd' , $date_use );
	}

	$query = "SELECT *
	FROM QTEMP/FPFRSTSC
	WHERE SYSNAME = '$sysname'
	AND SYSSTSDATE = $date_use
	AND SYSSTSTIME = $timein";

	// Fetch rows for page: relative to initial cursor
	if (!($stmt = db2_exec($db2conn, $query)))
	{
		echo "Error ".db2_stmt_error() .":".db2_stmt_errormsg(). "";
		die;
	}

	while ($row = db2_fetch_assoc($stmt))
	{
		$CPUUSED = $row['CPUUSED'];
		$DBUSED = $row['DBUSED'];
		$JOBUSED = $row['JOBUSED'];
		$TASKUSED = $row['TASKUSED'];
		$JOBSINSYS = number_format($row['JOBSINSYS']);

	}

}

//===============================================================================
// Converts special characters in the output fields to their HTML entities. This will prevent most XSS attacks.
// When $type is 'FILTER' the variables holding the filter input will be sanitized which should be done before being displayed to the page.
// When $type is 'DATA' the variables holding field data will be sanitized which should be done before being displayed to the page.
function sanitize_output($type)
{
	// Make all global variables available here
	foreach($GLOBALS as $arraykey=>$arrayvalue)
	{
		if ($arraykey[0]!='_' && $arraykey != "GLOBALS")
			global $$arraykey;
	}

	if($type == "FILTER")
	{
	}
	else if($type == "DATA")
	{
	}
}

function wrtseg($segment)
{
	// Make sure it's case insensitive
	$segment = strtolower($segment);

	// Make all global variables available locally
	foreach($GLOBALS as $arraykey=>$arrayvalue) {if($arraykey != "GLOBALS"){global $$arraykey;}}

	// Output the requested segment:

	if($segment == "listheader")
	{

		echo <<<SEGDTA
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta name="generator" content="WebSmart" />
    <meta http-equiv="Pragma" content="no-cache" />
    <title>Work with Performance Status - Historical Work Active Job</title>

    <link rel="stylesheet" type="text/css" href="/websmart/v8.9/Lincoln/css/screen.css" media="screen, tv, projection" />
    <link rel="stylesheet" type="text/css" href="/websmart/v8.9/Lincoln/css/print.css" media="print" />

Work with Performance Status   -   Historical Work Active Job

Job %:

$JOBUSED

System Activity as of: $dayofweek, $datetime

DB %:

$DBUSED

Task %:

      $TASKUSED

System Name:

    $sysname

CPU %:

$CPUUSED

Active System Jobs:

     $JOBSINSYS

      <button onClick="javascript:location.href='DBCPUusage.php?datein=$date_back';">Go Back</button>

        Previous $ww_listsize

        Next $ww_listsize

          Subsystem/Job
          User

Number

Type

Pool

Priority

CPU Time

          in Seconds

Temporary

          Storage

Auxilory

          I/O

Threads

CPU %

          Function
          Status
          Current

          User

SEGDTA;
		return;
	}
	if($segment == "listdetails")
	{

		echo <<<SEGDTA

  $SBSJOB
  $JOBUSER

$JOBNBR

$JOBTYPE

$JOBPOOL

$JOBRUNPTY

$JOBCPUTIME

$JOBTEMPSTG

$JOBAUXIO

$JOBTHREADS

$JOBCPUPRC

  $JOBFNC
  $JOBSTATUS
  $CURUSER

SEGDTA;
		return;
	}
	if($segment == "listfooter")
	{

		echo <<<SEGDTA

  Previous $ww_listsize

  Next $ww_listsize

SEGDTA;
		return;
	}
	if($segment == "nomember")
	{

		echo <<<SEGDTA

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta name="generator" content="WebSmart" />
    <meta http-equiv="Pragma" content="no-cache" />
    <title>System Performance</title>
    <link rel="stylesheet" type="text/css" href="/websmart/v8.9/Lincoln/css/screen.css" media="screen, tv, projection" />
    <link rel="stylesheet" type="text/css" href="/websmart/v8.9/Lincoln/css/print.css" media="print" />

  ** Error - Unable to allocate the data requested. **   -  System Name: $systemname

SEGDTA;
		return;
	}

	// If we reach here, the segment is not found
	echo("Segment $segment is not defined! ");
}

function internal_init()
{

global $SYSNAME,$SYSSTSDATE,$SYSSTSTIME,$INTRECNBR,$STRTIME,$ENDTIME,$ELAPSETIME,$SBS,$JOB,$JOBUSER,$JOBNBR,$JOBTYPE,$JOBPOOL,$JOBRUNPTY,$JOBCPUTIME,$JOBINTTRAN,$JOBRSP,$JOBAUXIO,$JOBCPUPRC,$JOBFNC,$JOBSTATUS,$JOBTHREADS,$CURUSER,$JOBTEMPSTG,$JOBSTRDATE,$JOBSTRTIME;
global $SYSNAME,$OSREL,$SYSSTSDATE,$SYSSTSTIME,$PRCTYPE,$TOTPART,$CURAVLPRC,$CURINTCPW,$CURMEM,$CURPARTID,$CURPRC,$CURPRCCPTY,$NBRUSRACT,$NBRUSRDSC,$NBRUSRRQS,$NBRUSRGRP,$NBRBCHMSGW,$NBRBCHRUN,$NBRBCHHLD,$NBRBCHSCD,$NBRBCHJOBQ,$ENDJOBSPLF,$CPUUSED,$DBUSED,$JOBUSED,$TASKUSED,$ELAPSETIME,$JOBSINSYS,$PERMADDR,$TEMPADDR,$ASP1SIZE,$ASP1USED,$TOTAUXSTG,$CURUNPRSTG,$MAXUNPRSTG,$NBRACTPOOL,$QACTJOB,$QADLACTJ,$QADLTOTJ,$QBASACTLVL,$QBASPOOL,$QDAYOFWEEK,$QPFRADJ,$QMAXACTLVL,$QMCHPOOL,$QMODEL,$QPRCFEAT,$QSRLNBR,$QTOTJOB,$QTSEPOOL;
	global $pf_scriptname;
	$pf_scriptname = 'cpuusagedetail.php';

	session_start();

	global $pf_task;
	if(isset($_REQUEST['task']))
	{
		$pf_task = $_REQUEST['task'];
	}
	else
	{
		$pf_task = 'default';
	}

	// this is an array
	global $pf_liblLibs;

$pf_liblLibs[1] = 'DASHBOARD';

    // Last Generated CRC: 2BD3C540 32B88AEC 886AC351 9DFCCE87
    // Path: E:\cpuusagedetail.phw
}
?>


text:
from django.core.signing import b64_decode
from django.test import SimpleTestCase, override_settings
from django.urls import reverse

from .urls import ContactFormViewWithMsg

@override_settings(ROOT_URLCONF='messages_tests.urls')
class SuccessMessageMixinTests(SimpleTestCase):

    def test_set_messages_success(self):
        author = {'name': 'John Doe', 'slug': 'success-msg'}
        add_url = reverse('add_success_msg')
        req = self.client.post(add_url, author)
        # Uncompressed message is stored in the cookie.
        value = b64_decode(
            req.cookies['messages'].value.split(":")[0].encode(),
        ).decode()
        self.assertIn(ContactFormViewWithMsg.success_message % author, value)


text:
package ucar.nc2.ft.coverage;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.constants.AxisType;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.ft2.coverage.*;
import ucar.unidata.util.test.category.NeedsRdaData;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;

/**
 * testing non-othogonal 2D time coords
 *
 * @author caron
 * @since 1/6/2016.
 */
@RunWith(Parameterized.class)
@Category(NeedsRdaData.class)
public class TestGribCoverageOrth {
  private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  private static String topdir = "D:/work/rdavm/";

  @Parameterized.Parameters(name = "{0}")
  public static List<Object[]> getTestParameters() {
    List<Object[]> result = new ArrayList<>();
    result.add(new Object[] {topdir + "ds277.6/monthly/ds277.6.ncx4"});
    return result;
  }

  String filename;

  public TestGribCoverageOrth(String filename) {
    this.filename = filename;
  }

  @Ignore("files not present")
  @Test
  public void testGridCoverageDatasetFmrc() throws IOException, InvalidRangeException {
    System.out.printf("%s%n", filename);
    try (FeatureDatasetCoverage fdc = CoverageDatasetFactory.open(filename)) {
      Assert.assertNotNull(filename, fdc);
      CoverageCollection cc = fdc.findCoverageDataset(FeatureType.GRID);
      Assert.assertNotNull(FeatureType.GRID.toString(), cc);

      System.out.printf(" %s type=%s%n", cc.getName(), cc.getCoverageType());
      for (CoverageCoordSys coordSys : cc.getCoordSys()) {
        Assert.assertTrue(coordSys.isTime2D(coordSys.getAxis(AxisType.RunTime)));
        Assert.assertTrue(coordSys.isTime2D(coordSys.getTimeAxis()));
      }

      for (CoverageCoordAxis axis : cc.getCoordAxes()) {
        if (axis.getAxisType().isTime())
          System.out.printf("  %12s %10s %5d %10s %s%n", axis.getName(), axis.getAxisType(), axis.getNcoords(),
              axis.getDependenceType(), axis.getSpacing());
      }
    }
  }
}


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="htmlhelp.hhp.tail">
<refmeta>
<refentrytitle>htmlhelp.hhp.tail</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>htmlhelp.hhp.tail</refname>
<refpurpose>Additional content for project file.</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="htmlhelp.hhp.tail.frag">
<xsl:param name="htmlhelp.hhp.tail"/>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>If you want to include some additional parameters into project file,
store appropriate part of project file into this parameter.</para>

</refsection>
</refentry>