text:
namespace Microsoft.Azure.Management.NotificationHubs
{
    using System.Threading.Tasks;
   using Microsoft.Rest.Azure;
   using Models;

    /// <summary>
    /// Extension methods for NamespacesOperations.
    /// </summary>
    public static partial class NamespacesOperationsExtensions
    {
            /// <summary>
            /// Checks the availability of the given service namespace across all Azure
            /// subscriptions. This is useful because the domain name is created based on
            /// the service namespace name.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='parameters'>
            /// The namespace name.
            /// </param>
            public static CheckAvailabilityResult CheckAvailability(this INamespacesOperations operations, CheckAvailabilityParameters parameters)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CheckAvailabilityAsync(parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Checks the availability of the given service namespace across all Azure
            /// subscriptions. This is useful because the domain name is created based on
            /// the service namespace name.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='parameters'>
            /// The namespace name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<CheckAvailabilityResult> CheckAvailabilityAsync(this INamespacesOperations operations, CheckAvailabilityParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.CheckAvailabilityWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Creates/Updates a service namespace. Once created, this namespace's
            /// resource manifest is immutable. This operation is idempotent.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='parameters'>
            /// Parameters supplied to create a Namespace Resource.
            /// </param>
            public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Creates/Updates a service namespace. Once created, this namespace's
            /// resource manifest is immutable. This operation is idempotent.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='parameters'>
            /// Parameters supplied to create a Namespace Resource.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Deletes an existing namespace. This operation also removes all associated
            /// notificationHubs under the namespace.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
            {
                System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None,  System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Deletes an existing namespace. This operation also removes all associated
            /// notificationHubs under the namespace.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// Deletes an existing namespace. This operation also removes all associated
            /// notificationHubs under the namespace.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
            {
                System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None,  System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Deletes an existing namespace. This operation also removes all associated
            /// notificationHubs under the namespace.
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// Returns the description for the specified namespace.
            /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Returns the description for the specified namespace.
            /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Creates an authorization rule for a namespace
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Aauthorization Rule Name.
            /// </param>
            /// <param name='parameters'>
            /// The shared access authorization rule.
            /// </param>
            public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Creates an authorization rule for a namespace
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Aauthorization Rule Name.
            /// </param>
            /// <param name='parameters'>
            /// The shared access authorization rule.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Deletes a namespace authorization rule
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Authorization Rule Name.
            /// </param>
            public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
            {
                System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None,  System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Deletes a namespace authorization rule
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Authorization Rule Name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// Gets an authorization rule for a namespace by name.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Authorization rule name.
            /// </param>
            public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets an authorization rule for a namespace by name.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name
            /// </param>
            /// <param name='authorizationRuleName'>
            /// Authorization rule name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists the available namespaces within a resourceGroup.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. If resourceGroupName value is null the
            /// method lists all the namespaces within subscription
            /// </param>
            public static Microsoft.Rest.Azure.IPage<NamespaceResource> List(this INamespacesOperations operations, string resourceGroupName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists the available namespaces within a resourceGroup.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. If resourceGroupName value is null the
            /// method lists all the namespaces within subscription
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAsync(this INamespacesOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists all the available namespaces within the subscription irrespective of
            /// the resourceGroups.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAll(this INamespacesOperations operations)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists all the available namespaces within the subscription irrespective of
            /// the resourceGroups.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllAsync(this INamespacesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Gets the authorization rules for a namespace.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name
            /// </param>
            public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the authorization rules for a namespace.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Gets the Primary and Secondary ConnectionStrings to the namespace
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// The connection string of the namespace for the specified authorizationRule.
            /// </param>
            public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the Primary and Secondary ConnectionStrings to the namespace
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// The connection string of the namespace for the specified authorizationRule.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// The connection string of the namespace for the specified authorizationRule.
            /// </param>
            /// <param name='parameters'>
            /// Parameters supplied to regenerate the Namespace Authorization Rule Key.
            /// </param>
            public static ResourceListKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule
            /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='namespaceName'>
            /// The namespace name.
            /// </param>
            /// <param name='authorizationRuleName'>
            /// The connection string of the namespace for the specified authorizationRule.
            /// </param>
            /// <param name='parameters'>
            /// Parameters supplied to regenerate the Namespace Authorization Rule Key.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async System.Threading.Tasks.Task<ResourceListKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists the available namespaces within a resourceGroup.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListNext(this INamespacesOperations operations, string nextPageLink)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists the available namespaces within a resourceGroup.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists all the available namespaces within the subscription irrespective of
            /// the resourceGroups.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAllNext(this INamespacesOperations operations, string nextPageLink)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists all the available namespaces within the subscription irrespective of
            /// the resourceGroups.
            /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Gets the authorization rules for a namespace.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink)
            {
                return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the authorization rules for a namespace.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
            {
                using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


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

<TITLE>
Uses of Class com.mattwilliamsnyc.service.remix.Element
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.mattwilliamsnyc.service.remix.Element

Packages that use Element

com.mattwilliamsnyc.service.remix
Overview

com.mattwilliamsnyc.service.remix.util

Uses of Element in com.mattwilliamsnyc.service.remix

Methods in com.mattwilliamsnyc.service.remix that return Element

 Element
Element.addChild(Element child)

          Adds a child element to this element.

 Element
Response.getDocumentRoot()

          Retrieves the root element of the response document.

 Element
Element.removeChild(Element element)

          Removes a child element from this element's children.

 Element
Element.setAttribute(java.lang.String name,
             java.lang.String value)

          Assigns an attribute to this Element.

 Element
Element.setValue(java.lang.Object value)

          Assigns a value to this Element.

Methods in com.mattwilliamsnyc.service.remix that return types with arguments of type Element

 java.util.List<Element>
Element.getChildren()

          Returns this element's children; returns null if this element has no children.

Methods in com.mattwilliamsnyc.service.remix with parameters of type Element

 Element
Element.addChild(Element child)

          Adds a child element to this element.

 Element
Element.removeChild(Element element)

          Removes a child element from this element's children.

Constructors in com.mattwilliamsnyc.service.remix with parameters of type Element

Category(Element element)

          Creates a new Category entity from a document representation.

Entity(Element root)

          Creates a new entity from a document tree.

ErrorDocument(int statusCode,
              Element element)

          Creates a new error document with a specified status code and document tree.

Offer(Element element)

          Creates a new Offer entity from a document representation.

Product(Element element)

          Creates a new Product from an document representation.

RelatedItem(Element element)

          Creates a new RelatedItem entity from a document representation.

Store(Element element)

          Creates a new Store from a document representation.

Uses of Element in com.mattwilliamsnyc.service.remix.util

Methods in com.mattwilliamsnyc.service.remix.util that return Element

 Element
XMLHandler.getDocumentRoot()

          Retrieve the root element of the document tree parsed by this handler.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

redpajama_set_name: RedPajamaGithub


text:
package com.sinoir.rest.repositories.gtfs;

import com.sinoir.rest.models.gtfs.Agency;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AgencyRepo extends CrudRepository<Agency, String> {}


text:
version=`curl https://tomcat.apache.org/whichversion.html`
version=${version#*Apache Tomcat Versions}
version=${version#*9.0.x}
version=${version#*<td>}
version=${version%%</td>*}
curl -O https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-9/v$version/bin/apache-tomcat-$version.tar.gz
tar -zxf apache-tomcat-$version.tar.gz
rm -rf apache-tomcat-$version.tar.gz

cd apache-tomcat-$version
sed -i '/# OS specific support/i\export LC_ALL="zh_CN.UTF-8"' bin/catalina.sh
sed -i '/# OS specific support/i\JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -Dfile.encoding=UTF-8"\n' bin/catalina.sh
sed -i 's/>> "$CATALINA_OUT" 2>&1 "&"/>> "$CATALINA_OUT" 2>\&1/g' bin/catalina.sh
sed -i 's/port="8080"/port="8080"\n               compression="on"\n               compressionMinSize="4096"\n               compressableMimeType="application\/json"\n              /' conf/server.xml

rm -rf webapps
mkdir -p webapps
rm -rf logs
mkdir -p logs

mv /run.sh bin/
chmod +x bin/run.sh

ln -s /apache-tomcat-$version /tomcat


text:
using System;
using System.Linq;
using System.Text;
using OpenQA.Selenium;

namespace TelerikAcademyWebDriver.Exceptions
{
    public class StillCheckedException : ApplicationException
    {
        public StillCheckedException()
        {
        }

        public StillCheckedException(By by, BaseWebDriverTest ext, Exception ex)
        {
            string message = this.BuildStillCheckedExceptionText(by, ext);

            throw new ApplicationException(message, ex);
        }

        public StillCheckedException(By by, BaseWebDriverTest ext)
        {
            string message = this.BuildStillCheckedExceptionText(by, ext);

            throw new ApplicationException(message);
        }

        private string BuildStillCheckedExceptionText(By by, BaseWebDriverTest ext)
        {
            StringBuilder sb = new StringBuilder();

            string customLoggingMessage =
                String.Format("#### The element with the location strategy:  {0} ####\n ####WAS CHECKED!####",
                    by.ToString());
            sb.AppendLine(customLoggingMessage);

            string cuurentUrlMessage = String.Format("The URL when the test failed was: {0}", ext.Browser.Url);
            sb.AppendLine(cuurentUrlMessage);

            return sb.ToString();
        }
    }
}


text:
"""
===========================================================
Image filtering and manipulation (:mod:`filtering` package)
===========================================================

This package contains various image filters and image manipulation functions.

Filter pipeline (:mod:`filtering.filter`)
-----------------------------------------

.. automodule:: filtering.filter
    :members:

Miscellaneous (:mod:`filtering.misc`)
-------------------------------------

.. automodule:: filtering.misc
    :members:

Pre-processing (:mod:`filtering.preprocessing`)
-----------------------------------------------

.. automodule:: filtering.preprocessing
    :members:

Post-processing (:mod:`filtering.postprocessing`)
-------------------------------------------------

.. automodule:: filtering.postprocessing
    :members:

Registration (:mod:`filtering.registration`)
--------------------------------------------

.. automodule:: filtering.registration
    :members:

Feature extraction (:mod:`filtering.feature_extraction`)
--------------------------------------------------------

.. automodule:: filtering.feature_extraction
    :members:

"""


text:
package com.szadowsz.cadisainmduit.people.census.uk

import com.szadowsz.cadisainmduit.people.census.uk.engwales.{EngWalNamesFreqCalculator, EngWalNamesStatsSplicer}
import com.szadowsz.cadisainmduit.people.census.uk.norire.{NorireNamesFreqCalculator, NorireNamesStatsSplicer}
import com.szadowsz.cadisainmduit.people.census.uk.scotland.{ScotGirlNamesStatsSplicer, ScotNamesFreqCalculator}
import com.szadowsz.common.io.write.CsvWriter
import com.szadowsz.spark.ml.Lineage
import com.szadowsz.spark.ml.feature.{AverageTransformer, ColFilterTransformer, NullReplacer, RoundingTransformer}
import org.apache.spark.ml.feature.{IndexToString, StringIndexerModel, VectorAssembler}
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.types.{IntegerType, NumericType}
import org.apache.spark.sql.functions._

/**
  * Created on 16/01/2017.
  */
object UkCensusNamesFreqCalculator {

  def loadData(save: Boolean): DataFrame = {
    val ni = NorireNamesFreqCalculator.loadData(false)
    val scot = ScotNamesFreqCalculator.loadData(false)
    val engwal = EngWalNamesFreqCalculator.loadData(false)

    val uk = ni.join(scot, Seq("name", "gender"), "outer").join(engwal, Seq("name", "gender"), "outer").na.fill("unused").cache()

    val fracs = uk.columns.filter(_.contains("AppRank"))

    val pipe = new Lineage("uk")
    fracs.foreach(r => pipe.addStage(new StringIndexerModel(s"$r-Indexer",Array("unused","rare","uncommon","common","basic")).setInputCol(r).setOutputCol(r + "Ind")))
    pipe.addStage(classOf[AverageTransformer],"inputCols" -> fracs.map(_ + "Ind").toArray, "outputCol" -> "UK_RawAppRank")
    pipe.addStage(classOf[RoundingTransformer],"inputCol" -> "UK_RawAppRank", "outputCol" -> "UK_RoundedAppRank")
    pipe.addStage(classOf[IndexToString],"inputCol" -> "UK_RoundedAppRank", "outputCol" -> "UK_AppRank", "labels" -> Array("unused","rare","uncommon","common","basic"))
    val (model,ukDf) = pipe.fitAndTransform(uk)
    val df = ukDf.select("name","gender", "EW_AppRank","SC_AppRank","NI_AppRank","UK_AppRank")

    if (save) {
      val writer = new CsvWriter("./data/results/uk_baby_names.csv", "UTF-8", false)
      writer.write(df.schema.fieldNames: _*)
      val res = df.collect().map(r => r.toSeq.map(f => Option(f).map(_.toString).getOrElse(""))).filter(_.head.length > 0)
      writer.writeAll(res.sortBy(seq => (seq.head)))
      //writer.write(tots: _*)
      writer.close()
    }

    df
  }

  def main(args: Array[String]): Unit = {
    loadData(true)
  }
}


text:
using namespace llvm;

#define DEBUG_TYPE "amdgpu-nsa-reassign"

STATISTIC(NumNSAInstructions,
          "Number of NSA instructions with non-sequential address found");
STATISTIC(NumNSAConverted,
          "Number of NSA instructions changed to sequential");

namespace {

class GCNNSAReassign : public MachineFunctionPass {
public:
  static char ID;

  GCNNSAReassign() : MachineFunctionPass(ID) {
    initializeGCNNSAReassignPass(*PassRegistry::getPassRegistry());
  }

  bool runOnMachineFunction(MachineFunction &MF) override;

  StringRef getPassName() const override { return "GCN NSA Reassign"; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<LiveIntervals>();
    AU.addRequired<VirtRegMap>();
    AU.addRequired<LiveRegMatrix>();
    AU.setPreservesAll();
    MachineFunctionPass::getAnalysisUsage(AU);
  }

private:
  typedef enum {
    NOT_NSA,        // Not an NSA instruction
    FIXED,          // NSA which we cannot modify
    NON_CONTIGUOUS, // NSA with non-sequential address which we can try
                    // to optimize.
    CONTIGUOUS      // NSA with all sequential address registers
  } NSA_Status;

  const GCNSubtarget *ST;

  const MachineRegisterInfo *MRI;

  const SIRegisterInfo *TRI;

  VirtRegMap *VRM;

  LiveRegMatrix *LRM;

  LiveIntervals *LIS;

  unsigned MaxNumVGPRs;

  const MCPhysReg *CSRegs;

  NSA_Status CheckNSA(const MachineInstr &MI, bool Fast = false) const;

  bool tryAssignRegisters(SmallVectorImpl<LiveInterval *> &Intervals,
                          unsigned StartReg) const;

  bool canAssign(unsigned StartReg, unsigned NumRegs) const;

  bool scavengeRegs(SmallVectorImpl<LiveInterval *> &Intervals) const;
};

} // End anonymous namespace.

INITIALIZE_PASS_BEGIN(GCNNSAReassign, DEBUG_TYPE, "GCN NSA Reassign",
                      false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
INITIALIZE_PASS_END(GCNNSAReassign, DEBUG_TYPE, "GCN NSA Reassign",
                    false, false)

char GCNNSAReassign::ID = 0;

char &llvm::GCNNSAReassignID = GCNNSAReassign::ID;

bool
GCNNSAReassign::tryAssignRegisters(SmallVectorImpl<LiveInterval *> &Intervals,
                                   unsigned StartReg) const {
  unsigned NumRegs = Intervals.size();

  for (unsigned N = 0; N < NumRegs; ++N)
    if (VRM->hasPhys(Intervals[N]->reg))
      LRM->unassign(*Intervals[N]);

  for (unsigned N = 0; N < NumRegs; ++N)
    if (LRM->checkInterference(*Intervals[N], StartReg + N))
      return false;

  for (unsigned N = 0; N < NumRegs; ++N)
    LRM->assign(*Intervals[N], StartReg + N);

  return true;
}

bool GCNNSAReassign::canAssign(unsigned StartReg, unsigned NumRegs) const {
  for (unsigned N = 0; N < NumRegs; ++N) {
    unsigned Reg = StartReg + N;
    if (!MRI->isAllocatable(Reg))
      return false;

    for (unsigned I = 0; CSRegs[I]; ++I)
      if (TRI->isSubRegisterEq(Reg, CSRegs[I]) &&
          !LRM->isPhysRegUsed(CSRegs[I]))
      return false;
  }

  return true;
}

bool
GCNNSAReassign::scavengeRegs(SmallVectorImpl<LiveInterval *> &Intervals) const {
  unsigned NumRegs = Intervals.size();

  if (NumRegs > MaxNumVGPRs)
    return false;
  unsigned MaxReg = MaxNumVGPRs - NumRegs + AMDGPU::VGPR0;

  for (unsigned Reg = AMDGPU::VGPR0; Reg <= MaxReg; ++Reg) {
    if (!canAssign(Reg, NumRegs))
      continue;

    if (tryAssignRegisters(Intervals, Reg))
      return true;
  }

  return false;
}

GCNNSAReassign::NSA_Status
GCNNSAReassign::CheckNSA(const MachineInstr &MI, bool Fast) const {
  const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
  if (!Info || Info->MIMGEncoding != AMDGPU::MIMGEncGfx10NSA)
    return NSA_Status::NOT_NSA;

  int VAddr0Idx =
    AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vaddr0);

  unsigned VgprBase = 0;
  bool NSA = false;
  for (unsigned I = 0; I < Info->VAddrDwords; ++I) {
    const MachineOperand &Op = MI.getOperand(VAddr0Idx + I);
    unsigned Reg = Op.getReg();
    if (TargetRegisterInfo::isPhysicalRegister(Reg) || !VRM->isAssignedReg(Reg))
      return NSA_Status::FIXED;

    unsigned PhysReg = VRM->getPhys(Reg);

    if (!Fast) {
      if (!PhysReg)
        return NSA_Status::FIXED;

      // Bail if address is not a VGPR32. That should be possible to extend the
      // optimization to work with subregs of a wider register tuples, but the
      // logic to find free registers will be much more complicated with much
      // less chances for success. That seems reasonable to assume that in most
      // cases a tuple is used because a vector variable contains different
      // parts of an address and it is either already consequitive or cannot
      // be reassigned if not. If needed it is better to rely on register
      // coalescer to process such address tuples.
      if (MRI->getRegClass(Reg) != &AMDGPU::VGPR_32RegClass || Op.getSubReg())
        return NSA_Status::FIXED;

      const MachineInstr *Def = MRI->getUniqueVRegDef(Reg);

      if (Def && Def->isCopy() && Def->getOperand(1).getReg() == PhysReg)
        return NSA_Status::FIXED;

      for (auto U : MRI->use_nodbg_operands(Reg)) {
        if (U.isImplicit())
          return NSA_Status::FIXED;
        const MachineInstr *UseInst = U.getParent();
        if (UseInst->isCopy() && UseInst->getOperand(0).getReg() == PhysReg)
          return NSA_Status::FIXED;
      }

      if (!LIS->hasInterval(Reg))
        return NSA_Status::FIXED;
    }

    if (I == 0)
      VgprBase = PhysReg;
    else if (VgprBase + I != PhysReg)
      NSA = true;
  }

  return NSA ? NSA_Status::NON_CONTIGUOUS : NSA_Status::CONTIGUOUS;
}

bool GCNNSAReassign::runOnMachineFunction(MachineFunction &MF) {
  ST = &MF.getSubtarget<GCNSubtarget>();
  if (ST->getGeneration() < GCNSubtarget::GFX10)
    return false;

  MRI = &MF.getRegInfo();
  TRI = ST->getRegisterInfo();
  VRM = &getAnalysis<VirtRegMap>();
  LRM = &getAnalysis<LiveRegMatrix>();
  LIS = &getAnalysis<LiveIntervals>();

  const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
  MaxNumVGPRs = ST->getMaxNumVGPRs(MF);
  MaxNumVGPRs = std::min(ST->getMaxNumVGPRs(MFI->getOccupancy()), MaxNumVGPRs);
  CSRegs = TRI->getCalleeSavedRegs(&MF);

  using Candidate = std::pair<const MachineInstr*, bool>;
  SmallVector<Candidate, 32> Candidates;
  for (const MachineBasicBlock &MBB : MF) {
    for (const MachineInstr &MI : MBB) {
      switch (CheckNSA(MI)) {
      default:
        continue;
      case NSA_Status::CONTIGUOUS:
        Candidates.push_back(std::make_pair(&MI, true));
        break;
      case NSA_Status::NON_CONTIGUOUS:
        Candidates.push_back(std::make_pair(&MI, false));
        ++NumNSAInstructions;
        break;
      }
    }
  }

  bool Changed = false;
  for (auto &C : Candidates) {
    if (C.second)
      continue;

    const MachineInstr *MI = C.first;
    if (CheckNSA(*MI, true) == NSA_Status::CONTIGUOUS) {
      // Already happen to be fixed.
      C.second = true;
      ++NumNSAConverted;
      continue;
    }

    const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI->getOpcode());
    int VAddr0Idx =
      AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::vaddr0);

    SmallVector<LiveInterval *, 16> Intervals;
    SmallVector<unsigned, 16> OrigRegs;
    SlotIndex MinInd, MaxInd;
    for (unsigned I = 0; I < Info->VAddrDwords; ++I) {
      const MachineOperand &Op = MI->getOperand(VAddr0Idx + I);
      unsigned Reg = Op.getReg();
      LiveInterval *LI = &LIS->getInterval(Reg);
      if (llvm::find(Intervals, LI) != Intervals.end()) {
        // Same register used, unable to make sequential
        Intervals.clear();
        break;
      }
      Intervals.push_back(LI);
      OrigRegs.push_back(VRM->getPhys(Reg));
      MinInd = I ? std::min(MinInd, LI->beginIndex()) : LI->beginIndex();
      MaxInd = I ? std::max(MaxInd, LI->endIndex()) : LI->endIndex();
    }

    if (Intervals.empty())
      continue;

    LLVM_DEBUG(dbgs() << "Attempting to reassign NSA: " << *MI
                      << "\tOriginal allocation:\t";
               for(auto *LI : Intervals)
                 dbgs() << " " << llvm::printReg((VRM->getPhys(LI->reg)), TRI);
               dbgs() << '\n');

    bool Success = scavengeRegs(Intervals);
    if (!Success) {
      LLVM_DEBUG(dbgs() << "\tCannot reallocate.\n");
      if (VRM->hasPhys(Intervals.back()->reg)) // Did not change allocation.
        continue;
    } else {
      // Check we did not make it worse for other instructions.
      auto I = std::lower_bound(Candidates.begin(), &C, MinInd,
                                [this](const Candidate &C, SlotIndex I) {
                                  return LIS->getInstructionIndex(*C.first) < I;
                                });
      for (auto E = Candidates.end(); Success && I != E &&
              LIS->getInstructionIndex(*I->first) < MaxInd; ++I) {
        if (I->second && CheckNSA(*I->first, true) < NSA_Status::CONTIGUOUS) {
          Success = false;
          LLVM_DEBUG(dbgs() << "\tNSA conversion conflict with " << *I->first);
        }
      }
    }

    if (!Success) {
      for (unsigned I = 0; I < Info->VAddrDwords; ++I)
        if (VRM->hasPhys(Intervals[I]->reg))
          LRM->unassign(*Intervals[I]);

      for (unsigned I = 0; I < Info->VAddrDwords; ++I)
        LRM->assign(*Intervals[I], OrigRegs[I]);

      continue;
    }

    C.second = true;
    ++NumNSAConverted;
    LLVM_DEBUG(dbgs() << "\tNew allocation:\t\t ["
                 << llvm::printReg((VRM->getPhys(Intervals.front()->reg)), TRI)
                 << " : "
                 << llvm::printReg((VRM->getPhys(Intervals.back()->reg)), TRI)
                 << "]\n");
    Changed = true;
  }

  return Changed;
}


text:
use std::thread::{self, JoinGuard};
use std::sync::mpsc;
use std::collections::VecMap;
use net::NetworkListener;

pub struct ListenerPool<A: NetworkListener> {
    acceptor: A
}

impl<'a, A: NetworkListener + Send + 'a> ListenerPool<A> {
    /// Create a thread pool to manage the acceptor.
    pub fn new(acceptor: A) -> ListenerPool<A> {
        ListenerPool { acceptor: acceptor }
    }

    /// Runs the acceptor pool. Blocks until the acceptors are closed.
    ///
    /// ## Panics
    ///
    /// Panics if threads == 0.
    pub fn accept<F>(self, work: F, threads: usize)
        where F: Fn(A::Stream) + Send + Sync + 'a {
        assert!(threads != 0, "Can't accept on 0 threads.");

        let (super_tx, supervisor_rx) = mpsc::channel();

        let counter = &mut 0;
        let work = &work;
        let mut spawn = move || {
            let id = *counter;
            let guard = spawn_with(super_tx.clone(), work, self.acceptor.clone(), id);
            *counter += 1;
            (id, guard)
        };

        // Go
        let mut guards: VecMap<_> = (0..threads).map(|_| spawn()).collect();

        for id in supervisor_rx.iter() {
            guards.remove(&id);
            let (id, guard) = spawn();
            guards.insert(id, guard);
        }
    }
}

fn spawn_with<'a, A, F>(supervisor: mpsc::Sender<usize>, work: &'a F, mut acceptor: A, id: usize) -> thread::JoinGuard<'a, ()>
where A: NetworkListener + Send + 'a,
      F: Fn(<A as NetworkListener>::Stream) + Send + Sync + 'a {

    thread::scoped(move || {
        let _sentinel = Sentinel::new(supervisor, id);

        loop {
            match acceptor.accept() {
                Ok(stream) => work(stream),
                Err(e) => {
                    error!("Connection failed: {}", e);
                }
            }
        }
    })
}

struct Sentinel<T: Send + 'static> {
    value: Option<T>,
    supervisor: mpsc::Sender<T>,
    //active: bool
}

impl<T: Send + 'static> Sentinel<T> {
    fn new(channel: mpsc::Sender<T>, data: T) -> Sentinel<T> {
        Sentinel {
            value: Some(data),
            supervisor: channel,
            //active: true
        }
    }

    //fn cancel(mut self) { self.active = false; }
}

#[unsafe_destructor]
impl<T: Send + 'static> Drop for Sentinel<T> {
    fn drop(&mut self) {
        // If we were cancelled, get out of here.
        //if !self.active { return; }

        // Respawn ourselves
        let _ = self.supervisor.send(self.value.take().unwrap());
    }
}


text:
class PhysicsList;

class G4UIdirectory;
class G4UIcmdWithABool;
class G4UIcmdWithAString;
class G4UIcmdWithAnInteger;
class G4UIcmdWithoutParameter;
class G4UIcmdWithADoubleAndUnit;

/// Provide control of the physics list and cut parameters

class PhysicsListMessenger : public G4UImessenger
{
  public:

    PhysicsListMessenger(PhysicsList* );
    virtual ~PhysicsListMessenger();

    virtual void SetNewValue(G4UIcommand*, G4String);

  private:

    PhysicsList* fPhysicsList;

    G4UIdirectory* fDirectory;
    G4UIdirectory* fDecayDirectory;

    G4UIcmdWithABool* fSetAbsorptionCMD;

    G4UIcmdWithAnInteger* fVerboseCmd;
    G4UIcmdWithAnInteger* fCerenkovCmd;

    G4UIcmdWithADoubleAndUnit* fGammaCutCMD;
    G4UIcmdWithADoubleAndUnit* fElectCutCMD;
    G4UIcmdWithADoubleAndUnit* fPosCutCMD;
    G4UIcmdWithADoubleAndUnit* fAllCutCMD;
    G4UIcmdWithADoubleAndUnit* fStepMaxCMD;

    G4UIcmdWithAString*        fRemovePhysicsCMD;
    G4UIcmdWithoutParameter*   fClearPhysicsCMD;

    G4UIcmdWithoutParameter*   fListCMD;

    G4UIcmdWithoutParameter* fPienuCMD;
    G4UIcmdWithoutParameter* fPimunuCMD;

};

#endif


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

namespace _02.Max_Method
{
    class Program
    {
        static void Main(string[] args)
        {
            var firstNum = int.Parse(Console.ReadLine());
            var secondNum = int.Parse(Console.ReadLine());
            var thirdNum = int.Parse(Console.ReadLine());

            var maxNum = GetMax(firstNum, secondNum);
            maxNum = GetMax(maxNum, thirdNum);

            Console.WriteLine(maxNum);

        }

        static int GetMax(int num1, int num2)
        {
            if (num1 > num2)
            {
                return num1;
            }
            return num2;
        }
    }
}


text:
from JumpScale import j
import JumpScale.portal
import JumpScale.baselib.http_client
import unittest

MOUNT_LOCATION = '/opt/data'
SERVERNAME = 'localhost'
USERNAME = 'admin'
PASSWORD = 'admin'
SESSION_DATA = dict()

def setUpModule():
    j.system.fs.createDir(MOUNT_LOCATION)
    data = {'username': USERNAME, 'password': PASSWORD, 'hostname': SERVERNAME, 'mountlocation': MOUNT_LOCATION}
    j.system.process.execute('curlftpfs ftp://%(username)s:%(password)s@%(hostname)s %(mountlocation)s' % data)

def tearDownModule():
    # delete testspace
    j.system.fs.removeDir(j.system.fs.joinPaths(MOUNT_LOCATION, 'spaces', SESSION_DATA['spacename']))
    # delete testactor
    j.system.fs.removeDir(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname']))
    # delete testbucket
    j.system.fs.removeDir(j.system.fs.joinPaths(MOUNT_LOCATION, 'buckets', SESSION_DATA['bucketname']))

    j.system.process.execute('fusermount -u %s' % MOUNT_LOCATION)

class Tests(unittest.TestCase):

    def setUp(self):
        self.client = j.core.portal.getPortalClient('127.0.0.1', 9999, '1234')
        self.contentmanager = self.client.getActor('system', 'contentmanager', instance=0)

    def tearDown(self):
        pass

    def test_1_Mount(self):
        self.assertTrue(j.system.fs.isMount(MOUNT_LOCATION))

    def test_2_createSpace(self):
        SESSION_DATA['spacename'] = j.base.idgenerator.generateGUID()
        spacepath = j.system.fs.joinPaths(MOUNT_LOCATION, 'spaces', SESSION_DATA['spacename'])
        j.system.fs.createDir(spacepath)
        self.assertTrue(j.system.fs.exists(spacepath))
        self.assertIn(SESSION_DATA['spacename'], self.contentmanager.getSpaces())

    def test_3_createActor(self):
        SESSION_DATA['actorname'] = 'system__%s' % j.base.idgenerator.generateGUID()
        actorpath = j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'])
        j.system.fs.createDir(actorpath)
        self.assertTrue(j.system.fs.exists(actorpath))
        self.assertIn(SESSION_DATA['actorname'], self.contentmanager.getActors())

    def test_3_createBucket(self):
        SESSION_DATA['bucketname'] = j.base.idgenerator.generateGUID()
        bucketpath = j.system.fs.joinPaths(MOUNT_LOCATION, 'buckets', SESSION_DATA['bucketname'])
        j.system.fs.createDir(bucketpath)
        self.assertTrue(j.system.fs.exists(bucketpath))
        self.assertIn(SESSION_DATA['bucketname'], self.contentmanager.getBuckets())

    def test_4_createActorMethod(self):
        self.assertIn(SESSION_DATA['actorname'], self.contentmanager.getActors())
        j.system.fs.renameFile(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'specs', 'example__ActorModel.spec'), j.system.fs.joinPaths(
            MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'specs', 'model.spec'))
        j.system.fs.renameFile(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'specs', 'example__Actor.spec'), j.system.fs.joinPaths(
            MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'specs', 'actor.spec'))
        j.system.fs.createDir(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'methodclass'))
        actorparts = SESSION_DATA['actorname'].split('__')
        osisfilename = '%s_osis' % '_'.join(actorparts)
        osisfile = """
        from JumpScale import j
        class %s(j.code.classGetBase()):
            def __init__(self):
                self.dbmem=j.db.keyvaluestore.getMemoryStore()
                self.db=self.dbmem

        """ % osisfilename

        methodsfile = """
        from JumpScale import j
        from %(osisfilename)s import %(osisfilename)s

        class %(actorclassname)s(%(osisfilename)s):
            def __init__(self):
                self._te={}
                self.actorname=%(actorname)s
                self.appname=%(appname)s
                 %(osisfilename)s.__init__(self)

            def dosomething(self, path, id, bool):
                return True

            def returnlist(self):
                return [1, 2, 3]

        """ % {'osisfilename': osisfilename, 'actorclassname': '_'.join(actorparts), 'actorname': actorparts[1], 'appname': actorparts[0]}
        j.system.fs.writeFile(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA['actorname'], 'methodclass', '%s.py' % osisfilename), osisfile)
        j.system.fs.writeFile(j.system.fs.joinPaths(MOUNT_LOCATION, 'actors', SESSION_DATA[
                              'actorname'], 'methodclass', '%s.py' % '_'.join(actorparts)), methodsfile)

if __name__ == '__main__':
    unittest.main()


text:
JS_API : BETA
======

Javascript API for AFS

This API works to call ACP in cross-domain.

For this case the API works only in ASYNCHRONUS mode.

To use this API read the "API Documentation.doc"

You can look the index.html for example of integration and initialisation of ACP object.

Warning : If you call an ANTIDOT URL, you can have some CORS error. In this case thanks to contact the ANTIDOT Support.


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

        <title>Synthetic Typing Test</title>

start

Move over me

end


text:
/**
 * @fileOverview Extends the Dialog User Interface to add the option of using input type="number"
 */

/* globals CKEDITOR */

(function() {
	'use strict';

	CKEDITOR.plugins.add( 'numericinput', {
		requires: 'dialogui',
		init: function( editor ) {

			// Add hook to automatically use the numericinput type on existing dialogs that we don't want/can't change

			// Customize dialogs:
			CKEDITOR.on( 'dialogDefinition', function( ev ) {
				if ( editor != ev.editor )
					return;

				var dialogName = ev.data.name,
					dialogDefinition = ev.data.definition,
					tabsToProcess,
					tabName, fields, tab;

				if (dialogName == 'tableProperties')
					dialogName = 'table';

				var fieldsToModify = editor.config.numericinput_modifyfields;
				if (!fieldsToModify)
					return;

				/*
					numericinput_modifyfields is an object, each entry is the name of a dialog that we want to modify,
						the value is another object, the tabs of the dialog, and finally an object with the name of the fields.
					eg for the Table dialog
					config.numericinput_modifyfields = {
						'table': {
							'info' : {
									'txtRows': {
										'min': 1
									},
									'txtCols': {
										'min': 1
									},
									'txtBorder': {
									}, 'txtCellSpace': {
									},
									'txtCellPad': {
									}
							}
						}

					}
				*/
				// iterate the possible items defined in the configuration
				if ( fieldsToModify && ( tabsToProcess = fieldsToModify[ dialogName ] ) ) {
					for ( tabName in tabsToProcess ) {
						tab = dialogDefinition.getContents( tabName );
						if (!tab)
							continue;

						fields = tabsToProcess[ tabName ];
						for ( var fieldName in fields ) {
							var dialogField = tab.get( fieldName );
							if ( dialogField ) {
								dialogField.type = 'number';
								dialogField = CKEDITOR.tools.extend(dialogField, fields[ fieldName], true);
							}

						}
					}
				}
			});

			if (CKEDITOR.ui.dialog.numericInput)
				return;

			initNumericInput();
		}
	} );

	function initNumericInput() {
		var initPrivateObject = function( elementDefinition ) {
				if (!this._)
					this._ = {};
				this._[ 'default' ] = this._.initValue = elementDefinition[ 'default' ] || '';
				this._.required = elementDefinition.required || false;
				var args = [ this._ ];
				for ( var i = 1; i < arguments.length; i++ )
					args.push( arguments[ i ] );
				args.push( true );
				CKEDITOR.tools.extend.apply( CKEDITOR.tools, args );
				return this._;
			},
			numericBuilder = {
				build: function( dialog, elementDefinition, output ) {
					return new CKEDITOR.ui.dialog.numericInput( dialog, elementDefinition, output );
				}
			},
			commonPrototype = {
				isChanged: function() {
					return this.getValue() != this.getInitValue();
				},

				reset: function( noChangeEvent ) {
					this.setValue( this.getInitValue(), noChangeEvent );
				},

				setInitValue: function() {
					this._.initValue = this.getValue();
				},

				resetInitValue: function() {
					this._.initValue = this._[ 'default' ];
				},

				getInitValue: function() {
					return this._.initValue;
				}
			};

		CKEDITOR.tools.extend( CKEDITOR.ui.dialog, {
			/**
			 * A numeric input with a label.
			 *
			 * @class CKEDITOR.ui.dialog.numericInput
			 * @extends CKEDITOR.ui.dialog.labeledElement
			 * @constructor Creates a numericInput class instance.
			 * @param {CKEDITOR.dialog} dialog Parent dialog window object.
			 * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition
			 * The element definition. Accepted fields:
			 *
			 * * `default` (Optional) The default value.
			 * * `validate` (Optional) The validation function.
			 * * `min` (Optional) The minimum value of the input.
			 * * `max` (Optional) The maximum value of the input.
			 * * `step` (Optional) The step value of the input.
			 *
			 * @param {Array} htmlList List of HTML code to output to.
			 */
			numericInput: function( dialog, elementDefinition, htmlList ) {
				if ( arguments.length < 3 )
					return;

				initPrivateObject.call( this, elementDefinition );
				var domId = this._.inputId = CKEDITOR.tools.getNextId() + '_numericInput',
					attributes = { 'class': 'cke_dialog_ui_input_text cke_dialog_ui_input_number', id: domId, type: 'number' };

				// Set the validator, if any.
				if ( elementDefinition.validate )
					this.validate = elementDefinition.validate;

				// Set the min, max and step.
				if ( typeof elementDefinition.min != 'undefined' )
					attributes.min = elementDefinition.min;
				if ( typeof elementDefinition.max != 'undefined' )
					attributes.max = elementDefinition.max;
				if ( elementDefinition.step )
					attributes.step = elementDefinition.step;

				if ( elementDefinition.inputStyle )
					attributes.style = elementDefinition.inputStyle;

				// If user presses Enter in a text box, it implies clicking OK for the dialog.
				var me = this,
					keyPressedOnMe = false;
				dialog.on( 'load', function() {
					me.getInputElement().on( 'keydown', function( evt ) {
						if ( evt.data.getKeystroke() == 13 )
							keyPressedOnMe = true;
					} );

					// Lower the priority this 'keyup' since 'ok' will close the dialog.(#3749)
					me.getInputElement().on( 'keyup', function( evt ) {
						if ( evt.data.getKeystroke() == 13 && keyPressedOnMe ) {
							var okButton = dialog.getButton( 'ok' );
							if (okButton)
								setTimeout( function() {
									dialog.getButton( 'ok' ).click();
								}, 0 );
							keyPressedOnMe = false;
						}

					}, null, null, 1000 );
				} );

				var innerHTML = function() {
					// IE BUG: Text input fields in IE at 100% would exceed a  or inline
					// container's width, so need to wrap it inside a
.
					var html = [ '
<input ' );

					attributes[ 'aria-labelledby' ] = this._.labelId;
					if (this._.required)
						attributes[ 'aria-required' ] = this._.required;
					for ( var i in attributes )
						html.push( i + '="' + attributes[ i ] + '" ' );
					html.push( ' />
' );
					return html.join( '' );
				};
				CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
			}

		}, true );

		/** @class CKEDITOR.ui.dialog.numericInput */
		CKEDITOR.ui.dialog.numericInput.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement(), {
			/**
			 * Gets the text input DOM element under this UI object.
			 *
			 * @returns {CKEDITOR.dom.element} The DOM element of the text input.
			 */
			getInputElement: function() {
				return CKEDITOR.document.getById( this._.inputId );
			},

			/**
			 * Puts focus into the text input.
			 */
			focus: function() {
				var me = this.selectParentTab();

				// GECKO BUG: setTimeout() is needed to workaround invisible selections.
				setTimeout( function() {
					var element = me.getInputElement();
					if (element)
						element.$.focus();
				}, 0 );
			},

			/**
			 * Selects all the text in the text input.
			 */
			select: function() {
				var me = this.selectParentTab();

				// GECKO BUG: setTimeout() is needed to workaround invisible selections.
				setTimeout( function() {
					var e = me.getInputElement();
					if ( e ) {
						e.$.focus();
						e.$.select();
					}
				}, 0 );
			},

			/**
			 * Handler for the text input's access key up event. Makes a `select()`
			 * call to the text input.
			 */
			accessKeyUp: function() {
				this.select();
			},

			/**
			 * Sets the value of this numeric input object.
			 *
			 *		uiElement.setValue( 83 );
			 *
			 * @param {Number} value The new value.
			 * @returns {CKEDITOR.ui.dialog.textInput} The current UI element.
			 */
			setValue: function( value ) {
				return CKEDITOR.ui.dialog.uiElement.prototype.setValue.apply( this, arguments );
			},

			/**
			 * Gets the value of this number input object.
			 *
			 * @returns {String} The value.
			 */
			getValue: function() {
				return CKEDITOR.ui.dialog.uiElement.prototype.getValue.call( this );
				if ( value === '' )
					return value;

				return parseFloat( value );
			},

			/**
			 * Gets the value as number of this number input object.
			 *
			 * @returns {Number} The value.
			 */
			getValueAsNumber: function() {
				var value = CKEDITOR.ui.dialog.uiElement.prototype.getValue.call( this );
				if ( value === '' )
					return null;

				return parseFloat( value );
			},

			keyboardFocusable: true
		}, commonPrototype, true );

		CKEDITOR.dialog.addUIElement( 'number', numericBuilder );
	}
})();

/*
/**
 * An object to modify elements of existing dialogs and turn them to input type="number"
 *
 *		CKEDITOR.config.numericinput_modifyfields;
 *
 * @since 0.2
 * @cfg {Object} numericinput_modifyfields
 * @member CKEDITOR.config

The object is composed of dialog names, each of these properties is another object.
This second object then lists the tab names and its value is again an object.
In the third object the keys are the control names, and the value is an object with the properties that must me modified.

Example for the Table dialog:

config.numericinput_modifyfields = {
	'table': {
		'info' : {
			'txtRows': {
				'min': 1
			},
			'txtCols': {
				'min': 1
			},
			'txtBorder': {
				'min': 0,
				'controlStyle': 'width: 4em',
			},
			'txtCellSpace': {
				'min': 0,
				'controlStyle': 'width: 4em',
			},
			'txtCellPad': {
				'min': 0,
				'controlStyle': 'width: 4em',
			}
		}
	}
}

*/


text:
#include <camera/camera.h>
#include <camera/camera_extrinsics.h>
#include <camera/camera_intrinsics.h>
#include <geometry/eight_point_algorithm_solver.h>
#include <geometry/essential_matrix_solver.h>
#include <geometry/pose_estimator_2d3d.h>
#include <geometry/rotation.h>
#include <matching/distance_metric.h>
#include <matching/feature_matcher_options.h>
#include <matching/pairwise_image_match.h>
#include <matching/naive_matcher_2d2d.h>
#include <matching/naive_matcher_2d3d.h>
#include <math/random_generator.h>
#include <pose/pose.h>
#include <sfm/view.h>
#include <slam/landmark.h>
#include <slam/observation.h>
#include <util/types.h>

#include <Eigen/Core>
#include <gtest/gtest.h>

namespace bsfm {

using Eigen::Matrix3d;
using Eigen::Vector3d;

class TestSimpleNoiselessSfm : public ::testing::Test {
 public:
  // Clean up before and after running tests.
  TestSimpleNoiselessSfm() {
    Landmark::ResetLandmarks();
    View::ResetViews();
  }

  ~TestSimpleNoiselessSfm() {
    Landmark::ResetLandmarks();
    View::ResetViews();
  }

 protected:

  // Create a bunch of 3D points, and cameras that are able to see at least one of
  // those points. Also generate a random descriptor for each point.
  void GenerateGroundTruthPointsAndCameras() {
    points_.clear();
    descriptors_.clear();
    cameras_.clear();

    // Generate a bunch of 3D points, and then a bunch of cameras that each
    // observe some subset of the points. Run a simple incremental SfM pipeline
    // to estimate the 3D points of all cameras and images, and check that they
    // are all in the right places.
    math::RandomGenerator rng(0);

    // Generate random points in 3D, and give them each a unique descriptor.
    std::vector<Descriptor> descriptors;
    for (int ii = 0; ii < kNumPoints_; ++ii) {
      const double x = rng.DoubleUniform(-2.0, 2.0);
      const double y = rng.DoubleUniform(-2.0, 2.0);
      const double z = rng.DoubleUniform(-2.0, 2.0);
      points_.emplace_back(x, y, z);
      descriptors_.push_back(Descriptor::Random(64));
    }

    // Use the same intrinsics for all cameras.
    CameraIntrinsics intrinsics = DefaultIntrinsics();

    // Generate the first camera at identity for easy testing.
    cameras_.push_back(Camera());
    cameras_.back().SetIntrinsics(intrinsics);

    // Generate cameras such that each camera sees at least 8 points.
    while (cameras_.size() < kNumCameras_) {
      Camera camera;
      CameraExtrinsics extrinsics;
      const double x = rng.DoubleUniform(-10.0, 10.0);
      const double y = rng.DoubleUniform(-10.0, 10.0);
      const double z = rng.DoubleUniform(-10.0, 10.0);

      // Don't get too close to the 3D points.
      if ((x > -3.0 && x < 3.0) || (y > -3.0 && y < 3.0) || (z > -3.0 && z < 3.0))
        continue;

      extrinsics.SetTranslation(x, y, z);
      Vector3d euler_angles(Vector3d::Random()*D2R(20.0));
      extrinsics.Rotate(EulerAnglesToMatrix(euler_angles));
      camera.SetExtrinsics(extrinsics);
      camera.SetIntrinsics(intrinsics);

      // Make sure this camera can see at least eight 3D points.
      bool sees_at_least_eight = false;
      unsigned int count = 0;
      for (const auto& point : points_) {
        double u = 0.0, v = 0.0;
        if (camera.WorldToImage(point.X(), point.Y(), point.Z(), &u, &v)) {
          count++;
        }

        if (count == 8) {
          sees_at_least_eight = true;
          break;
        }
      }

      if (sees_at_least_eight)
        cameras_.push_back(camera);
    }

    // Set the global scale to be the distance between the first two cameras.
    global_scale_ =
        (cameras_[0].Translation() - cameras_[1].Translation()).norm();
  }

  // Simulate feature extraction from the camera at a specified index.
  void SimulateFeatureExtraction(unsigned int camera_index,
                                 std::vector<Feature>& features,
                                 std::vector<Descriptor>& descriptors) {
    features.clear();
    descriptors.clear();

    // Get this camera.
    Camera camera = cameras_[camera_index];

    // Try to project each point into the camera.
    for (size_t ii = 0; ii < points_.size(); ++ii) {
      Point3D p = points_[ii];
      double u = 0.0, v = 0.0;

      // If any points project successfully, store the projected point and its
      // corresponding descriptor as output.
      if (camera.WorldToImage(p.X(), p.Y(), p.Z(), &u, &v)) {
        features.push_back(Feature(u, v));
        descriptors.push_back(descriptors_[ii]);
      }
    }
  }

  CameraIntrinsics DefaultIntrinsics() const {
    CameraIntrinsics intrinsics;
    intrinsics.SetImageLeft(0);
    intrinsics.SetImageTop(0);
    intrinsics.SetImageWidth(kImageWidth_);
    intrinsics.SetImageHeight(kImageHeight_);
    intrinsics.SetVerticalFOV(kVerticalFov_);
    intrinsics.SetFU(intrinsics.f_v());
    intrinsics.SetCU(0.5 * kImageWidth_);
    intrinsics.SetCV(0.5 * kImageHeight_);
    intrinsics.SetK(0.0, 0.0, 0.0, 0.0, 0.0);
    return intrinsics;
  }

  int kImageWidth_ = 1920;
  int kImageHeight_ = 1080;
  int kVerticalFov_ = D2R(90.0);

  int kNumPoints_ = 100;
  int kNumCameras_ = 20;

  // The distance between the first two cameras' centers.
  double global_scale_ = 0.0;

  std::vector<Point3D> points_;
  std::vector<Descriptor> descriptors_;
  std::vector<Camera> cameras_;
};

TEST_F(TestSimpleNoiselessSfm, TestNoBundleAdjustment) {

  // Make some fake 3D points, a random descriptor for each point, and cameras
  // that are able to observe at least 1 point.
  GenerateGroundTruthPointsAndCameras();

  // Initialize using the first two cameras.
  std::vector<Feature> features1;
  std::vector<Feature> features2;
  std::vector<Descriptor> descriptors1;
  std::vector<Descriptor> descriptors2;
  SimulateFeatureExtraction(0, features1, descriptors1);
  SimulateFeatureExtraction(1, features2, descriptors2);

  // Match features between first 2 cameras.
  NaiveMatcher2D2D feature_matcher_2d2d;
  FeatureMatcherOptions matcher_options;
  matcher_options.distance_metric = "SCALED_L2";

  // Get exact feature matches so that we isolate SfM testing.
  matcher_options.min_num_feature_matches = 8;
  matcher_options.enforce_maximum_descriptor_distance = true;
  matcher_options.maximum_descriptor_distance = 1e-8;
  matcher_options.threshold_image_distance= false;
  feature_matcher_2d2d.AddImageFeatures(features1, descriptors1);
  feature_matcher_2d2d.AddImageFeatures(features2, descriptors2);
  PairwiseImageMatchList image_matches;
  ASSERT_TRUE(feature_matcher_2d2d.MatchImages(matcher_options, image_matches));
  PairwiseImageMatch image_match = image_matches[0];
  FeatureMatchList feature_matches = image_match.feature_matches_;

  // Get fundamental matrix of first 2 cameras.
  Matrix3d E, F;
  EightPointAlgorithmSolver f_solver;
  FundamentalMatrixSolverOptions solver_options;
  f_solver.SetOptions(solver_options);
  ASSERT_TRUE(f_solver.ComputeFundamentalMatrix(feature_matches, F));

  // Get essential matrix of first 2 cameras.
  CameraIntrinsics intrinsics = DefaultIntrinsics();
  EssentialMatrixSolver e_solver;
  E = e_solver.ComputeEssentialMatrix(F, intrinsics, intrinsics);

  // Get extrinsics from essential matrix.
  Pose relative_pose;
  ASSERT_TRUE(e_solver.ComputeExtrinsics(E, feature_matches, intrinsics,
                                         intrinsics, relative_pose));

  // Now we know the transformation between the first two cameras up to scale.
  Camera camera1, camera2;
  CameraExtrinsics extrinsics1, extrinsics2;
  extrinsics1.SetWorldToCamera(Pose());
  extrinsics2.SetWorldToCamera(relative_pose);
  camera1.SetExtrinsics(extrinsics1);
  camera2.SetExtrinsics(extrinsics2);
  camera1.SetIntrinsics(intrinsics);
  camera2.SetIntrinsics(intrinsics);

  // Triangulate features in 3D. This not needed in a real implementation. We
  // are doing it so that we can check if landmarks automatically triangulate
  // points.
  Point3DList initial_points;
  double uncertainty = 0.0;
  ASSERT_TRUE(Triangulate(feature_matches,
                          camera1,
                          camera2,
                          initial_points,
                          uncertainty));
  ASSERT_EQ(initial_points.size(), feature_matches.size());

  // Initialize views and landmarks.
  View::Ptr view1 = View::Create(camera1);
  View::Ptr view2 = View::Create(camera2);
  for (size_t ii = 0; ii < initial_points.size(); ++ii) {
    Landmark::Ptr landmark = Landmark::Create();

    Descriptor d1 = descriptors1[image_match.descriptor_indices1_[ii]];
    Descriptor d2 = descriptors2[image_match.descriptor_indices2_[ii]];
    ASSERT_TRUE(d1.isApprox(d2));

    // Creating observations automatically adds them to their views.
    Observation::Ptr observation1 =
        Observation::Create(view1, feature_matches[ii].feature1_, d1);
    Observation::Ptr observation2 =
        Observation::Create(view2, feature_matches[ii].feature2_, d2);

    landmark->IncorporateObservation(observation1);
    landmark->IncorporateObservation(observation2);

    // The landmark's 3D position should automatically be triangulated from the
    // observations.
    EXPECT_NEAR(initial_points[ii].X(), landmark->Position().X(), 1e-8);
    EXPECT_NEAR(initial_points[ii].Y(), landmark->Position().Y(), 1e-8);
    EXPECT_NEAR(initial_points[ii].Z(), landmark->Position().Z(), 1e-8);
  }

  // Loop over remaining cameras as if we are receiving their images
  // incrementally.
  for (int ii = 2; ii < kNumCameras_; ++ii) {
    // Get features and descriptors for the new frame.
    std::vector<Feature> features;
    std::vector<Descriptor> descriptors;
    SimulateFeatureExtraction(ii, features, descriptors);

    // Create a new view with identity camera extrinsics.
    Camera new_camera;
    new_camera.SetIntrinsics(intrinsics);
    View::Ptr new_view = View::Create(new_camera);

    // Add features and descriptors as observations to the view.
    for (size_t jj = 0; jj < features.size(); ++jj) {
      // Creating observations automatically adds them to their views.
      Observation::Create(new_view, features[jj], descriptors[jj]);
    }

    // Get a list of all existing landmarks.
    std::vector<LandmarkIndex> existing_landmarks;
    for (LandmarkIndex jj = 0; jj < Landmark::NumExistingLandmarks(); ++jj)
      existing_landmarks.push_back(jj);

    // Match features seen by this new view with existing landmarks.
    NaiveMatcher2D3D feature_matcher_2d3d;
    if (!feature_matcher_2d3d.Match(matcher_options,
                                    new_view->Index(),
                                    existing_landmarks)) {
      continue;
    }

    // Get 2D and 3D points from the match.
    FeatureList points_2d;
    Point3DList points_3d;
    for (const auto& observation : new_view->Observations()) {
      CHECK_NOTNULL(observation.get());
      if (!observation->IsMatched())
        continue;

      points_2d.push_back(observation->Feature());
      points_3d.push_back(observation->GetLandmark()->Position());
    }

    // Calculate the 3D pose of this camera.
    Pose calculated_pose;
    PoseEstimator2D3D pose_estimator;
    pose_estimator.Initialize(points_2d, points_3d, intrinsics);
    ASSERT_TRUE(pose_estimator.Solve(calculated_pose));

    // Set the extrinsic parameters of the camera in the new view.
    CameraExtrinsics extrinsics(calculated_pose);
    new_view->MutableCamera().SetExtrinsics(extrinsics);

    const Matrix3d expected_R = cameras_[ii].Rotation();
    const Matrix3d actual_R = new_view->Camera().Rotation();
    const Vector3d expected_t = cameras_[ii].Translation() / global_scale_;
    const Vector3d actual_t = new_view->Camera().Translation();

    // Did SfM work? :)
    EXPECT_TRUE(expected_R.isApprox(actual_R, 1e-8));
    EXPECT_TRUE(expected_t.isApprox(actual_t, 1e-8));
  }
}

}  //\namespace bsfm


text:
package convert

import (
	"gogs.io/gogs/internal/conf"
)

// ToCorrectPageSize makes sure page size is in allowed range.
func ToCorrectPageSize(size int) int {
	if size <= 0 {
		size = 10
	} else if size > conf.API.MaxResponseItems {
		size = conf.API.MaxResponseItems
	}
	return size
}


text:
{{ fullname }}
{{ underline }}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}
    :members:


text:
/**
 * @author  Joel Marcotte
 * @license MIT
 */

"use strict"

var piper = (function() {
    var f = {}; // Return object

    /**
     * Verifies if a value is numeric
     *
     * Source : http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
     */
    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    /**
     * Checks if `amount` is within `confidence` of `sought_amount`
     *
     * @param  {float}  sought_amount Amount we want to get close to
     * @param  {float}  amount        Amount we currently have
     * @param  {float}  percent       Percentage of confidence sought (i.e. 0.02)
     * @return {Boolean}              True if we are within this confidence level
     */
    function isWithin(sought_amount, amount, confidence) {
        return Math.abs(sought_amount - amount) <= sought_amount * confidence;
    }

    /**
     * Creates a new mortgage object
     *
     * Data should have :
     *     - loan           : Amount of the loan
     *     - interest       : Quoted interest rate (i.e. 0.03) compounded semi-annually (canadian mortgage)
     *     - amortization   : Amortization period in years
     *     - periods        : Number of periods per year (12 for monthly, 26 for bi-weekly, 52 for weekly)
     *     - extraPayment   : Amount you intend to pay on top of the payment at every
     *     - extraInterval  : Interval at which you intend to make an extra payment. i.e. (1 is for every time you make
     *                        a payment, 2 is at every 2 payments etc...)
     */
    var mortgage = function(data) {
        // Set default data for extra payments
        this.extraPayment = 0;
        this.extraInterval = 1;

        // Copy over the data and make sure they are all numeric
        for (var prop in data) {
            this[prop] = data[prop]*1;
        }

        // Compute real periodical interest
        this.computedInterest = Math.pow(Math.pow((1+(this.interest/2)),2),(1/this.periods))-1;

        // Compute the periodcal payment
        this.payment = this.getPayment();
    };

    /**
     * Returns the periodical payment of the mortgage
     */
    mortgage.prototype.getPayment = function() {
        return (this.loan * this.computedInterest) / (1- Math.pow((1+this.computedInterest), (-1 * this.amortization*this.periods)));
    };

    /**
     * Returns a mortgage iterator which can be used to fill a table or draw a graph
     * @return {[type]} [description]
     */
    mortgage.prototype.makeIterator = function() {
        var self = this;
        var iterator = {
            _period:1,

            _extra: self.extraPayment*1,

            _extraInterval: self.extraInterval*1,

            _year:1,

            _loan: self.loan,

            _payment: function() {
                return self.payment + (this._period % this._extraInterval == 0 ? this._extra : 0);
            },

            _interest_portion: function() {
                return self.computedInterest * this._loan;
            },

            _principal_portion: function() {
                return this._payment() - this._interest_portion();
            },

            hasNext: function() {
                return this._loan > 1;
            },

            next: function() {
                var it = this; // Reference to the iterator
                var result = {
                    period: it._period,
                    payment: it._payment,
                    principal: it._principal_portion(),
                    interest: it._interest_portion(),
                    loan: it._loan - it._principal_portion(),
                }
                it._loan = result.loan;
                if (this.hasNext()) {
                    it._period++;
                    if (it._period % self.periods == 0) { it._year++; }
                }
                return result;
            }
        }

        return iterator;
    }

    mortgage.prototype.getNumberOfPeriods = function() {
        // Make an iterator
        var it = this.makeIterator();
        // Make it go round and round
        while (it.hasNext()) { it.next(); }
        // Return the number of period it has gone through
        return it._period;
    };

    f.mortgage = mortgage;

    /**
     * Returns the future value based on previous value, interest and period
     * @param  {float} pv Previous Value
     * @param  {float} i  Interest (i.e. 0.03)
     * @param  {int} n  number of periods (years, months or whatever the compound period is)
     * @return {float}    Future value
     */
    f.capAccumulation = function(pv, i, n) {
        return pv * Math.pow((1+i*1), n);
    }

    /**
     * Returns the future value of a series of investments
     * with late-term annuities (payments) according to
     * FV = PMT * ((1+i)^n / i)
     * @param  {float} pmt Payment
     * @param  {float} i   Interest rate (i.e. 0.03)
     * @param  {int} n   Period (years, months or whatever the compound period is)
     * @return {float}     Future value
     */

    f.seriesAccumulation = function(pmt, i, n) {
        return pmt * (Math.pow((1+i*1), n) - 1) / i;
    }

    /**
     * Returns the future value of an investment with annual contributions
     * at the end of every period
     * @param  {float} pv  Previous Value (initial investment)
     * @param  {float} pmt Periodical contributions
     * @param  {float} i   Interest rate (0.03 for example)
     * @param  {int} n   Number of periods
     * @return {float}     Future value
     */
    f.capAndSeriesAccumulation = function(pv, pmt, i, n) {
        return this.capAccumulation(pv, i, n) + this.seriesAccumulation(pmt, i, n);
    }

    /**
     * Finds the interest rate up to 2 decimals after the period
     * that would yield the provided future value with the provided initial investment,
     * periodical contributions, and number of periods
     *
     * @param  {float} fv  Future value we are looking for
     * @param  {float} pv  Previous value (initial investment)
     * @param  {float} pmt Periodical contributions (contributed at the end of the period)
     * @param  {[type]} n  Number of periods
     * @return {float}     Interest rate (i.e. 0.0300) matching this yield
     */

    f.interestForCapAndSeriesFutureValue = function(fv, pv, pmt, n) {
        var current_fv;
        var current_interest = 0.05;
        var delta = 0.05;
        while (!isWithin(fv, current_fv, 0.0002)) {
            current_fv = this.capAndSeriesAccumulation(pv, pmt, current_interest, n)
            if ((current_fv > fv && delta > 0) ||
                (current_fv < fv && delta < 0)) {
                // Interest rate is too high and previous delta was positive
                // or interest rate is too small and previous delta was negative
                // thus we need to switch sign, and divide it by 2
                delta *= (-1/2);
            }
            current_interest += delta;
        }
        return current_interest;
    }

    return f;
})();


text:
package gov.nasa.ensemble.core.model.plan.diff.trees;

import gov.nasa.ensemble.core.model.plan.CommonMember;
import gov.nasa.ensemble.core.model.plan.EActivity;
import gov.nasa.ensemble.core.model.plan.EActivityGroup;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.temporal.TemporalMember;

import java.util.Comparator;
import java.util.Date;

import org.eclipse.emf.ecore.EObject;

public class ChronologicalOrder implements Comparator<PlanDiffNode> {

	private static Date UNDEFINED_DATE = new Date(0);

	@Override
	public int compare(PlanDiffNode arg1, PlanDiffNode arg2) {
		if (arg1 instanceof PlanDiffObjectNode && arg2 instanceof PlanDiffObjectNode)
			return compare((PlanDiffObjectNode)arg1, (PlanDiffObjectNode)arg2);
		if (arg1 instanceof PlanDiffObjectNode) return +1; // should be irrelevant
		if (arg2 instanceof PlanDiffObjectNode) return -1;
		return 0;
	}

	public int compare(PlanDiffObjectNode arg1, PlanDiffObjectNode arg2) {
		return compare(arg1.getObject(), arg2.getObject());
	}

	public int compare(EObject arg1, EObject arg2) {
		if (arg1 instanceof EPlanElement
				&& arg2 instanceof EPlanElement)
		return compare((EPlanElement)arg1, (EPlanElement)arg2);
		else return 0;
	}

	public int compare(EPlanElement arg1, EPlanElement arg2) {
		Date time1 = arg1.getMember(TemporalMember.class).getStartTime();
		Date time2 = arg2.getMember(TemporalMember.class).getStartTime();
		if (time1==null) time1 = UNDEFINED_DATE;
		if (time2==null) time2 = UNDEFINED_DATE;
		if (time1.before(time2)) return -1;
		if (time2.before(time1)) return +1;
		// Groups should be listed before their first activity, if their start times are equal.
		if (arg1 instanceof EActivityGroup && arg2 instanceof EActivity) return -1;
		if (arg1 instanceof EActivity && arg2 instanceof EActivityGroup) return +1;
		// For objects whose sort keys are equal (e.g. start time),
		// we need to produce a consistent result each time
		// to facilitate automated testing, even if the choice is arbitrary.
		return getTiebreaker(arg1).compareTo(getTiebreaker(arg2));
	}

	private String getTiebreaker(EPlanElement element) {
		String diffID = element.getMember(CommonMember.class).getDiffID();
		if (diffID==null) return "?";
		return diffID;
	}

}