text:
BinMeshTranslator::BinMeshTranslator()
{
}

void* BinMeshTranslator::creator()
{
    return new BinMeshTranslator();
}

MString BinMeshTranslator::defaultExtension() const
{
    return "binarymesh";
}

//Summary:  saves a file of a type supported by this translator by traversing
//          the all or selected objects (depending on mode) in the current
//          Maya scene, and writing a representation to the given file
//Args   :  file - object containing the pathname of the file to be written to
//          options - a string representation of any file options
//          mode - the method used to write the file - export, or export active
//                 are valid values; method will fail for any other values
//Returns:  MStatus::kSuccess if the export was successful;
//          MStatus::kFailure otherwise
MStatus BinMeshTranslator::writer(
    const MFileObject&                  file,
    const MString&                      opts,
    MPxFileTranslator::FileAccessMode   mode)
{
    mOptions = opts;
    #if defined (OSMac_)
        char nameBuffer[MAXPATHLEN];
        strcpy (nameBuffer, file.fullName().asChar());
        fileName(nameBuffer);
    #else
        mFileName = file.fullName();
    #endif

    if (MPxFileTranslator::kExportAccessMode == mode)
    {
        MGlobal::displayInfo("writer - export all.");
        return exportObjects("all");
    }

    if (MPxFileTranslator::kExportActiveAccessMode == mode)
    {
        MGlobal::displayInfo("writer - export selected.");
        return exportObjects("selected");
    }

    return MS::kSuccess;
}

MStatus BinMeshTranslator::reader(
    const MFileObject&                  file,
    const MString&                      opts,
    MPxFileTranslator::FileAccessMode   mode)
{
    mOptions = opts;
    #if defined (OSMac_)
        char nameBuffer[MAXPATHLEN];
        strcpy (nameBuffer, file.fullName().asChar());
        fileName(nameBuffer);
    #else
        mFileName = file.fullName();
    #endif

    MGlobal::displayInfo("Options " + mOptions);

    return importObjects();
}

bool BinMeshTranslator::haveWriteMethod() const
{
    return true;
}

bool BinMeshTranslator::haveReadMethod() const
{
    return true;
}

//Summary:  returns true if the translator can open and import files;
//          false if it can only import files
//Returns:  true
bool BinMeshTranslator::canBeOpened() const
{
    return true;
}

MStatus BinMeshTranslator::importObjects()
{
    MString cmd = MString("import binmeshtranslator; binmeshtranslator.binMeshTranslatorRead(");
    cmd += "'" + mFileName + "',";
    cmd += "'" + mOptions + "',";
    cmd += "'read')";

    MGlobal::displayInfo(MString("translator cmd: ") + cmd);
    return MGlobal::executePythonCommand(cmd, true);
}

//Summary:  finds and outputs all selected polygonal meshes in the DAG
//Args   :  os - an output stream to write to
//Returns:  MStatus::kSuccess if the method succeeds
//          MStatus::kFailure if the method fails
MStatus BinMeshTranslator::exportObjects(const MString& mode)
{
    MString cmd = MString("import binmeshtranslator; binmeshtranslator.binMeshTranslatorWrite(");
    cmd += "'" + mFileName + "',";
    cmd += "'" + mOptions + "',";
    cmd += "'" + mode + "')";

    MGlobal::displayInfo(MString("translator cmd: ") + cmd);
    return MGlobal::executePythonCommand(cmd, true);
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Scriban.Helpers;
using Scriban.Runtime;
using Scriban.Syntax;

namespace Scriban.Parsing
{
    /// <summary>
    /// The parser.
    /// </summary>
    public partial class Parser
    {
        private readonly Lexer _lexer;
        private readonly bool _isLiquid;
        private Lexer.Enumerator _tokenIt;
        private readonly List<Token> _tokensPreview;
        private int _tokensPreviewStart;
        private Token _previousToken;
        private Token _token;
        private bool _inCodeSection;
        private bool _isLiquidTagSection;
        private int _blockLevel;
        private bool _inFrontMatter;
        private bool _isExpressionDepthLimitReached;
        private int _expressionDepth;
        private bool _hasFatalError;
        private readonly bool _isScientific;
        private readonly bool _isKeepTrivia;
        private readonly List<ScriptTrivia> _trivias;
        private readonly Queue<ScriptStatement> _pendingStatements;
        private IScriptTerminal _lastTerminalWithTrivias;

        /// <summary>
        /// Initializes a new instance of the <see cref="Parser"/> class.
        /// </summary>
        /// <param name="lexer">The lexer.</param>
        /// <param name="options">The options.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        public Parser(Lexer lexer, ParserOptions? options = null)
        {
            _lexer = lexer ?? throw new ArgumentNullException(nameof(lexer));
            _isLiquid = _lexer.Options.Lang == ScriptLang.Liquid;
            _isScientific = _lexer.Options.Lang == ScriptLang.Scientific;
            _tokensPreview = new List<Token>(4);
            Messages = new LogMessageBag();
            _trivias = new List<ScriptTrivia>();

            Options = options ?? new ParserOptions();
            CurrentParsingMode = lexer.Options.Mode;

            _isKeepTrivia = lexer.Options.KeepTrivia;

            _pendingStatements = new Queue<ScriptStatement>(2);
            Blocks = new Stack<ScriptNode>();

            // Initialize the iterator
            _tokenIt = lexer.GetEnumerator();
            NextToken();
        }

        public readonly ParserOptions Options;
        private ScriptFrontMatter _frontmatter;

        public LogMessageBag Messages { get; private set; }

        public bool HasErrors { get; private set; }

        private Stack<ScriptNode> Blocks { get; }

        private Token Current => _token;

        private Token Previous => _previousToken;

        public SourceSpan CurrentSpan => GetSpanForToken(Current);

        private ScriptMode CurrentParsingMode { get; set; }

        public ScriptPage Run()
        {
            Messages = new LogMessageBag();
            HasErrors = false;
            _blockLevel = 0;
            _isExpressionDepthLimitReached = false;
            Blocks.Clear();

            var page = Open<ScriptPage>();
            var parsingMode = CurrentParsingMode;
            switch (parsingMode)
            {
                case ScriptMode.FrontMatterAndContent:
                case ScriptMode.FrontMatterOnly:
                    if (Current.Type != TokenType.FrontMatterMarker)
                    {
                        LogError($"When `{CurrentParsingMode}` is enabled, expecting a `{_lexer.Options.FrontMatterMarker}` at the beginning of the text instead of `{Current.GetText(_lexer.Text)}`");
                        return null;
                    }

                    _inFrontMatter = true;
                    _inCodeSection = true;

                    _frontmatter = Open<ScriptFrontMatter>();

                    // Parse the frontmatter start=-marker
                    ExpectAndParseTokenTo(_frontmatter.StartMarker, TokenType.FrontMatterMarker);

                    // Parse front-marker statements
                    _frontmatter.Statements = ParseBlockStatement(_frontmatter);

                    // We should not be in a frontmatter after parsing the statements
                    if (_inFrontMatter)
                    {
                        LogError($"End of frontmatter `{_lexer.Options.FrontMatterMarker}` not found");
                    }

                    page.FrontMatter = _frontmatter;
                    page.Span = _frontmatter.Span;

                    if (parsingMode == ScriptMode.FrontMatterOnly)
                    {
                        return page;
                    }
                    break;
                case ScriptMode.ScriptOnly:
                    _inCodeSection = true;
                    break;
            }

            page.Body = ParseBlockStatement(null);
            if (page.Body != null)
            {
                page.Span = page.Body.Span;
            }

            // Flush any pending trivias
            if (_isKeepTrivia && _lastTerminalWithTrivias != null)
            {
                FlushTriviasToLastTerminal();
            }

            if (page.FrontMatter != null)
            {
                FixRawStatementAfterFrontMatter(page);
            }

            if (_lexer.HasErrors)
            {
                foreach (var lexerError in _lexer.Errors)
                {
                    Log(lexerError);
                }
            }

            return !HasErrors ? page : null;
        }

        private void PushTokenToTrivia()
        {
            if (_isKeepTrivia)
            {
                if (Current.Type == TokenType.NewLine)
                {
                    _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.NewLine, CurrentStringSlice));
                }
                else if (Current.Type == TokenType.SemiColon)
                {
                    _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.SemiColon, CurrentStringSlice));
                }
                else if (Current.Type == TokenType.Comma)
                {
                    _trivias.Add(new ScriptTrivia(CurrentSpan, ScriptTriviaType.Comma, CurrentStringSlice));
                }
            }
        }

        private ScriptStringSlice CurrentStringSlice => GetAsStringSlice(Current);

        private ScriptStringSlice GetAsStringSlice(Token token)
        {
            return new ScriptStringSlice(_lexer.Text,  token.Start.Offset,  token.End.Offset -  token.Start.Offset + 1);
        }

        private T Open<T>(T element) where T : ScriptNode
        {
            element.Span = new SourceSpan() { FileName = _lexer.SourcePath, Start = Current.Start };
            if (_isKeepTrivia && element is IScriptTerminal terminal)
            {
                FlushTrivias(terminal, true);
            }
            return element;
        }

        private T Open<T>() where T : ScriptNode, new()
        {
            var element = new T() { Span = {FileName = _lexer.SourcePath, Start = Current.Start}};
            if (_isKeepTrivia && element is IScriptTerminal terminal)
            {
                FlushTrivias(terminal, true);
            }
            return element;
        }

        private void FlushTrivias(IScriptTerminal element, bool isBefore)
        {
            if (_isKeepTrivia && _trivias.Count > 0)
            {
                element.AddTrivias(_trivias, isBefore);
                _trivias.Clear();
            }
        }

        private T Close<T>(T node) where T : ScriptNode
        {
            node.Span.End = Previous.End;
            if (_isKeepTrivia && node is IScriptTerminal terminal)
            {
                _lastTerminalWithTrivias = terminal;
                FlushTrivias(terminal, false);
            }
            return node;
        }

        private void FlushTriviasToLastTerminal()
        {
            if (_isKeepTrivia && _lastTerminalWithTrivias != null)
            {
                FlushTrivias(_lastTerminalWithTrivias, false);
            }
        }

        private string GetAsText(Token localToken)
        {
            return localToken.GetText(_lexer.Text);
        }

        private bool MatchText(Token localToken, string text)
        {
            return localToken.Match(text, _lexer.Text);
        }

        private void NextToken()
        {
            _previousToken = _token;
            bool result;

            while (_tokensPreviewStart < _tokensPreview.Count)
            {
                _token = _tokensPreview[_tokensPreviewStart];
               _tokensPreviewStart++;

                // We can reset the tokens if we hit the upper limit of the preview
                if (_tokensPreviewStart == _tokensPreview.Count)
                {
                    _tokensPreviewStart = 0;
                    _tokensPreview.Clear();
                }

                if (IsHidden(_token.Type))
                {
                    if (_isKeepTrivia)
                    {
                        PushTrivia(_token);
                    }
                }
                else
                {
                    return;
                }

            }

            // Skip Comments
            while ((result = _tokenIt.MoveNext()))
            {
                if (IsHidden(_tokenIt.Current.Type))
                {
                    if (_isKeepTrivia)
                    {
                        PushTrivia(_tokenIt.Current);
                    }
                }
                else
                {
                    break;
                }
            }

            _token = result ? _tokenIt.Current : Token.Eof;
        }

        private void PushTrivia(Token token)
        {
            ScriptTriviaType type;
            switch (token.Type)
            {
                case TokenType.Comment:
                    type = ScriptTriviaType.Comment;
                    break;

                case TokenType.CommentMulti:
                    type = ScriptTriviaType.CommentMulti;
                    break;

                case TokenType.Whitespace:
                    type = ScriptTriviaType.Whitespace;
                    break;

                case TokenType.WhitespaceFull:
                    type = ScriptTriviaType.WhitespaceFull;
                    break;

                case TokenType.NewLine:
                    type = ScriptTriviaType.NewLine;
                    break;
                default:
                    throw new InvalidOperationException($"Token type `{token.Type}` not supported by trivia");
            }

            var trivia = new ScriptTrivia(GetSpanForToken(token), type,  GetAsStringSlice(token));
            _trivias.Add(trivia);
        }

        private Token PeekToken()
        {
            // Do we have preview token available?
            for (int i = _tokensPreviewStart; i < _tokensPreview.Count; i++)
            {
                var nextToken = _tokensPreview[i];
                if (!IsHidden(nextToken.Type))
                {
                    return nextToken;
                }
            }

            // Else try to find the first token not hidden
            while (_tokenIt.MoveNext())
            {
                var nextToken = _tokenIt.Current;
                _tokensPreview.Add(nextToken);
                if (!IsHidden(nextToken.Type))
                {
                    return nextToken;
                }
            }

            return Token.Eof;
        }

        private ScriptIdentifier ParseIdentifier()
        {
            var identifier = Open<ScriptIdentifier>();
            identifier.Value = GetAsText(Current);
            NextToken();
            return Close(identifier);
        }

        private bool IsHidden(TokenType tokenType)
        {
            return tokenType == TokenType.Comment || tokenType == TokenType.CommentMulti || tokenType == TokenType.Whitespace || tokenType == TokenType.WhitespaceFull || (tokenType == TokenType.NewLine && _allowNewLineLevel > 0);
        }

        private void LogError(string text, bool isFatal = false)
        {
            LogError(Current, text, isFatal);
        }

        private void LogError(Token tokenArg, string text, bool isFatal = false)
        {
            LogError(GetSpanForToken(tokenArg), text, isFatal);
        }

        private SourceSpan GetSpanForToken(Token tokenArg)
        {
            return new SourceSpan(_lexer.SourcePath, tokenArg.Start, tokenArg.End);
        }

        private void LogError(SourceSpan span, string text, bool isFatal = false)
        {
            Log(new LogMessage(ParserMessageType.Error, span, text), isFatal);
        }

        private void LogError(ScriptNode node, string message, bool isFatal = false)
        {
            LogError(node, node.Span, message, isFatal);
        }

        private void LogError(ScriptNode node, SourceSpan span, string message, bool isFatal = false)
        {
            var syntax = ScriptSyntaxAttribute.Get(node);
            string inMessage = " in";
            if (message.EndsWith("after"))
            {
                inMessage = string.Empty;
            }
            LogError(span, $"Error while parsing {syntax.TypeName}: {message}{inMessage}: {syntax.Example}", isFatal);
        }

        private void Log(LogMessage logMessage, bool isFatal = false)
        {
            if (logMessage == null) throw new ArgumentNullException(nameof(logMessage));
            Messages.Add(logMessage);
            if (logMessage.Type == ParserMessageType.Error)
            {
                HasErrors = true;
                if (isFatal)
                {
                    _hasFatalError = true;
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// -----------------------------------------------------------------------
// <copyright file="DynamicAllocationCampaign.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using ConfigManager;
using DataAccessLayer;
using DeliveryNetworkUtilities;
using Diagnostics;
using DynamicAllocation;
using EntityUtilities;
using Utilities.Serialization;
using daName = DynamicAllocationUtilities.DynamicAllocationEntityProperties;

namespace DynamicAllocationActivities
{
    /// Helper methods for accessing data from a dynamic allocation campaign entity.
    public class DynamicAllocationCampaign : IDynamicAllocationCampaign
    {
        /// Campaign entity id
        private readonly EntityId campaignEntityId;

        /// Company entity id
        private readonly EntityId companyEntityId;

        /// Backing field for campaign version
        private int? campaignVersion;

        /// Backing field for CompanyEntity
        private CompanyEntity companyEntityBack;

        /// Backing field for CampiagnEntity
        private CampaignEntity campaignEntityBack;

        /// Backing field for CampaignOwner
        private UserEntity campaignOwnerBack;

        /// Backing field for CampaignConfig
        private IConfig campaignConfigBack;

        /// Backing field for AllocationParameters
        private AllocationParameters allocationParametersBack;

        /// Backing field for DeliveryNetwork
        private DeliveryNetworkDesignation? deliveryNetworkBack;

        /// Backing field for AllocationHistory
        private BudgetAllocationHistory budgetAllocationHistoryBack;

        /// Backing field for RawDeliveryData
        private RawDeliveryData rawDeliveryDataBack;

        /// Initializes a new instance of the <see cref="DynamicAllocationCampaign"/> class.
        /// <param name="repository">The IEntityRepository instance to use.</param>
        /// <param name="companyEntityId">The entity id of the company entity associated with this DA campaign.</param>
        /// <param name="campaignEntityId">The entity id of the campaign entity associated with this DA campaign.</param>
        public DynamicAllocationCampaign(
            IEntityRepository repository, EntityId companyEntityId, EntityId campaignEntityId)
            : this(repository, companyEntityId, campaignEntityId, null)
        {
        }

        /// Initializes a new instance of the <see cref="DynamicAllocationCampaign"/> class.
        /// <param name="repository">The IEntityRepository instance to use.</param>
        /// <param name="companyEntityId">The entity id of the company entity associated with this DA campaign.</param>
        /// <param name="campaignEntityId">The entity id of the campaign entity associated with this DA campaign.</param>
        /// <param name="version">The version of the campaign to use.</param>
        public DynamicAllocationCampaign(
            IEntityRepository repository, EntityId companyEntityId, EntityId campaignEntityId, int? version)
        {
            this.Repository = repository;
            this.companyEntityId = companyEntityId;
            this.campaignEntityId = campaignEntityId;
            this.campaignVersion = version;
        }

        /// Initializes a new instance of the <see cref="DynamicAllocationCampaign"/> class.
        /// <param name="repository">The IEntityRepository instance to use.</param>
        /// <param name="companyEntity">The company entity associated with this DA campaign.</param>
        /// <param name="campaignEntity">The campaign entity associated with this DA campaign.</param>
        internal DynamicAllocationCampaign(
            IEntityRepository repository, CompanyEntity companyEntity, CampaignEntity campaignEntity)
            : this(repository, companyEntity, campaignEntity, null)
        {
        }

        /// Initializes a new instance of the <see cref="DynamicAllocationCampaign"/> class.
        /// <param name="repository">The IEntityRepository instance to use.</param>
        /// <param name="companyEntity">The company entity associated with this DA campaign.</param>
        /// <param name="campaignEntity">The campaign entity associated with this DA campaign.</param>
        /// <param name="campaignConfig">The campaign config instance to use.</param>
        /// <exception cref="NullReferenceException">Thrown if null entities are passed.</exception>
        internal DynamicAllocationCampaign(
            IEntityRepository repository, CompanyEntity companyEntity, CampaignEntity campaignEntity, IConfig campaignConfig)
            : this(repository, companyEntity.ExternalEntityId, campaignEntity.ExternalEntityId)
        {
            this.companyEntityBack = companyEntity;
            this.campaignEntityBack = campaignEntity;
            this.campaignConfigBack = campaignConfig;
        }

        /// Gets the company entity associated with the DA Campaign.
        public CompanyEntity CompanyEntity
        {
            get
            {
                return this.companyEntityBack ?? (this.companyEntityBack = this.GetCompanyEntity());
            }
        }

        /// Gets the campaign entity associated with the DA Campaign.
        public CampaignEntity CampaignEntity
        {
            get
            {
                return this.campaignEntityBack ?? (this.campaignEntityBack = this.GetCampaignEntity());
            }
        }

        /// Gets the user entity owner of the campaign
        public UserEntity CampaignOwner
        {
            get
            {
                return this.campaignOwnerBack ?? (this.campaignOwnerBack = this.GetCampaignOwner());
            }
        }

        /// Gets the custom config parameters for the DA Campaign.
        public IConfig CampaignConfig
        {
            get
            {
                return this.campaignConfigBack ?? (this.campaignConfigBack =
                    EntityActivityUtilities.BuildCustomConfigFromEntities(true, this.CompanyEntity, this.CampaignEntity));
            }
        }

        /// Gets the allocation parameters for the DA Campaign.
        public AllocationParameters AllocationParameters
        {
            get
            {
                return this.allocationParametersBack ?? (this.allocationParametersBack =
                    new AllocationParameters(this.CampaignConfig));
            }
        }

        /// Gets the default delivery network
        public DeliveryNetworkDesignation DeliveryNetwork
        {
            get
            {
                if (!this.deliveryNetworkBack.HasValue)
                {
                    this.deliveryNetworkBack = this.RetrieveDeliveryNetwork();
                }

                return this.deliveryNetworkBack.Value;
            }
        }

        /// Gets an object to manage BudgetAllocationHistory.
        public IBudgetAllocationHistory BudgetAllocationHistory
        {
            get
            {
                return this.budgetAllocationHistoryBack ?? (this.budgetAllocationHistoryBack =
                    new BudgetAllocationHistory(this.Repository, this.CompanyEntity, this.CampaignEntity));
            }
        }

        /// Gets an object to manage RawDeliveryData.
        public IRawDeliveryData RawDeliveryData
        {
            get
            {
                return this.rawDeliveryDataBack ?? (this.rawDeliveryDataBack =
                    new RawDeliveryData(this.Repository, this.CompanyEntity, this.CampaignEntity));
            }
        }

        /// Gets the IEntityRepository instance associated with the DA Campaign.
        internal IEntityRepository Repository { get; private set; }

        ///
        /// Create a DynamicAllocationEngine instance using measure sources, etc from the entities
        ///
        /// <returns>The created DynamicAllocationEngine instance</returns>
        public IDynamicAllocationEngine CreateDynamicAllocationEngine()
        {
            return new DynamicAllocationEngine(this.RetrieveMeasureMap());
        }

        /// Gets the AllocationNodeMap or initializes a new one if it doesn't exist
        /// <returns>The allocation node map (empty if not yet initialized).</returns>
        /// <exception cref="DataAccessEntityNotFoundException">Thrown if associated blob entity not found.</exception>
        /// <exception cref="DataAccessTypeMismatchException">Thrown if associated entity is not BlobEntity.</exception>
        public Dictionary<string, MeasureSet> RetrieveAllocationNodeMap()
        {
            var allocationNodeMap = new Dictionary<string, MeasureSet>();

            // see if there's an association to the campaign
            var allocationNodeMapBlobAssociation = this.CampaignEntity.TryGetAssociationByName(daName.AllocationNodeMap);
            if (allocationNodeMapBlobAssociation != null)
            {
                // if there's an association, get the blob
                var allocationNodeMapBlob = this.Repository.GetEntity<BlobEntity>(
                    new RequestContext { ExternalCompanyId = this.CompanyEntity.ExternalEntityId },
                    allocationNodeMapBlobAssociation.TargetEntityId);

                allocationNodeMap = allocationNodeMapBlob.DeserializeBlob<Dictionary<string, MeasureSet>>();
            }

            return allocationNodeMap;
        }

        /// Creates a measure map for the company and campaign
        /// <returns>The measure map</returns>
        /// <exception cref="ArgumentNullException">
        /// Throws if static measure providers have not been initialized in the runtime context.
        /// </exception>
        public MeasureMap RetrieveMeasureMap()
        {
            // Get the measures version
            int version = this.CampaignEntity.GetExporterVersion();

            // Get the measures sources
            var measureSources = MeasureSourceFactory.CreateMeasureSources(
                this.DeliveryNetwork,
                version,
                this.CompanyEntity,
                this.CampaignEntity,
                this.CampaignOwner);

            // Create a measure map from the sources and return it
            return new MeasureMap(measureSources);
        }

        /// Get the active budget allocation
        /// <returns>The active allocation (or null if none associated)</returns>
        public BudgetAllocation RetrieveActiveAllocation()
        {
            BudgetAllocation activeAllocation = null;

            // see if there's an association to the campaign
            var activeAllocationBlobAssociation = this.CampaignEntity.TryGetAssociationByName(daName.AllocationSetActive);
            if (activeAllocationBlobAssociation != null)
            {
                // if there's an association, get the blob
                var activeAllocationBlob = this.Repository.GetEntity<BlobEntity>(
                    new RequestContext { ExternalCompanyId = this.CompanyEntity.ExternalEntityId },
                    activeAllocationBlobAssociation.TargetEntityId);

                activeAllocation = activeAllocationBlob.DeserializeBlob<BudgetAllocation>();
            }

            return activeAllocation;
        }

        ///
        /// Build a new blob containing the the allocation and associate it to the campaign as the active allocation
        ///
        /// <param name="newActiveAllocation">The new active allocation</param>
        /// <returns>The created budget allocation blob</returns>
        public BlobEntity CreateAndAssociateActiveAllocationBlob(BudgetAllocation newActiveAllocation)
        {
            // Create a new blob containing the new active allocation
            var activeAllocationJson = AppsJsonSerializer.SerializeObject(newActiveAllocation);
            var activeAllocationBlob = BlobEntity.BuildBlobEntity(new EntityId(), activeAllocationJson);

            // Associate the new active allocation set blob with the campaign and set the initial allocations flag
            this.CampaignEntity.AssociateEntities(
                daName.AllocationSetActive,
                string.Empty,
                new HashSet<IEntity> { activeAllocationBlob },
                AssociationType.Relationship,
                true);

            // Return the created allocation blob
            return activeAllocationBlob;
        }

        ///
        /// Gets the Delivery Network of a campaign, if available, or of a company if not available.
        ///
        /// <returns>
        /// Campaign or company delivery network if available;
        /// Otherwise, DeliveryNetworkDesignation.Unknown.
        /// </returns>
        private DeliveryNetworkDesignation RetrieveDeliveryNetwork()
        {
            var deliveryNetwork = this.CampaignEntity.GetDeliveryNetwork();
            if (deliveryNetwork != DeliveryNetworkDesignation.Unknown)
            {
                LogManager.Log(
                    LogLevels.Trace,
                    "Got delivery network from campaign '{0}' ({1}): {2}",
                    this.CampaignEntity.ExternalName,
                    this.CampaignEntity.ExternalEntityId,
                    deliveryNetwork);
            }
            else
            {
                deliveryNetwork = this.CompanyEntity.GetDeliveryNetwork();
                if (deliveryNetwork != DeliveryNetworkDesignation.Unknown)
                {
                    LogManager.Log(
                        LogLevels.Trace,
                        "Got delivery network for campaign '{0}' ({1}) from company '{2}' ({3}): {4}",
                        this.CampaignEntity.ExternalName,
                        this.CampaignEntity.ExternalEntityId,
                        this.CompanyEntity.ExternalName,
                        this.CompanyEntity.ExternalEntityId,
                        deliveryNetwork);
                }
                else
                {
                    deliveryNetwork = this.GetDefaultDeliveryNetwork();
                    LogManager.Log(
                        LogLevels.Warning,
                        "Invalid/missing delivery network for campaign '{0}' ({1}) and company '{2}' ({3}). Defaulting to {4}",
                        this.CampaignEntity.ExternalName,
                        this.CampaignEntity.ExternalEntityId,
                        this.CompanyEntity.ExternalName,
                        this.CompanyEntity.ExternalEntityId,
                        deliveryNetwork);
                }
            }

            return deliveryNetwork;
        }

        /// Gets the default delivery network
        /// <returns>The default delivery network.</returns>
        private DeliveryNetworkDesignation GetDefaultDeliveryNetwork()
        {
            try
            {
                return this.CampaignConfig.GetEnumValue<DeliveryNetworkDesignation>("Delivery.DefaultNetwork");
            }
            catch (ArgumentException)
            {
                return DeliveryNetworkDesignation.Unknown;
            }
        }

        /// Get the Company Entity.
        /// <returns>A CompanyEntity.</returns>
        private CompanyEntity GetCompanyEntity()
        {
            var context = new RequestContext
            {
                ExternalCompanyId = this.companyEntityId,
                EntityFilter = new RepositoryEntityFilter(true, true, true, true)
            };

            return this.Repository.GetEntity<CompanyEntity>(context, this.companyEntityId);
        }

        /// Get the Campaign Entity.
        /// <returns>A CampaignEntity.</returns>
        private CampaignEntity GetCampaignEntity()
        {
            var context = new RequestContext
            {
                ExternalCompanyId = this.companyEntityId,
                EntityFilter = new RepositoryEntityFilter(true, true, true, true)
            };

            if (this.campaignVersion != null)
            {
                context.EntityFilter.AddVersionToEntityFilter(this.campaignVersion.Value);
            }

            return this.Repository.GetEntity<CampaignEntity>(context, this.campaignEntityId);
        }

        /// Get the campaign owner User Entity.
        /// <returns>A UserEntity.</returns>
        private UserEntity GetCampaignOwner()
        {
            var context = new RequestContext
            {
                ExternalCompanyId = this.companyEntityId,
                EntityFilter = new RepositoryEntityFilter(true, true, true, true)
            };

            return this.Repository.GetUser(context, this.CampaignEntity.GetOwnerId());
        }
    }
}


text:
using System.IO;
using Helvetica.NntpClient.Models;

namespace Helvetica.NntpClient.Interfaces
{
    public interface INntpClient
    {
        bool Authenticated { get; }
        long CurrentArticleId { get; }
        string CurrentMessageId { get; }
        Group CurrentGroup { get; }
        Article CurrentArticle { get; }
        string QuitMessage { get; }
        bool Connected { get; }
        Stream AccessStream { get; }
        void Connect();
        void Disconnect();
        bool Authenticate(string username, string password);
        bool Group(string group);
        bool Stat(long articleId);
        bool Next();
        bool Last();
        bool Quit();
        Article Article(long articleId);
        Article Article(string messageId);
        Body Body(long articleId);
        Body Body(string messageId);
        Head Head(long articleId);
        Head Head(string messageId);
        HeaderCollection Headers(string header, long articleIdStart, long articleIdEnd = 0);
        HeaderCollection Headers(string header, string messageId);
        GroupCollection List();
        T Query<T>(IQuery<T> query);
        bool Execute(ICommand command);
        void Dispose();
        void Reset();
    }
}


text:
AcceptMime
Decoratorprivate

Module
import { AcceptMime } from "@tsed/common/lib/mvc/decorators/method/acceptMime"

Source	/common/mvc/decorators/method/acceptMime.ts

### Overview

function AcceptMime(...mimes: string[]): Function;

### Description

Set a mime list as acceptable for a request on a specific endpoint.

```typescript
 @ControllerProvider('/mypath')
 provide MyCtrl {

   @Get('/')
   @AcceptMime('application/json')
   public getResource(){}
 }
```


text:
<!DOCTYPE html><html>
  <head>
    <!-- this value is replaced at build time, see gulpfile.js for more -->
    <title>%TITLE%</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="{{cache-break:/main.css}}">
    <link rel="icon" href="{{cache-break:/assets/images/favicon.ico}}">
  </head>
  <body>
    <script src="{{cache-break:/main.js}}"></script>
  </body>
</html>


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
define(["require", "exports", "./DisplayObject", "../geom/Rectangle", "../../util/Methods"], function (require, exports, DisplayObject_1, Rectangle_1, Methods) {
    var Text = (function (_super) {
        __extends(Text, _super);
        function Text(text, font, color, width, height, x, y, regX, regY) {
            if (font === void 0) { font = '10px sans-serif'; }
            if (color === void 0) { color = '#000000'; }
            if (width === void 0) { width = 1; }
            if (height === void 0) { height = 1; }
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (regX === void 0) { regX = 0; }
            if (regY === void 0) { regY = 0; }
            _super.call(this, width, height, x, y, regX, regY);
            this.isDebugMode = false;
            this._text = "";
            this.font = null;
            this.color = null;
            this.textAlign = Text.TEXT_ALIGN_LEFT;
            this.textBaseline = Text.TEXT_BASELINE_TOP;
            this.maxWidth = null;
            this.outline = 0;
            this.lineHeight = 0;
            this.lineWidth = null;
            this._autoWidth = false;
            this._autoHeight = false;
            if (text.length == 0) {
                text = " ";
            }
            this.text = text;
            this.font = font;
            this.color = color;
        }
        Object.defineProperty(Text.prototype, "text", {
            get: function () {
                return this._text;
            },
            set: function (value) {
                value = value.replace(/\s+\n|\n\s+/g, "\n");
                if (this._text != value) {
                    this._text = value;
                    if (this._autoWidth) {
                        this.setWidth('auto');
                    }
                    if (this._autoHeight) {
                        this.setHeight('auto');
                    }
                }
                this.dispatchEvent(Text.EVENT_ON_TEXT_CHANGE);
            },
            enumerable: true,
            configurable: true
        });
        Text.prototype.setWidth = function (value) {
            if (value == 'auto') {
                this._autoWidth = true;
                _super.prototype.setWidth.call(this, this.getBounds().width);
            }
            else {
                this._autoWidth = false;
                _super.prototype.setWidth.call(this, value);
            }
        };
        Text.prototype.setHeight = function (value) {
            if (value == 'auto') {
                this._autoHeight = true;
                _super.prototype.setHeight.call(this, this.getMeasuredHeight());
            }
            else {
                this._autoHeight = false;
                _super.prototype.setHeight.call(this, value);
            }
        };
        Text.prototype.isVisible = function () {
            var hasContent = this.cacheCanvas || (this.text != null && this.text !== "");
            return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent);
        };
        Text.prototype.draw = function (ctx, ignoreCache) {
            if (_super.prototype.draw.call(this, ctx, ignoreCache)) {
                return true;
            }
            var col = this.color || "#000";
            if (this.outline) {
                ctx.strokeStyle = col;
                ctx.lineWidth = this.outline * 1;
            }
            else {
                ctx.fillStyle = col;
            }
            this._drawText(this._prepContext(ctx));
            ctx.save();
            if (this.isDebugMode) {
                ctx.beginPath();
                ctx.lineWidth = 2;
                ctx.strokeStyle = '#FFF';
                ctx.rect(0, 0, this.width, this.height);
                ctx.stroke();
            }
            ctx.restore();
            return true;
        };
        Text.prototype.getMeasuredWidth = function () {
            return this._drawText(null, {}).width;
        };
        Text.prototype.getExactSize = function () {
            var width = Math.ceil(this.getMeasuredWidth());
            var height = Math.ceil(this.getMeasuredHeight() * 1.4);
            var rowHeight = Math.ceil(this._getMeasuredWidth('M') * 2);
            var cacheArguments = null;
            var color = this.color;
            this.color = '#00000';
            var y = 0;
            var x = 0;
            switch (this.textAlign) {
                case Text.TEXT_ALIGN_CENTER:
                    {
                        x = -width / 2;
                        break;
                    }
                case Text.TEXT_ALIGN_END:
                case Text.TEXT_ALIGN_RIGHT:
                    {
                        x = -width;
                        break;
                    }
            }
            switch (this.textBaseline) {
                case Text.TEXT_BASELINE_ALPHABETIC:
                    {
                        y = -rowHeight;
                        break;
                    }
                case Text.TEXT_BASELINE_BOTTOM:
                    {
                        y = -rowHeight;
                        break;
                    }
                case Text.TEXT_BASELINE_TOP:
                case Text.TEXT_BASELINE_HANGING:
                    {
                        break;
                    }
                case Text.TEXT_BASELINE_IDEOGRAPHIC:
                    {
                        y = -rowHeight;
                        break;
                    }
                case Text.TEXT_BASELINE_MIDDLE:
                    {
                        y = -rowHeight / 2;
                        break;
                    }
            }
            if (this.cacheCanvas) {
                cacheArguments = [this._cacheX, this._cacheY, this._cacheWidth, this._cacheHeight, this._cacheScale];
            }
            this.cache(x, y, width, height, 1);
            var ctx = this.cacheCanvas.getContext('2d');
            var img = ctx.getImageData(0, 0, width, height);
            if (cacheArguments) {
                this.cache.apply(this, cacheArguments);
            }
            else {
                this.uncache();
            }
            var data = img.data, x0 = width, y0 = height, x1 = 0, y1 = 0;
            for (var i = 3, l = data.length, p = 0; i < l; i += 4, ++p) {
                var px = p % width;
                var py = Math.floor(p / width);
                if (data[i - 3] > 0 ||
                    data[i - 2] > 0 ||
                    data[i - 1] > 0 ||
                    data[i] > 0) {
                    x0 = Math.min(x0, px);
                    y0 = Math.min(y0, py);
                    x1 = Math.max(x1, px);
                    y1 = Math.max(y1, py);
                }
            }
            this.color = color;
            x0 += x;
            y0 += y;
            x1 += x;
            y1 += y;
            return new Rectangle_1.default(x0, y0, x1 - x0, y1 - y0);
        };
        Text.prototype.getMeasuredLineHeight = function () {
            return this._getMeasuredWidth("M") * 1.2;
        };
        Text.prototype.getMeasuredHeight = function () {
            return this._drawText(null, {}).height;
        };
        Text.prototype.getBounds = function () {
            var rect = _super.prototype.getBounds.call(this);
            if (rect) {
                return rect;
            }
            if (this.text == null || this.text == "") {
                return null;
            }
            var o = this._drawText(null, {});
            var w = (this.maxWidth && this.maxWidth < o.width) ? this.maxWidth : o.width;
            var x = w * Text.H_OFFSETS[this.textAlign];
            var lineHeight = this.lineHeight || this.getMeasuredLineHeight();
            var y = lineHeight * Text.V_OFFSETS[this.textBaseline];
            return this._rectangle.setProperies(x, y, w, o.height);
        };
        Text.prototype.getMetrics = function () {
            var o = { lines: [] };
            o.lineHeight = this.lineHeight || this.getMeasuredLineHeight();
            o.vOffset = o.lineHeight * Text.V_OFFSETS[this.textBaseline];
            return this._drawText(null, o, o.lines);
        };
        Text.prototype.clone = function () {
            var o = new Text(this.text, this.font, this.color);
            this.cloneProps(o);
            return o;
        };
        Text.prototype.toString = function () {
            return "[Text (text=" + (this.text.length > 20 ? this.text.substr(0, 17) + "..." : this.text) + ")]";
        };
        Text.prototype.cloneProps = function (o) {
            _super.prototype.cloneProps.call(this, o);
            o.textAlign = this.textAlign;
            o.textBaseline = this.textBaseline;
            o.maxWidth = this.maxWidth;
            o.outline = this.outline;
            o.lineHeight = this.lineHeight;
            o.lineWidth = this.lineWidth;
        };
        Text.prototype._prepContext = function (ctx) {
            ctx.font = this.font;
            ctx.textAlign = this.textAlign;
            ctx.textBaseline = this.textBaseline;
            return ctx;
        };
        Text.prototype._drawText = function (ctx, o, lines) {
            var paint = !!ctx;
            if (!paint) {
                ctx = Text._workingContext;
                ctx.save();
                this._prepContext(ctx);
            }
            var lineHeight = this.lineHeight || this.getMeasuredLineHeight();
            var maxW = 0, count = 0;
            var hardLines = String(this._text).split(/(?:\r\n|\r|\n)/);
            for (var i = 0, l = hardLines.length; i < l; i++) {
                var str = hardLines[i];
                var w = null;
                if (this.lineWidth != null && (w = ctx.measureText(str).width) > this.lineWidth) {
                    var words = str.split(/(\s)/);
                    str = words[0];
                    w = ctx.measureText(str).width;
                    for (var j = 1, jl = words.length; j < jl; j += 2) {
                        var wordW = ctx.measureText(words[j] + words[j + 1]).width;
                        if (w + wordW > this.lineWidth) {
                            if (paint) {
                                this._drawTextLine(ctx, str, count * lineHeight);
                            }
                            if (lines) {
                                lines.push(str);
                            }
                            if (w > maxW) {
                                maxW = w;
                            }
                            str = words[j + 1];
                            w = ctx.measureText(str).width;
                            count++;
                        }
                        else {
                            str += words[j] + words[j + 1];
                            w += wordW;
                        }
                    }
                }
                if (paint) {
                    this._drawTextLine(ctx, str, count * lineHeight);
                }
                if (lines) {
                    lines.push(str);
                }
                if (o && w == null) {
                    w = ctx.measureText(str).width;
                }
                if (w > maxW) {
                    maxW = w;
                }
                count++;
            }
            if (o) {
                o.width = maxW;
                o.height = count * lineHeight;
            }
            if (!paint) {
                ctx.restore();
            }
            return o;
        };
        Text.prototype._drawTextLine = function (ctx, text, y) {
            if (this.outline) {
                ctx.strokeText(text, 0, y, this.maxWidth || 0xFFFF);
            }
            else {
                ctx.fillText(text, 0, y, this.maxWidth || 0xFFFF);
            }
        };
        Text.prototype._getMeasuredWidth = function (text) {
            var ctx = Text._workingContext;
            ctx.save();
            var w = this._prepContext(ctx).measureText(text).width;
            ctx.restore();
            return w;
        };
        Text.EVENT_ON_TEXT_CHANGE = 'onTextChange';
        Text.TEXT_BASELINE_TOP = 'top';
        Text.TEXT_BASELINE_HANGING = 'hanging';
        Text.TEXT_BASELINE_MIDDLE = 'middle';
        Text.TEXT_BASELINE_ALPHABETIC = 'alphabetic';
        Text.TEXT_BASELINE_IDEOGRAPHIC = 'ideographic';
        Text.TEXT_BASELINE_BOTTOM = 'bottom';
        Text.TEXT_ALIGN_START = 'start';
        Text.TEXT_ALIGN_END = 'end';
        Text.TEXT_ALIGN_LEFT = 'left';
        Text.TEXT_ALIGN_RIGHT = 'right';
        Text.TEXT_ALIGN_CENTER = 'center';
        Text.TEXT_ALIGN_BOTTOM = 'bottom';
        Text.H_OFFSETS = { start: 0, left: 0, center: -0.5, end: -1, right: -1 };
        Text.V_OFFSETS = { top: 0, hanging: -0.01, middle: -0.4, alphabetic: -0.8, ideographic: -0.85, bottom: -1 };
        return Text;
    })(DisplayObject_1.default);
    var canvas = Methods.createCanvas();
    if (canvas.getContext) {
        Text._workingContext = canvas.getContext("2d");
        canvas.width = canvas.height = 1;
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = Text;
});


text:
package software.amazon.awssdk.transfer.s3.progress;

import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.transfer.s3.Copy;
import software.amazon.awssdk.transfer.s3.Download;
import software.amazon.awssdk.transfer.s3.ObjectTransfer;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.Upload;

/**
 * {@link TransferProgress} is a stateful representation of the progress of a transfer initiated by {@link
 * S3TransferManager}. {@link TransferProgress} offers the ability to take a {@link #snapshot()} of the current progress,
 * represented by an immutable {@link TransferProgressSnapshot}, which contains helpful progress-related methods like {@link
 * TransferProgressSnapshot#bytesTransferred()} and {@link TransferProgressSnapshot#ratioTransferred()}. {@link TransferProgress}
 * is attached to {@link ObjectTransfer} objects, namely {@link Upload}, {@link Download}, and {@link Copy}.
 *

 * Where possible, it is typically recommended to avoid directly querying {@link TransferProgress} and to instead leverage
 * the {@link TransferListener} interface to receive event-driven updates of the latest {@link TransferProgressSnapshot}. See the
 * {@link TransferListener} documentation for usage instructions. However, if desired, {@link TransferProgress} can be used for
 * poll-like checking of the current progress. E.g.,
 *
{@code
 * Upload upload = tm.upload(...);
 * while (!upload.completionFuture().isDone()) {
 *     upload.progress().snapshot().ratioTransferred().ifPresent(System.out::println);
 *     Thread.sleep(1000);
 * }
 * }

 *
 * @see TransferProgressSnapshot
 * @see TransferListener
 * @see S3TransferManager
 */
@Mutable
@ThreadSafe
@SdkPublicApi
@SdkPreviewApi
public interface TransferProgress {

    /**
     * Take a snapshot of the current progress, represented by an immutable {@link TransferProgressSnapshot}.
     */
    TransferProgressSnapshot snapshot();
}


text:
package org.apache.activemq.artemis.jms.example;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.activemq.artemis.common.example.ActiveMQExample;

/**
 * A simple JMS Queue example that sends and receives message groups.
 */
public class MessageGroupExample extends ActiveMQExample
{
   private final Map<String, String> messageReceiverMap = new ConcurrentHashMap<String, String>();

   private boolean result = true;

   public static void main(final String[] args)
   {
      new MessageGroupExample().run(args);
   }

   @Override
   public boolean runExample() throws Exception
   {
      Connection connection = null;
      InitialContext initialContext = null;
      try
      {
         // Step 1. Create an initial context to perform the JNDI lookup.
         initialContext = new InitialContext();

         // Step 2. Perform a lookup on the queue
         Queue queue = (Queue)initialContext.lookup("queue/exampleQueue");

         // Step 3. Perform a lookup on the Connection Factory
         ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("ConnectionFactory");

         // Step 4. Create a JMS Connection
         connection = cf.createConnection();

         // Step 5. Create a JMS Session
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

         // Step 6. Create a JMS Message Producer
         MessageProducer producer = session.createProducer(queue);

         // Step 7. Create two consumers
         MessageConsumer consumer1 = session.createConsumer(queue);
         consumer1.setMessageListener(new SimpleMessageListener("consumer-1"));
         MessageConsumer consumer2 = session.createConsumer(queue);
         consumer2.setMessageListener(new SimpleMessageListener("consumer-2"));

         // Step 8. Create and send 10 text messages with group id 'Group-0'
         int msgCount = 10;
         TextMessage[] groupMessages = new TextMessage[msgCount];
         for (int i = 0; i < msgCount; i++)
         {
            groupMessages[i] = session.createTextMessage("Group-0 message " + i);
            groupMessages[i].setStringProperty("JMSXGroupID", "Group-0");
            producer.send(groupMessages[i]);
            System.out.println("Sent message: " + groupMessages[i].getText());
         }

         System.out.println("all messages are sent");

         // Step 9. Start the connection
         connection.start();

         Thread.sleep(2000);

         // Step 10. check the group messages are received by only one consumer
         String trueReceiver = messageReceiverMap.get(groupMessages[0].getText());
         for (TextMessage grpMsg : groupMessages)
         {
            String receiver = messageReceiverMap.get(grpMsg.getText());
            if (!trueReceiver.equals(receiver))
            {
               System.out.println("Group message [" + grpMsg.getText() + "[ went to wrong receiver: " + receiver);
               result = false;
            }
         }

         return result;
      }
      finally
      {
         // Step 11. Be sure to close our JMS resources!
         if (initialContext != null)
         {
            initialContext.close();
         }
         if (connection != null)
         {
            connection.close();
         }
      }
   }

   private class SimpleMessageListener implements MessageListener
   {
      private final String name;

      public SimpleMessageListener(final String listenerName)
      {
         name = listenerName;
      }

      public void onMessage(final Message message)
      {
         try
         {
            TextMessage msg = (TextMessage)message;
            System.out.format("Message: [%s] received by %s%n", msg.getText(), name);
            messageReceiverMap.put(msg.getText(), name);
         }
         catch (JMSException e)
         {
            e.printStackTrace();
         }
      }
   }

}


text:
{{extend "layout.html"}}
{{include response.s3.views.get("timeplot.html", "_timeplot.html")}}


text:
function die(){
    echo -e "\033[33mERROR: $1 \033[0m" > /dev/null 1>&2
    exit 1
}

#info echo
function print_info(){
    echo -n -e '\e[1;36m'
    echo -n $1
    echo -e '\e[0m'
}

##### echo
function print_xxxx(){
    xXxX="#############################"
    echo
    echo "$xXxX$xXxX$xXxX$xXxX"
    echo
}

#warn echo
function print_warn(){
    echo -n -e '\033[41;37m'
    echo -n $1
    echo -e '\033[0m'
}

#get random word 获取$1位随机文本,剔除容易识别错误的字符例如0和O等等
function get_random_word(){
    D_Num_Random="8"
    Num_Random=${1:-$D_Num_Random}
    str=`cat /dev/urandom | tr -cd abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789 | head -c $Num_Random`
    echo $str
}

#Default_Ask "what's your name?" "li" "The_name"
#echo $The_name
function Default_Ask(){
    echo
    Temp_question=$1
    Temp_default_var=$2
    Temp_var_name=$3
#rewrite $ok
    if [  -f ${CONFIG_PATH_VARS} ]; then
        New_temp_default_var=`cat $CONFIG_PATH_VARS | grep "^$Temp_var_name=" | cut -d "'" -f 2`
        Temp_default_var=${New_temp_default_var:-$Temp_default_var}
    fi
#if yes or no
    echo -e -n "\e[1;36m$Temp_question\e[0m""\033[31m(Default:$Temp_default_var)\033[0m"
    echo
    read Temp_var
    if [ "$Temp_default_var" = "y" ] || [ "$Temp_default_var" = "n" ]; then
        Temp_var=$(echo $Temp_var | sed 'y/YESNO0/yesnoo/')
        case $Temp_var in
            y|ye|yes)
                Temp_var=y
                ;;
            n|no)
                Temp_var=n
                ;;
            *)
                Temp_var=$Temp_default_var
                ;;
        esac
    else
        Temp_var=${Temp_var:-$Temp_default_var}
    fi
    Temp_cmd="$Temp_var_name='$Temp_var'"
    eval $Temp_cmd
    print_info "Your answer is : ${Temp_var}"
    echo
    print_xxxx
}

#Press any key to start 任意键开始
function press_any_key(){
    echo
    print_info "Press any key to start...or Press Ctrl+C to cancel"
    get_char_ffff(){
        SAVEDSTTY=`stty -g`
        stty -echo
        stty cbreak
        dd if=/dev/tty bs=1 count=1 2> /dev/null
        stty -raw
        stty echo
        stty $SAVEDSTTY
    }
    get_char_fffff=`get_char_ffff`
    echo
}

#fast mode
function fast_Default_Ask(){
    if [ "$fast_install" = "y" ]; then
        print_info "In the fast mode, $3 will be loaded from $CONFIG_PATH_VARS"
    else
        Default_Ask "$1" "$2" "$3"
        [ -f ${CONFIG_PATH_VARS} ] && sed -i "/^${Temp_var_name}=/d" $CONFIG_PATH_VARS
        echo $Temp_cmd >> $CONFIG_PATH_VARS
    fi
}

###################################################################################################################
#core-function                                                                                #
###################################################################################################################

#install 安装主体
function install_OpenConnect_VPN_server(){
#check system , get IP and ocversion ,del test sources 检测系统 获取本机公网ip 最新版本 去除测试源
    check_Required

#custom-configuration or not 自定义安装与否
    fast_Default_Ask "Install ocserv with Custom Configuration?(y/n)" "n" "Custom_config_ocserv"
    if [ "$Custom_config_ocserv" = "y" ]; then
        clear
        print_xxxx
        print_info "Install ocserv with custom configuration."
        print_xxxx
        get_Custom_configuration
    else
        clear
        print_xxxx
        print_info "Automatic installation,choose the plain login."
        print_xxxx
        self_signed_ca="y"
        ca_login="n"
    fi

#add a user 增加初始用户
    add_a_user

#press any key to start 任意键开始
    press_any_key

#install dependencies 安装依赖文件
    pre_install

#install ocserv 编译安装软件
    tar_ocserv_install

#make self-signd server-ca 制作服务器自签名证书
    if [ "$self_signed_ca" = "y" ]; then
    make_ocserv_ca
    fi

#make a client cert 若证书登录则制作客户端证书
    if [ "$ca_login" = "y" ] && [ "$self_signed_ca" = "y" ]; then
    ca_login_ocserv
    fi

#configuration 设定软件相关选项
    set_ocserv_conf

#stop all 关闭所有正在运行的ocserv软件
    stop_ocserv

#no certificate,no start 没有服务器证书则不启动
    if [ "$self_signed_ca" = "y" ]; then
    start_ocserv
    fi

#show result 显示结果
    show_ocserv
}

function check_Required(){
#check root
    [ $EUID -ne 0 ] && die 'Must be run by root user.'
    print_info "Root ok"
#debian-based only
    [ ! -f /etc/debian_version ] && die "Must be run on a Debian-based system."
    print_info "Debian-based ok"
#tun/tap
    [ ! -e /dev/net/tun ] && die "TUN/TAP is not available."
#only Debian 7+
    cat /etc/issue|grep -i 'debian' > /dev/null 2>&1 && {
        oc_D_V=`expr $(cat /etc/debian_version | cut -d. -f1)`
        [ $oc_D_V -lt 7 ] && die "Your system is debian $oc_D_V. Only for Debian 7+."
        [ "$oc_D_V" = "7" ] && oc_D_V="wheezy"
        [ "$oc_D_V" = "8" ] && oc_D_V="jessie"
        [ "$oc_D_V" = "9" ] && oc_D_V="stretch"
        print_info "Debian version ok"
    }
    cat /etc/issue|grep -i 'debian' > /dev/null 2>&1 || {
        print_info "Only test on ubuntu 14.04"
        oc_D_V="$(cat /etc/debian_version | cut -d/ -f1)"
    }
#check install 防止重复安装
    [ -f /usr/sbin/ocserv ] && die "Ocserv has been installed."
    print_info "Not installed ok"
#sources check,del test sources 去掉测试源
    sed 's/^[ \t]*//' /etc/apt/sources.list | grep -v '^#' | grep 'wheezy-backports' > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        oc_wheezy_backports="n"
     else
        sed -i '/wheezy-backports/d' /etc/apt/sources.list
    fi
    print_info "Sources ok"
#install base-tools
    print_info "Installing base-tools......"
    apt-get update  -qq
    apt-get install -qq -y vim sudo gawk curl nano sed insserv dnsutils
    insserv -s  > /dev/null 2>&1 || sudo ln -s /usr/lib/insserv/insserv /sbin/insserv
    print_info "Get base-tools ok"
#get info from net 从网络中获取信息
    print_info "Getting info from net......"
    get_info_from_net
    print_info "Get info ok"
    clear
}

function get_info_from_net(){
    ocserv_hostname=$(wget -qO- ipv4.icanhazip.com)
    if [ $? -ne 0 -o -z $ocserv_hostname ]; then
        ocserv_hostname=`dig +short +tcp myip.opendns.com @resolver1.opendns.com`
    fi
    OC_version_latest=$(curl -s "http://www.infradead.org/ocserv/download.html" | sed -n 's/^.*version is <b>\(.*$\)/\1/p')
}

function get_Custom_configuration(){
#Which ocserv version to install 安装哪个版本的ocserv
    fast_Default_Ask "$OC_version_latest is the latest,but default version is recommended.Which to choose?" "$Default_oc_version" "oc_version"
#whether to use the certificate login 是否证书登录,默认为用户名密码登录
    fast_Default_Ask "Whether to choose the certificate login?(y/n)" "n" "ca_login"
#whether to generate a Self-signed CA 是否需要制作自签名证书
    fast_Default_Ask "Generate a Self-signed CA for your server?(y/n)" "y" "self_signed_ca"
    if [ "$self_signed_ca" = "n" ]; then
        Default_Ask "Input your own domain for ocserv." "$ocserv_hostname" "fqdnname"
    else
#get CA's name
        fast_Default_Ask "Your CA's name?" "ocvpn" "caname"
#get Organization name
        fast_Default_Ask "Your Organization name?" "ocvpn" "ogname"
#get Company name
        fast_Default_Ask "Your Company name?" "ocvpn" "coname"
#get server's FQDN
        Default_Ask "Your server's domain?" "$ocserv_hostname" "fqdnname"
    fi
#set max router rulers 最大路由规则限制数目
    fast_Default_Ask "The maximum number of routing table rules?" "200" "max_router"
#which port to use for verification 选择验证端口
    fast_Default_Ask "Which port to use for verification?(Tcp-Port)" "999" "ocserv_tcpport_set"
#tcp-port only or not 是否仅仅使用tcp端口,即是否禁用udp
    fast_Default_Ask "Only use tcp-port or not?(y/n)" "n" "only_tcp_port"
#which port to use for data transmission 选择udp端口 即专用数据传输的udp端口
    if [ "$only_tcp_port" = "n" ]; then
        fast_Default_Ask "Which port to use for data transmission?(Udp-Port)" "1999" "ocserv_udpport_set"
    fi
#boot from the start 是否开机自起
    fast_Default_Ask "Start ocserv when system is started?(y/n)" "y" "ocserv_boot_start"
#Save user vars or not 是否保存脚本参数 以便于下次快速配置
    fast_Default_Ask "Save the vars for fast mode or not?" "n" "save_user_vars"
}

#add a user 增加一个初始用户
function add_a_user(){
#get username,4 figures default
    if [ "$ca_login" = "n" ]; then
        Default_Ask "Input your username for ocserv." "$(get_random_word 4)" "username"
#get password,6 figures default
        Default_Ask "Input your password for ocserv." "$(get_random_word 6)" "password"
    fi
#get password,if ca login,4 figures default
    if [ "$ca_login" = "y" ] && [ "$self_signed_ca" = "y" ]; then
        Default_Ask "Input your password for your p12-cert file." "$(get_random_word 4)" "password"
#get expiration days for client p12-cert 获取客户端证书到期天数
        Default_Ask "Input the number of expiration days for your p12-cert file." "7777" "oc_ex_days"
    fi
}

#dependencies onebyone
function Dependencies_install_onebyone(){
    for OC_DP in $oc_dependencies
    do
        print_info "Installing $OC_DP "
        DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $TEST_S $OC_DP
        if [ $? -eq 0 ]; then
            print_info "[ ${OC_DP} ] ok!"
            apt-get clean
        else
            print_warn "[ ${OC_DP} ] not be installed!"
        fi
    done
}

#lz4 from github
function tar_lz4_install(){
    print_info "Installing lz4 from github"
    DEBIAN_FRONTEND=noninteractive apt-get -y -qq remove --purge liblz4-dev
    apt-get autoremove -qq -y && apt-get clean
    mkdir lz4
    LZ4_VERSION=`curl "https://github.com/Cyan4973/lz4/releases/latest" | sed -n 's/^.*tag\/\(.*\)".*/\1/p'`
    curl -SL "https://github.com/Cyan4973/lz4/archive/$LZ4_VERSION.tar.gz" -o lz4.tar.gz
    tar -xf lz4.tar.gz -C lz4 --strip-components=1
    rm lz4.tar.gz
    cd lz4
    make -j"$(nproc)" && make install
    cd ..
    rm -r lz4
    if [ `getconf WORD_BIT` = '32' ] && [ `getconf LONG_BIT` = '64' ]; then
        ln -sf /usr/local/lib/liblz4.* /usr/lib/x86_64-linux-gnu/
    else
        ln -sf /usr/local/lib/liblz4.* /usr/lib/i386-linux-gnu/
    fi
    print_info "[ lz4 ] ok"
}

#install freeradius-client 1.1.7
function tar_freeradius_client_install(){
    print_info "Installing freeradius-client-1.1.7"
    wget -c ftp://ftp.freeradius.org/pub/freeradius/freeradius-client-1.1.7.tar.gz
    tar -zxf freeradius-client-1.1.7.tar.gz
    cd freeradius-client-1.1.7
    ./configure --prefix=/usr --sysconfdir=/etc
    make -j"$(nproc)" && make install
    cd ..
    rm -rf freeradius-client*
    print_info "[ freeradius-client ] ok"
}

#install dependencies 安装依赖文件
function pre_install(){
#keep kernel 防止某些情况下内核升级
    echo linux-image-`uname -r` hold | sudo dpkg --set-selections > /dev/null 2>&1
    apt-get upgrade -y
    echo linux-image-`uname -r` install | sudo dpkg --set-selections > /dev/null 2>&1
#no upgrade from test sources 不升级不安装测试源其他包
    [ ! -d /etc/apt/preferences.d ] && mkdir /etc/apt/preferences.d
    [ ! -d /etc/apt/apt.conf.d ] && mkdir /etc/apt/apt.conf.d
    cat > /etc/apt/preferences.d/my_ocserv_preferences<<'EOF'
Package: *
Pin: release wheezy
Pin-Priority: 900
Package: *
Pin: release wheezy-backports
Pin-Priority: 90
Package: *
EOF
    cat > /etc/apt/apt.conf.d/77ocserv<<'EOF'
APT::Install-Recommends "false";
APT::Install-Suggests "false";
APT::Get::Install-Recommends "false";
APT::Get::Install-Suggests "false";
EOF
#sources check @ check Required 源检测在前面 for ubuntu+3
    [ "$oc_D_V" = "wheezy" ] || oc_u_dependencies="libgnutls28-dev libseccomp-dev libhttp-parser-dev"
    oc_dependencies="build-essential pkg-config make gcc m4 gnutls-bin libgmp3-dev libwrap0-dev libpam0g-dev libdbus-1-dev libnl-route-3-dev libopts25-dev libnl-nf-3-dev libreadline-dev libpcl1-dev autogen libtalloc-dev $oc_u_dependencies"
    TEST_S=""
    Dependencies_install_onebyone
#add test source
    echo "deb http://ftp.debian.org/debian wheezy-backports main contrib non-free" >> /etc/apt/sources.list
#install dependencies from wheezy-backports
    [ "$oc_D_V" = "wheezy" ] && {
        oc_dependencies="libgnutls28-dev libseccomp-dev" && TEST_S="-t wheezy-backports -f --force-yes"
        apt-get update
        Dependencies_install_onebyone
    }
#install freeradius-client-1.1.7
    tar_freeradius_client_install
#install dependencies lz4  增加lz4压缩必须包
#libprotobuf-c-dev libhttp-parser-dev
#lz4
    tar_lz4_install
#if sources del 如果本来没有测试源便删除
    [ "$oc_wheezy_backports" = "n" ] && sed -i '/wheezy-backports/d' /etc/apt/sources.list
#keep update
    rm -f /etc/apt/preferences.d/my_ocserv_preferences
    rm -f /etc/apt/apt.conf.d/77ocserv
    [ "$oc_D_V" = "wheezy" ] && apt-get update
    print_info "Dependencies  ok"
}

#install 编译安装
function tar_ocserv_install(){
    cd ${Script_Dir}
#default max route rulers
    max_router=${max_router:-200}
#default version  默认版本
    oc_version=${oc_version:-${Default_oc_version}}
    wget -c ftp://ftp.infradead.org/pub/ocserv/ocserv-$oc_version.tar.xz
    tar xvf ocserv-$oc_version.tar.xz
    rm -rf ocserv-$oc_version.tar.xz
    cd ocserv-$oc_version
#have to use "" then $ work ,set router limit 设定路由规则最大限制
    sed -i "s|\(#define MAX_CONFIG_ENTRIES \).*|\1$max_router|" src/vpn.h
    ./configure --prefix=/usr --sysconfdir=/etc 2>${Script_Dir}/ocerror.log
    make -j"$(nproc)" 2>>${Script_Dir}/ocerror.log
    make install
#check install 检测编译安装是否成功
    [ ! -f /usr/sbin/ocserv ] && {
        make clean
        die "Ocserv install failure,check ${Script_Dir}/ocerror.log"
    }
#mv files
    rm -f ${Script_Dir}/ocerror.log
    mkdir -p /etc/ocserv/CAforOC/revoke > /dev/null 2>&1
    mkdir /etc/ocserv/{config-per-group,defaults} > /dev/null 2>&1
    cp doc/profile.xml /etc/ocserv
    sed -i "s|localhost|$ocserv_hostname|" /etc/ocserv/profile.xml
    cd ..
    rm -rf ocserv-$oc_version
#get or set config file
    cd /etc/ocserv
    cat > /etc/init.d/ocserv <<'EOF'
#!/bin/sh
### BEGIN INIT INFO
# Provides:          ocserv
# Required-Start:    $network $local_fs $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO
# Copyright Rene Mayrhofer, Gibraltar, 1999
# This script is distibuted under the GPL

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/sbin/ocserv
PIDFILE=/var/run/ocserv.pid
DAEMON_ARGS="-c /etc/ocserv/ocserv.conf"

# Exit if the package is not installed
[ -x $DAEMON ] || exit 0

case "$1" in
start)
if [ ! -r $PIDFILE ]; then
echo -n "Starting OpenConnect VPN Server Daemon: "
. /etc/ocserv/start-ocserv-sysctl.sh
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
$DAEMON_ARGS > /dev/null
echo "[ok]"
else
echo -n "OpenConnect VPN Server is already running.\n\r"
exit 0
fi
;;
stop)
echo -n "Stopping OpenConnect VPN Server Daemon: "
. /etc/ocserv/stop-ocserv-sysctl.sh
start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON
echo "[ok]"
rm -f $PIDFILE
;;
force-reload|restart)
echo "Restarting OpenConnect VPN Server: "
$0 stop
sleep 3
$0 start
;;
status)
if [ ! -r $PIDFILE ]; then
echo "no pid file, process doesn't seem to be running correctly"
exit 3
fi
PID=`cat $PIDFILE | sed 's/ //g'`
EXE=/proc/$PID/exe
if [ -x "$EXE" ] &&
[ "`ls -l \"$EXE\" | cut -d'>' -f2,2 | cut -d' ' -f2,2`" = \
"$DAEMON" ]; then
echo "ok, process seems to be running"
exit 0
elif [ -r $PIDFILE ]; then
echo "process not running, but pidfile exists"
exit 1
else
echo "no lock file to check for, so simply return the stopped status"
exit 3
fi
;;
*)
echo "Usage: /etc/init.d/ocserv {start|stop|restart|force-reload|status}"
exit 1
;;
esac

:
EOF
    chmod 755 /etc/init.d/ocserv
    cat > start-ocserv-sysctl.sh <<'EOF'
#!/bin/bash

#vars
OCSERV_CONFIG="/etc/ocserv/ocserv.conf"

# turn on IP forwarding
#sysctl -w net.ipv6.conf.all.forwarding=1 > /dev/null 2>&1
sysctl -w net.ipv4.ip_forward=1 > /dev/null 2>&1

#get gateway and profiles
gw_intf_oc=`ip route show|sed -n 's/^default.* dev \([^ ]*\).*/\1/p'`
ocserv_tcpport=`sed -n 's/^tcp-.*=[ \t]*//p' $OCSERV_CONFIG`
ocserv_udpport=`sed -n 's/^udp-.*=[ \t]*//p' $OCSERV_CONFIG`
ocserv_ip4_work_mask=`sed -n 's/^ipv4-.*=[ \t]*//p' $OCSERV_CONFIG|sed 'N;s|\n|/|g'`

# turn on NAT over default gateway and VPN
if !(iptables-save -t nat | grep -q "$gw_intf_oc (ocserv)"); then
iptables -t nat -A POSTROUTING -s $ocserv_ip4_work_mask -o $gw_intf_oc -m comment --comment "$gw_intf_oc (ocserv)" -j MASQUERADE
fi

if !(iptables-save -t filter | grep -q "$gw_intf_oc (ocserv2)"); then
iptables -A FORWARD -s $ocserv_ip4_work_mask -m comment --comment "$gw_intf_oc (ocserv2)" -j ACCEPT
fi

if !(iptables-save -t filter | grep -q "$gw_intf_oc (ocserv3)"); then
iptables -A INPUT -p tcp --dport $ocserv_tcpport -m comment --comment "$gw_intf_oc (ocserv3)" -j ACCEPT
fi

if [ "$ocserv_udpport" != "" ]; then
    if !(iptables-save -t filter | grep -q "$gw_intf_oc (ocserv4)"); then
        iptables -A INPUT -p udp --dport $ocserv_udpport -m comment --comment "$gw_intf_oc (ocserv4)" -j ACCEPT
    fi
fi

if !(iptables-save -t filter | grep -q "$gw_intf_oc (ocserv5)"); then
iptables -A FORWARD  -m state --state RELATED,ESTABLISHED -m comment --comment "$gw_intf_oc (ocserv5)" -j ACCEPT
fi

# turn on MSS fix
# MSS = MTU - TCP header - IP header
if !(iptables-save -t mangle | grep -q "$gw_intf_oc (ocserv6)"); then
iptables -t mangle -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "$gw_intf_oc (ocserv6)" -j TCPMSS --clamp-mss-to-pmtu
fi

echo "..."
EOF
    chmod +x start-ocserv-sysctl.sh
    cat > stop-ocserv-sysctl.sh <<'EOF'
#!/bin/bash

# uncomment if you want to turn off IP forwarding
# sysctl -w net.ipv4.ip_forward=0

#del iptables

iptables-save | grep 'ocserv' | sed 's/^-A P/iptables -t nat -D P/' | sed 's/^-A FORWARD -p/iptables -t mangle -D FORWARD -p/' | sed 's/^-A/iptables -D/' | bash

echo "..."
EOF
    chmod +x stop-ocserv-sysctl.sh
    while [ ! -f ocserv.conf ]; do
        wget -c $OC_CONF_NET_DOC/ocserv.conf --no-check-certificate
    done
    while [ ! -f config-per-group/Route ]; do
        wget -c $OC_CONF_NET_DOC/routerulers -O config-per-group/Route --no-check-certificate
    done
    if [ ! -f dh.pem ]; then
        print_info "Perhaps generate DH parameters will take some time , please wait..."
        certtool --generate-dh-params --sec-param high --outfile dh.pem
    fi
    clear
    print_info "Ocserv install ok"

}

function make_ocserv_ca(){
    print_info "Generating Self-signed CA..."
#all in one doc
    cd /etc/ocserv/CAforOC
#Self-signed CA set
#ca's name#organization name#company name#server's FQDN
    caname=${caname:-ocvpn}
    ogname=${ogname:-ocvpn}
    coname=${coname:-ocvpn}
    fqdnname=${fqdnname:-$ocserv_hostname}
#generating the CA 制作自签证书授权中心
    certtool --generate-privkey --outfile ca-key.pem
    cat << _EOF_ > ca.tmpl
cn = "$caname"
organization = "$ogname"
serial = 1
expiration_days = 7777
ca
signing_key
cert_signing_key
crl_signing_key
_EOF_
    certtool --generate-self-signed --load-privkey ca-key.pem --template ca.tmpl --outfile ca-cert.pem
#generating a local server key-certificate pair 通过自签证书授权中心制作服务器的私钥与证书
    certtool --generate-privkey --outfile server-key.pem
    cat << _EOF_ > server.tmpl
cn = "$fqdnname"
organization = "$coname"
serial = 2
expiration_days = 7777
signing_key
encryption_key
tls_www_server
_EOF_
    certtool --generate-certificate --load-privkey server-key.pem --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem --template server.tmpl --outfile server-cert.pem
    [ ! -f server-cert.pem ] && die "server-cert.pem NOT Found , make failure!"
    [ ! -f server-key.pem ] && die "server-key.pem NOT Found , make failure!"
    cp server-cert.pem /etc/ocserv && cp server-key.pem /etc/ocserv
    cp ca-cert.pem /etc/ocserv
    print_info "Self-signed CA for ocserv ok"
}

function ca_login_ocserv(){
#make a client cert
    print_info "Generating a client cert..."
    cd /etc/ocserv/CAforOC
    caname=`cat ca.tmpl | grep cn | cut -d '"' -f 2`
    if [ "X${caname}" = "X" ]; then
        Default_Ask "Tell me your CA's name." "ocvpn" "caname"
    fi
    name_user_ca=$(get_random_word 4)
    while [ -d user-${name_user_ca} ]; do
        name_user_ca=$(get_random_word 4)
    done
    mkdir user-${name_user_ca}
    oc_ex_days=${oc_ex_days:-7777}
    cat << _EOF_ > user-${name_user_ca}/user.tmpl
cn = "user-${name_user_ca}"
unit = "Route"
expiration_days = ${oc_ex_days}
signing_key
tls_www_client
_EOF_
#user key
    certtool --generate-privkey --outfile user-${name_user_ca}/user-${name_user_ca}-key.pem
#user cert
    certtool --generate-certificate --load-privkey user-${name_user_ca}/user-${name_user_ca}-key.pem --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem --template user-${name_user_ca}/user.tmpl --outfile user-${name_user_ca}/user-${name_user_ca}-cert.pem
#p12
    openssl pkcs12 -export -inkey user-${name_user_ca}/user-${name_user_ca}-key.pem -in user-${name_user_ca}/user-${name_user_ca}-cert.pem -name "user-${name_user_ca}" -certfile ca-cert.pem -caname "$caname" -out user-${name_user_ca}/user-${name_user_ca}.p12 -passout pass:$password
#cp to ${Script_Dir}
    cp user-${name_user_ca}/user-${name_user_ca}.p12 ${Script_Dir}
#make a empty revocation list
    if [ ! -f crl.tmpl ];then
    cat << _EOF_ >crl.tmpl
crl_next_update = 7777
crl_number = 1
_EOF_
    certtool --generate-crl --load-ca-privkey ca-key.pem --load-ca-certificate ca-cert.pem --template crl.tmpl --outfile ../crl.pem
    fi
    print_info "Generate client cert ok"
}

#set 设定相关参数
function set_ocserv_conf(){
#default vars
    ocserv_tcpport_set=${ocserv_tcpport_set:-999}
    ocserv_udpport_set=${ocserv_udpport_set:-1999}
    save_user_vars=${save_user_vars:-n}
    ocserv_boot_start=${ocserv_boot_start:-y}
    only_tcp_port=${only_tcp_port:-n}
#set port
    sed -i "s|\(tcp-port = \).*|\1$ocserv_tcpport_set|" /etc/ocserv/ocserv.conf
    sed -i "s|\(udp-port = \).*|\1$ocserv_udpport_set|" /etc/ocserv/ocserv.conf
#default domain compression dh.pem
    sed -i "s|^[# \t]*\(default-domain = \).*|\1$fqdnname|" /etc/ocserv/ocserv.conf
    sed -i "s|^[# \t]*\(compression = \).*|\1true|" /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(dh-params = \).*|\1/etc/ocserv/dh.pem|' /etc/ocserv/ocserv.conf
#2-group 增加组 bug 证书登录无法正常使用Default组
    [ "$open_two_group" = "y" ] && two_group_set
    echo "route = 0.0.0.0/128.0.0.0" > /etc/ocserv/defaults/group.conf
    echo "route = 128.0.0.0/128.0.0.0" >> /etc/ocserv/defaults/group.conf
    echo "route = 0.0.0.0/128.0.0.0" > /etc/ocserv/config-per-group/All
    echo "route = 128.0.0.0/128.0.0.0" >> /etc/ocserv/config-per-group/All
#boot from the start 开机自启
    [ "$ocserv_boot_start" = "y" ] && sudo insserv ocserv > /dev/null 2>&1
#add a user 增加一个初始用户
    [ "$ca_login" = "n" ] && plain_login_set
#set only tcp-port 仅仅使用tcp端口
    [ "$only_tcp_port" = "y" ] && sed -i 's|^[ \t]*\(udp-port = \)|#\1|' /etc/ocserv/ocserv.conf
#set ca_login
    if [ "$ca_login" = "y" ]; then
        sed -i 's|^[ \t]*\(auth = "plain\)|#\1|' /etc/ocserv/ocserv.conf
        sed -i 's|^[# \t]*\(auth = "certificate"\)|\1|' /etc/ocserv/ocserv.conf
        ca_login_set
    fi
#save custom-configuration files or not
    [ "$save_user_vars" = "n" ] && rm -f $CONFIG_PATH_VARS
    print_info "Set ocserv ok"
}

function two_group_set(){
    sed -i 's|^[# \t]*\(cert-group-oid = \).*|\12.5.4.11|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(select-group = \)group1.*|\1Route|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(select-group = \)group2.*|\1All|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(default-select-group = \).*|\1Default|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(auto-select-group = \).*|\1false|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(config-per-group = \).*|\1/etc/ocserv/config-per-group|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(default-group-config = \).*|\1/etc/ocserv/defaults/group.conf|' /etc/ocserv/ocserv.conf
}

function plain_login_set(){
    [ "$open_two_group" = "y" ] && group_name='-g "Route,All"'
    (echo "$password"; sleep 1; echo "$password") | ocpasswd -c /etc/ocserv/ocpasswd $group_name $username
}

function ca_login_set(){
    sed -i 's|^[# \t]*\(ca-cert = \).*|\1/etc/ocserv/ca-cert.pem|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(crl = \).*|\1/etc/ocserv/crl.pem|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(cert-user-oid = \).*|\12.5.4.3|' /etc/ocserv/ocserv.conf
}

function stop_ocserv(){
#stop all
    /etc/init.d/ocserv stop
    oc_pid=`pidof ocserv`
    if [ ! -z "$oc_pid" ]; then
        for pid in $oc_pid
        do
            kill -9 $pid > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                echo "Ocserv process[$pid] has been killed"
            fi
        done
    fi
}

function start_ocserv(){
    [ ! -f /etc/ocserv/server-cert.pem ] && die "server-cert.pem NOT Found !!!"
    [ ! -f /etc/ocserv/server-key.pem ] && die "server-key.pem NOT Found !!!"
#start
    /etc/init.d/ocserv start
}

function show_ocserv(){
    ocserv_port=`sed -n 's/^[ \t]*tcp-port[ \t]*=[ \t]*//p' /etc/ocserv/ocserv.conf`
    clear
    ps cax | grep ocserv > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        if [ "$ca_login" = "y" ]; then
            echo ""
            echo -e "\033[41;37m Your server domain is \033[0m" "$fqdnname:$ocserv_port"
            echo -e "\033[41;37m Your p12-cert's password is \033[0m" "$password"
            echo -e "\033[41;37m Your p12-cert's number of expiration days is \033[0m" "$oc_ex_days"
            print_warn "You could get user-${name_user_ca}.p12 from ${Script_Dir}."
            print_warn "You could stop ocserv by ' /etc/init.d/ocserv stop '!"
            print_warn "Boot from the start or not, use ' sudo insserv ocserv ' or ' sudo insserv -r ocserv '."
            echo ""
            print_info "Enjoy it!"
            echo ""
        else
            echo ""
            echo -e "\033[41;37m Your server domain is \033[0m" "$fqdnname:$ocserv_port"
            echo -e "\033[41;37m Your username is \033[0m" "$username"
            echo -e "\033[41;37m Your password is \033[0m" "$password"
            print_warn "You could use ' sudo ocpasswd -c /etc/ocserv/ocpasswd username ' to add users. "
            print_warn "You could stop ocserv by ' /etc/init.d/ocserv stop '!"
            print_warn "Boot from the start or not, use ' sudo insserv ocserv ' or ' sudo insserv -r ocserv '."
            echo ""
            print_info "Enjoy it!"
            echo ""
        fi
    elif [ "$self_signed_ca" = "n" -a "$ca_login" = "n" ]; then
        print_warn "1,You should change Server Certificate and Server Key's name to server-cert.pem and server-key.pem !!!"
        print_warn "2,You should put them to /etc/ocserv !!!"
        print_warn "3,You should start ocserv by ' /etc/init.d/ocserv start '!"
        print_warn "4,You could use ' sudo ocpasswd -c /etc/ocserv/ocpasswd username ' to add users."
        print_warn "5,Boot from the start or not, use ' sudo insserv ocserv ' or ' sudo insserv -r ocserv '."
        echo -e "\033[41;37m Your username is \033[0m" "$username"
        echo -e "\033[41;37m Your password is \033[0m" "$password"
    elif [ "$self_signed_ca" = "n" -a "$ca_login" = "y" ]; then
        print_warn "1,You should change your Server Certificate and Server Key's name to server-cert.pem and server-key.pem !!!"
        print_warn "2,You should change your Certificate Authority Certificates and Certificate Authority Key's  name to ca-cert.pem and ca-key.pem!!!"
        print_warn "3,You should put server-cert.pem server-key.pem and ca-cert.pem to /etc/ocserv !!!"
        print_warn "4,You should put ca-cert.pem and ca-key.pem to /etc/ocserv/CAforOC !!!"
        print_warn "5,You should use ' bash `basename $0` gc ' to get a client cert !!!"
        print_warn "6,You could start ocserv by ' /etc/init.d/ocserv start '!"
        print_warn "7,Boot from the start or not, use ' sudo insserv ocserv ' or ' sudo insserv -r ocserv '."
    else
        print_warn "Ocserv start failure,ocserv is offline!"
    fi
}

function check_ca_cert(){
    [ ! -f /usr/sbin/ocserv ] && die "Ocserv NOT Found !!!"
    [ ! -f /etc/ocserv/CAforOC/ca-cert.pem ] && die "ca-cert.pem NOT Found !!!"
    [ ! -f /etc/ocserv/CAforOC/ca-key.pem ] && die "ca-key.pem NOT Found !!!"
}

function get_new_userca(){
    check_ca_cert
    ca_login="y"
    self_signed_ca="y"
    add_a_user
    press_any_key
    ca_login_ocserv
    clear
}

function get_new_userca_show(){
    echo
    echo -e "\033[41;37m Your p12-cert's password is \033[0m" "$password"
    echo -e "\033[41;37m Your p12-cert's number of expiration days is \033[0m" "$oc_ex_days"
    print_warn " You could get user-${name_user_ca}.p12 from ${Script_Dir}."
    print_warn " You should import the certificate to your device at first."
    echo
    print_info "Enjoy it"
}

function Outdate_Autoclean(){
    My_All_Ca=`ls -F|sed -n 's/\(user-.*\)\//\1/p'|sed ':a;N;s/\n/ /;ba;'`
    for My_One_Ca in $My_All_Ca
    do
        Client_EX_Days=`sed -n 's/.*days = //p' $My_One_Ca/user.tmpl`
        Client_Ifsign_Date=`expr $(date +%Y%m%d -d "-$Client_EX_Days day")`
        Client_Truesign_Date=`expr $(date -r $My_One_Ca/user.tmpl +%Y%m%d)`
        if [ $Client_Truesign_Date -lt $Client_Ifsign_Date ]; then
            mv $My_One_Ca -t revoke/
        fi
    done
}

function revoke_userca(){
    check_ca_cert
#get info
    cd /etc/ocserv/CAforOC
    Outdate_Autoclean
    clear
    print_xxxx
    print_info "The following is the user list..."
    echo
    ls -F|grep /|grep user|cut -d/ -f1
    print_xxxx
    print_info "Which user do you want to revoke?"
    echo
    read -p "Which: " -e -i user- revoke_ca
    if [ ! -f /etc/ocserv/CAforOC/$revoke_ca/$revoke_ca-cert.pem ]
    then
        die "$revoke_ca NOT Found !!!"
    fi
    echo
    print_warn "Okay,${revoke_ca} will be revoked."
    print_xxxx
    press_any_key
#revoke
    cat ${revoke_ca}/${revoke_ca}-cert.pem >>revoked.pem
    certtool --generate-crl --load-ca-privkey ca-key.pem --load-ca-certificate ca-cert.pem --load-certificate revoked.pem --template crl.tmpl --outfile ../crl.pem
#show
    mv ${revoke_ca} revoke/
    print_info "${revoke_ca} was revoked."
    echo
}

function reinstall_ocserv(){
    stop_ocserv
    rm -rf /etc/ocserv
    rm -rf /usr/sbin/ocserv
    rm -rf /etc/init.d/ocserv
    install_OpenConnect_VPN_server
}

function upgrade_ocserv(){
    get_info_from_net
    Default_Ask "The latest is ${OC_version_latest}.Input the version you want to upgrade?" "$OC_version_latest" "oc_version"
    Default_Ask "The maximum number of routing table rules?" "200" "max_router"
    press_any_key
    stop_ocserv
    rm -f /etc/ocserv/profile.xml
    rm -f /usr/sbin/ocserv
    tar_ocserv_install
    start_ocserv
    ps cax | grep ocserv > /dev/null 2>&1
    if [ $? -eq 0 ]; then
    print_info "Your ocserv upgrade was successful!"
    else
    print_warn "Ocserv start failure,ocserv is offline!"
    print_info "You could use ' bash `basename $0` ri' to forcibly upgrade your ocserv."
    fi
}

function enable_both_login_open_ca(){
    get_new_userca
    sed -i 's|^[# \t]*\(enable-auth = certificate\)|\1|' /etc/ocserv/ocserv.conf
    ca_login_set
    stop_ocserv
    start_ocserv
    clear
    echo
    print_info "The plain login and the certificate login are Okay~"
    print_info "The following is your certificate login info~"
    get_new_userca_show
}

function enable_both_login_open_plain(){
    ca_login="n"
    add_a_user
    press_any_key
    plain_login_set
    sed -i 's|^[ \t]*\(auth = "certificate"\)|#\1|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(auth = "plain\)|\1|' /etc/ocserv/ocserv.conf
    sed -i 's|^[# \t]*\(enable-auth = certificate\)|\1|' /etc/ocserv/ocserv.conf
    stop_ocserv
    start_ocserv
    clear
    echo
    print_info "The plain login and the certificate login are Okay~"
    print_info "The following is your plain login info~"
    echo
    echo -e "\033[41;37m Your username is \033[0m" "$username"
    echo -e "\033[41;37m Your password is \033[0m" "$password"
    echo
    print_info "Enjoy it"
}

function help_ocservauto(){
    print_xxxx
    print_info "######################## Parameter Description ####################################"
    echo
    print_info " install ----------------------- Install ocserv for Debian 7+"
    echo
    print_info " fastmode or fm ---------------- Rapid installation for ocserv through $CONFIG_PATH_VARS"
    echo
    print_info " getuserca or gc --------------- Get a new client certificate"
    echo
    print_info " revokeuserca or rc ------------ Revoke a client certificate"
    echo
    print_info " upgrade or ug ----------------- Smoothly upgrade your ocserv"
    echo
    print_info " reinstall or ri --------------- Force to reinstall your ocserv(Destroy All Data)"
    echo
    print_info " pc ---------------------------- At the same time,enable the plain login and the certificate login"
    echo
    print_info " help or h --------------------- Show this description"
    print_xxxx
}
###################################################################################################################
#main                                                                                #
###################################################################################################################

#install info
clear
echo "==============================================================================================="
echo
print_info " System Required:  Debian 7+"
echo
print_info " Description:  Install OpenConnect VPN server"
echo
print_info " Help Info:  bash `basename $0` help"
echo
echo "==============================================================================================="

#脚本所在文件夹
Script_Dir="$(cd "$(dirname $0)"; pwd)"
#fastmode vars 存放配置参数文件的绝对路径,快速安装模式可用
CONFIG_PATH_VARS="${Script_Dir}/vars_ocservauto"
#ocserv配置文件所在的网络文件夹位置,请勿轻易改变
OC_CONF_NET_DOC="https://raw.githubusercontent.com/fanyueciyuan/eazy-for-ss/master/ocservauto"
#推荐的默认版本
Default_oc_version="0.10.2"
open_two_group="n"

#Initialization step
action=$1
[  -z $1 ] && action=install
case "$action" in
install)
    install_OpenConnect_VPN_server
    ;;
fastmode | fm)
    fast_install="y"
    [ ! -f $CONFIG_PATH_VARS ] && die "$CONFIG_PATH_VARS Not Found !"
    . $CONFIG_PATH_VARS
    install_OpenConnect_VPN_server
    ;;
getuserca | gc)
    get_new_userca
    get_new_userca_show
    ;;
revokeuserca | rc)
    revoke_userca
    ;;
upgrade | ug)
    upgrade_ocserv
    ;;
reinstall | ri)
    reinstall_ocserv
    ;;
pc)
    [  -f /etc/ocserv/crl.pem ] && enable_both_login_open_plain
    [ ! -f /etc/ocserv/crl.pem ] && enable_both_login_open_ca
    ;;
help | h)
    help_ocservauto
    ;;
*)
    clear
    print_warn "Arguments error! [ ${action} ]"
    print_warn "Usage:  bash `basename $0` {install|fm|gc|rc|ug|ri|pc|help}"
    help_ocservauto
    ;;
esac


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// For later use.
/// <summary>
/// Boundary Class require the System.Serializable to be accessible within the project.
/// Don't need to know how to do this just use it.
/// </summary>
[System.Serializable]
public class Boundary
{
	public float xMin, xMax, zMin, zMax;
}

public class UserMovement : MonoBehaviour {

	public float speed;

	public Boundary boundary;

	private Rigidbody rb;

	void Start () {
		rb = GetComponent<Rigidbody> ();
	}

	/* 	Update is called before rendering a frame.
	 *
	 *
	 *
	 *
	 * Game code goes here.
	*/

	void Update () {

	}
	/* FixedUpdate is called before physics calculations
	 *
	 *
	 *
	 *
	 * and is where our movement code goes.
	*/

	void FixedUpdate () {
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		// Gets the calculation of movement.
		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

		// This moves us.
		rb.velocity = movement * speed;

		// This constrains the movement at the edges of the map.
		// <Rigidbody>.position teleports the player object to defined coordinates.
		rb.position = new Vector3
			(
				Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
				0.0f,
				Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
			);

	}
}


text:
<?php

/**
 * Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
 *
 * @phpstub
 *
 * @return float
 */
function stats_rand_ranf()
{
}


text:
/*-- Stack.h ---------------------------------------------------------------
 This header file defines a Stack data type.
 Basic operations:
 constructor:  Constructs an empty stack
 empty:        Checks if a stack is empty
 push:         Modifies a stack by adding a value at the top
 top:          Retrieves the top stack value; leaves stack unchanged
 pop:          Modifies stack by removing the value at the top
 display:      Displays all the stack elements

 Class Invariant:
 1. The stack elements (if any) are stored in positions
    0, 1, . . ., myTop of myArray.
 2. -1 <= myTop < STACK_CAPACITY
 --------------------------------------------------------------------------*/

#include <iostream>

#ifndef STACK
#define STACK

const int STACK_CAPACITY = 1024;
typedef int StackElement;

class Stack
{
public:
	/***** Function Members *****/
	/***** Constructor *****/
	Stack();
	/*------------------------------------------------------------------------
	 Construct a Stack object.

	 Precondition:  None.
	 Postcondition: An empty Stack object has been constructed (myTop is
	     initialized to -1 and myArray is an array with STACK_CAPACITY
	     elements of type StackElement).
	 -----------------------------------------------------------------------*/

	bool empty() const;
	/*------------------------------------------------------------------------
	 Check if stack is empty.
	 Precondition: None
	 Postcondition: Returns true if stack is empty and false otherwise.
	 -----------------------------------------------------------------------*/

	void push(const StackElement& value);
	/*------------------------------------------------------------------------
	 Add a value to a stack.

	 Precondition:  value is to be added to this stack
	 Postcondition: value is added at top of stack provided there is space;
	     otherwise, a stack-full message is displayed and execution is
	     terminated.
	 -----------------------------------------------------------------------*/

	void display(std::ostream& out) const;
	/*------------------------------------------------------------------------
	 Display values stored in the stack.

	 Precondition:  ostream out is open.
	 Postcondition: Stack's contents, from top down, have been output to out.
	 -----------------------------------------------------------------------*/

	StackElement top() const;
	/*------------------------------------------------------------------------
	 Retrieve value at top of stack (if any).

	 Precondition:  Stack is nonempty
	 Postcondition: Value at top of stack is returned, unless the stack is
	     empty; in that case, an error message is displayed and a "garbage
	     value" is returned.
	 -----------------------------------------------------------------------*/

	void pop();
	/*------------------------------------------------------------------------
	 Remove value at top of stack (if any).

	 Precondition:  Stack is nonempty.
	 Postcondition: Value at top of stack has been removed, unless the stack
	     is empty; in that case, an error message is displayed and
	     execution allowed to proceed.
	 -----------------------------------------------------------------------*/

private:
	/***** Data Members *****/
	StackElement myArray[STACK_CAPACITY];
	int myTop;
}; // end of class declaration

#endif