text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.AliasAmbiguousType;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AliasAmbiguousType
{
    public class AliasAmbiguousTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
    {
        internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
            => (null, new CSharpAliasAmbiguousTypeCodeFixProvider());

        protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
            => FlattenActions(actions);

        private string GetAmbiguousDefinition(string typeDefinion)
            => $@"
namespace N1
{{
    { typeDefinion }
}}
namespace N2
{{
    { typeDefinion }
}}";

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassObjectCreationUsingsInNamespace()
        {
            var classDef = GetAmbiguousDefinition("public class Ambiguous { }");
            var initialMarkup = classDef + @"
namespace Test
{
    using N1;
    using N2;
    class C
    {
        void M()
        {
            var a = new [|Ambiguous|]();
        }
    }
}";
            var expectedMarkup0 = classDef + @"
namespace Test
{
    using N1;
    using N2;
    using Ambiguous = N1.Ambiguous;

    class C
    {
        void M()
        {
            var a = new Ambiguous();
        }
    }
}";
            var expectedMarkup1 = classDef + @"
namespace Test
{
    using N1;
    using N2;
    using Ambiguous = N2.Ambiguous;

    class C
    {
        void M()
        {
            var a = new Ambiguous();
        }
    }
}";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup0, index: 0);
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup1, index: 1);
            await TestSmartTagTextAsync(initialMarkup, "using Ambiguous = N1.Ambiguous;", index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassObjectCreationUsingsInCompilationUnit()
        {
            var classDef = GetAmbiguousDefinition("public class Ambiguous { }");
            await TestInRegularAndScriptAsync(@"
using N1;
using N2;
" + classDef + @"
namespace Test
{
    class C
    {
        void M()
        {
            var a = new [|Ambiguous|]();
        }
    }
}", @"
using N1;
using N2;
using Ambiguous = N1.Ambiguous;
" + classDef + @"
namespace Test
{
    class C
    {
        void M()
        {
            var a = new Ambiguous();
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassObjectCreationGenericsDontOfferDiagnostic()
        {
            var genericAmbiguousClassDefinition = GetAmbiguousDefinition("public class Ambiguous<T> { }");
            await TestMissingAsync(@"
using N1;
using N2;
" + genericAmbiguousClassDefinition + @"
namespace Test
{
    class C
    {
        void M()
        {
            var a = new [|Ambiguous<int>|]();
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousAttribute()
        {
            var classDef = GetAmbiguousDefinition("public class AmbiguousAttribute: System.Attribute { }");
            await TestInRegularAndScriptAsync(@"
using N1;
using N2;
" + classDef + @"
namespace Test
{
    [[|Ambiguous|]]
    class C
    {
    }
}", @"
using N1;
using N2;
using AmbiguousAttribute = N1.AmbiguousAttribute;
" + classDef + @"
namespace Test
{
    [Ambiguous]
    class C
    {
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestNamespaceAndTypenameIdenticalOffersNoDiagnostics()
        {
            // This gives CS0433: The type 'Ambiguous' exists in both 'Assembly1' and 'Assembly2'
            // Couldn't get a CS0104 in this situation. Keep the test anyway if someone finds a way to force CS0104 here
            // or CS0433 is added as a supported diagnostic for this fix.
            await TestMissingAsync(@"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document FilePath=""File1.cs"">
namespace N
{
    public class Ambiguous { }
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
        <Document FilePath=""File2.cs"">
namespace N
{
    public class Ambiguous { }
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Test"" CommonReferences=""true"">
        <ProjectReference Alias=""A1"">Assembly1</ProjectReference>
        <ProjectReference Alias=""A2"">Assembly2</ProjectReference>
        <Document FilePath=""File3.cs"">
extern alias A1;
extern alias A2;
using A1::N;
using A2::N;
namespace N1
{
    public class C
    {
        void M()
        {
            var a = new [|Ambiguous|]();
        }
    }
}
        </Document>
    </Project>
</Workspace>
");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousAliasNoDiagnostics()
        {
            await TestMissingAsync(@"
extern alias alias;
using alias=alias;
class myClass : [|alias|]::Uri
    {
    }
");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousNestedClass()
        {
            var initialMarkup = @"
using static Static<string>;
using static Static<int>;

public static class Static<T>
{
    public class Nested
    {
        public void M() { }
    }
}

class D
{
    static void Main(string[] args)
    {
        var c = new [|Nested|]();
        c.M();
    }
}";
            var expectedMarkup0 = @"
using static Static<string>;
using static Static<int>;
using Nested = Static<string>.Nested;

public static class Static<T>
{
    public class Nested
    {
        public void M() { }
    }
}

class D
{
    static void Main(string[] args)
    {
        var c = new Nested();
        c.M();
    }
}";
            var expectedMarkup1 = @"
using static Static<string>;
using static Static<int>;
using Nested = Static<int>.Nested;

public static class Static<T>
{
    public class Nested
    {
        public void M() { }
    }
}

class D
{
    static void Main(string[] args)
    {
        var c = new Nested();
        c.M();
    }
}";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup0, index: 0);
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup1, index: 1);
            await TestSmartTagTextAsync(initialMarkup, "using Nested = Static<string>.Nested;", index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtBaseList()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
" + classDef + @"
namespace NTest
{
    public class Test : [|AmbiguousClass|] { }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test : AmbiguousClass { }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtTypeConstraint()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
" + classDef + @"
namespace NTest
{
    public class Test<T> where T : [|AmbiguousClass|] { }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test<T> where T : AmbiguousClass { }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousEnumDiagnosedAtFieldDeclaration()
        {
            var enumDef = GetAmbiguousDefinition(@"public enum AmbiguousEnum { }");
            var initialMarkup = @"
using N1;
using N2;
" + enumDef + @"
namespace NTest
{
    public class Test
    {
        private [|AmbiguousEnum|] _AmbiguousEnum;
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousEnum = N1.AmbiguousEnum;
" + enumDef + @"
namespace NTest
{
    public class Test
    {
        private AmbiguousEnum _AmbiguousEnum;
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousStructDiagnosedAtPropertyDeclaration()
        {
            var strcutDef = GetAmbiguousDefinition(@"public struct AmbiguousStruct { }");
            var initialMarkup = @"
using N1;
using N2;
" + strcutDef + @"
namespace NTest
{
    public class Test
    {
        public [|AmbiguousStruct|] AmbiguousStruct { get; }
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousStruct = N1.AmbiguousStruct;
" + strcutDef + @"
namespace NTest
{
    public class Test
    {
        public AmbiguousStruct AmbiguousStruct { get; }
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtTypeArgument()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            var list = new System.Collections.Generic.List<[|AmbiguousClass|]> { new AmbiguousClass() };
        }
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            var list = new System.Collections.Generic.List<AmbiguousClass> { new AmbiguousClass() };
        }
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtIdentifierOfIncompleteExpression()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            [|AmbiguousClass|]
        }
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            AmbiguousClass
        }
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtMethodParameter()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M([|AmbiguousClass|] a)
        {
        }
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M(AmbiguousClass a)
        {
        }
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAliasAmbiguousType)]
        public async Task TestAmbiguousClassDiagnosedAtFromClauseTypeIdentifier()
        {
            var classDef = GetAmbiguousDefinition(@"public class AmbiguousClass { }");
            var initialMarkup = @"
using N1;
using N2;
using System.Linq;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            var qry = from [|AmbiguousClass|] a in new object[] { }
                      select a;
        }
    }
}
";
            var expectedMarkup = @"
using N1;
using N2;
using System.Linq;
using AmbiguousClass = N1.AmbiguousClass;
" + classDef + @"
namespace NTest
{
    public class Test
    {
        public void M()
        {
            var qry = from AmbiguousClass a in new object[] { }
                      select a;
        }
    }
}
";
            await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup);
        }
    }
}


text:
package io.github.vastframework.pubsub.protocol;

import io.github.vastframework.codecs.Codec;

public interface DataTypeCodecProvider {

  Codec getCodec(String dataType);

}

redpajama_set_name: RedPajamaGithub


text:
package com.lmax.disruptor.dsl;

import com.lmax.disruptor.EventProcessor;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.dsl.stubs.SleepingEventHandler;
import com.lmax.disruptor.support.TestEvent;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

public class ConsumerRepositoryTest
{
    private final Mockery mockery = new Mockery();

    private ConsumerRepository<TestEvent> consumerRepository;
    private EventProcessor eventProcessor1;
    private EventProcessor eventProcessor2;
    private SleepingEventHandler handler1;
    private SleepingEventHandler handler2;
    private SequenceBarrier barrier1;
    private SequenceBarrier barrier2;

    @Before
    public void setUp() throws Exception
    {
        consumerRepository = new ConsumerRepository<TestEvent>();
        eventProcessor1 = mockery.mock(EventProcessor.class, "eventProcessor1");
        eventProcessor2 = mockery.mock(EventProcessor.class, "eventProcessor2");

        final Sequence sequence1 = new Sequence();
        final Sequence sequence2 = new Sequence();
        mockery.checking(new Expectations()
        {
            {
                allowing(eventProcessor1).getSequence();
                will(returnValue(sequence1));

                allowing(eventProcessor1).isRunning();
                will(returnValue(true));

                allowing(eventProcessor2).getSequence();
                will(returnValue(sequence2));

                allowing(eventProcessor2).isRunning();
                will(returnValue(true));
            }
        });
        handler1 = new SleepingEventHandler();
        handler2 = new SleepingEventHandler();

        barrier1 = mockery.mock(SequenceBarrier.class, "barrier1");
        barrier2 = mockery.mock(SequenceBarrier.class, "barrier2");
    }

    @Test
    public void shouldGetBarrierByHandler() throws Exception
    {
        consumerRepository.add(eventProcessor1, handler1, barrier1);

        assertThat(consumerRepository.getBarrierFor(handler1), sameInstance(barrier1));
    }

    @Test
    public void shouldReturnNullForBarrierWhenHandlerIsNotRegistered() throws Exception
    {
        assertThat(consumerRepository.getBarrierFor(handler1), is(nullValue()));
    }

    @Test
    public void shouldGetLastEventProcessorsInChain() throws Exception
    {
        consumerRepository.add(eventProcessor1, handler1, barrier1);
        consumerRepository.add(eventProcessor2, handler2, barrier2);

        consumerRepository.unMarkEventProcessorsAsEndOfChain(eventProcessor2.getSequence());

        final Sequence[] lastEventProcessorsInChain = consumerRepository.getLastSequenceInChain(true);
        assertThat(lastEventProcessorsInChain.length, equalTo(1));
        assertThat(lastEventProcessorsInChain[0], sameInstance(eventProcessor1.getSequence()));
    }

    @Test
    public void shouldRetrieveEventProcessorForHandler() throws Exception
    {
        consumerRepository.add(eventProcessor1, handler1, barrier1);

        assertThat(consumerRepository.getEventProcessorFor(handler1), sameInstance(eventProcessor1));
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenHandlerIsNotRegistered() throws Exception
    {
        consumerRepository.getEventProcessorFor(new SleepingEventHandler());
    }

    @Test
    public void shouldIterateAllEventProcessors() throws Exception
    {
        consumerRepository.add(eventProcessor1, handler1, barrier1);
        consumerRepository.add(eventProcessor2, handler2, barrier2);

        boolean seen1 = false;
        boolean seen2 = false;
        for (ConsumerInfo testEntryEventProcessorInfo : consumerRepository)
        {
            final EventProcessorInfo eventProcessorInfo = (EventProcessorInfo) testEntryEventProcessorInfo;
            if (!seen1 && eventProcessorInfo.getEventProcessor() == eventProcessor1 &&
                eventProcessorInfo.getHandler() == handler1)
            {
                seen1 = true;
            }
            else if (!seen2 && eventProcessorInfo.getEventProcessor() == eventProcessor2 &&
                     eventProcessorInfo.getHandler() == handler2)
            {
                seen2 = true;
            }
            else
            {
                fail("Unexpected eventProcessor info: " + testEntryEventProcessorInfo);
            }
        }

        assertTrue("Included eventProcessor 1", seen1);
        assertTrue("Included eventProcessor 2", seen2);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>hvs2</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="hvs1.html" title="hvs1" />
    <link rel="next" href="hvs3.html" title="hvs3" />

          hvs2

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          hvs2

hvs2 —
      Synthèse Hyper Vectorielle (SHV) à deux dimensions contrôlée par des variables
      de taux-k mises à jour en externe.

Description

      hvs2 permet la synthèse Hyper Vectorielle (SHV) à deux
      dimensions contrôlée par des variables de taux-k mises à jour en externe.

Syntaxe

hvs2 kx, ky, inumParms, inumPointsX, inumPointsY, iOutTab, iPositionsTab, iSnapTab [, iConfigTab]

Initialisation

      inumParms - nombre de paramètres contrôlés par la SHV.
      Chaque instantané de la SHV est composé de inumParms
      éléments.

      inumPointsX, inumPointsY - nombre
      de points dont est composée chaque dimension du cube de la SHV (ou du carré
      dans le cas de la SHV à deux dimensions, ou du segment de droite dans le
      cas de la SHV à une dimension).

      iOutTab - numéro de la table recevant l'ensemble des
      valeurs instantanées des paramètres de sortie de la SHV. Le nombre total de
      paramètres est défini par l'argument inumParms.

      iPositionsTab – une table remplie avec les positions
      individuelles des instantanés dans la matrice de SHV (voir ci-dessous pour
      plur d'information).

      iSnapTab – une table remplie avec tous les instantanés.
      Chaque instantané se compose d'un ensemble de valeurs des paramètres. Le
      nombre d'éléments contenus dans chaque instantané est spécifié par l'argument
      inumParms. L'ensemble des éléments de chaque instantané
      suit (et est adjacent à) l'instantané précédent dans la table. Ainsi la
      taille totale de cette table doit être >= à inumParms
      multiplié par le nombre d'instantanés que l'on veut mémoriser pour la SVH.

      iConfigTab – (facultatif) une table contenant le
      comportement de la SHV pour chaque paramètre. Si iConfigTab
      vaut zéro (par défaut), cet argument est ignoré, ce qui signifie que chaque
      paramètre est interpolé linéairement par la SHV. Si iConfigTab
      est différent de zéro, il doit faire référence à une table existante dont
      le contenu fait référence à son tour à un genre particulier d'interpolation.
      Dans cette table, une valeur de -1 indique que le paramètre correspondant
      reste inchangé (ignoré) par la SHV ; une valeur de zéro indique que le
      paramètre correspondant est traité par interpolation linéaire ; tout autre
      valeur doit être un nombre entier indiquant une table existante remplie
      avec une forme qui détermine le genre d'interpolation spéciale à utiliser
      (interpolation basée sur une table).

Exécution

      kx, ky - ce sont des variables modifiées de l'extérieur,
      qui contrôlent le mouvement du pointeur dans la matrice cubique de SHV
      (ou carrée ou en ligne dans le cas où les matrices de SHV ont moins de
      3 dimensions). Les valeurs de ces arguments d'entrée doivent être comprises
      entre 0 et 1.

      La Synthèse Hyper Vectorielle est une technique qui permet de contrôler un
      ensemble immense de paramètres en utilisant une approche simple et globale.
      Les concepts clé de la SHV sont :

      L'ensemble des paramètres de SHV, dont le nombre est fixé et défini par
      l'argument inumParms. Durant l'exécution de la SHV,
      tous ces paramètres sont variables et peuvent être appliqués à n'importe
      quelle technique de synthèse sonore, de même qu'à n'importe quel contrôle
      global de composition algorithmique ou de tout autre niveau. L'utilisateur
      doit définir au préalable plusieurs ensembles de valeurs fixes pour chaque
      paramètre de la SHV, chaque ensemble correspondant à une configuration de
      synthèse déterminée. Chaque ensemble de valeurs est appelé un instantané et
      peut être considéré comme les coordonnées d'un saut dans un espace
      multi-dimensionnel. La SHV consiste à faire évoluer un point dans cet
      espace multi-dimensionnel (en utilisant un pointeur de mouvement spécial,
      voie ci-dessous), selon les points et les limites définis par les instantanés.
      On peut fixer le nombre de paramètres de la SHV (chaque paramètre suivant
      une dimension de l'espace multi-dimensionnel), même un nombre très important,
      la limite ne dépendant que de la puissance de calcul (et de la mémoire) de
      votre ordinateur et de la complexité de la synthèse sonore utilisée.

      Le cube de SHV (ou le carré ou le segment). C'est la matrice (à 3, 2 ou 1
      dimensions, en fonction de l'opcode hvs utilisé) des
      points d'appui ou pivots de la SHV. Le nombre total de points pivots dépend
      de la valeur des arguments inumPointsX,
      inumPointsY et inumPointsZ. Dans
      le cas d'une matrice de SHV à 3 dimensions on peut définir, par exemple, 3
      points pour la dimension X, 5 pour la dimension Y et 2 pour la dimension Z.
      Dans ce cas le nombre total de points pivots est 3 * 5 * 2 = 30. Avec cet
      ensemble de points pivots, le cube est divisé en zones cubiques plus petites,
      chacune étant délimitée par huit points. Chaque point est numéroté. La
      numérotation de ces points se fait de la manière suivante : numéro zéro pour
      le premier point, numéro un pour le second, et ainsi de suite. En supposant
      que l'on utilise un cube de SHV à 3 dimensions ayant le nombre de points
      mentionné ci-dessus (c'est-à-dire 3, 5 et 2 respectivement pour les axes
      X, Y et Z), le premier point (point zéro) est le coin supérieur gauche de
      la face avant du cube, si l'on regarde le plan XY du cube. Le second point
      est le centre de l'arête supérieure de la face avant du cube, ainsi de suite.
      On peut se référer à la figure ci-dessous pour comprendre comment la
      numérotation des points pivots est réalisée :

      Pour la SHV à 2 dimensions, c'est la même chose, en omettant seulement la
      face arrière du cube, si bien que chaque zone est délimitée par 4 points
      pivots au lieu de 8. Pour la SHV à 1 dimension, tout devient plus simple
      car il n'y a qu'un segment de droite sur lequel les points pivots sont
      répartis de gauche à droite. Chaque point est couplé à un instantané.

      L'ordre des instantanés, comme il est stocké dans la table iSnapTab,
      peut suivre ou pas l'ordre des numéros des points pivots. En fait il est
      possible de modifier cet ordre avec la table iPositionsTab,
      qui repositionne chaque instantané en fonction des points pivots. La table
      iPositionsTab est constituée des positions des instantanés
      (contenus dans la table iSnapTab) sur la grille à deux
      dimensions. Chaque élément successif est un pointeur représentant la position
      dans la table iSnapTab. Par exemple, dans une matrice
      de SHV à 2 dimensions comme la suivante (ayant dans ce cas
      inumPointsX = 3 et inumPointsY = 5) :

            Tableau 10.

              <colgroup>
                <col />
                <col />
                <col />
              </colgroup>

                  5
                  7
                  1

                  3
                  4
                  9

                  6
                  2
                  0

                  4
                  1
                  3

                  8
                  2
                  7

      Ces numéros (à stocker dans la table iSnapTab en utilisant,
      par exemple, le générateur de fonction GEN02), représentent
      la position des instantanés dans la grille (dans ce cas une matrice 3x5).
      Ainsi, le premier élément 5 a l'indice zéro et représente le sixième
      (l'élément zéro est le premier) instantané contenu dans la table
      iSnapTab, le second élément 7 représente le huitième
      élément de iSnapTab, ainsi de suite. En résumé, les
      sommets de chaque zone (une zone cubique est délimitée par 8 sommets, une
      zone carrée par 4 sommets et une zone linéaire par 2 points) sont liés à
      un instantané donné, dont le numéro est transformé par la table
      iSnapTab.

      Les valeurs de sortie de la SHV sont influencées par le mouvement du pointeur,
      un point dont la position dans le cube de SHV (ou le carré ou le segment)
      est déterminée par les arguments kx, ky
      et kz. Les valeurs de ces arguments, qui doivent être
      comprises entre 0 et 1, sont fixées extérieurement par l'utilisateur. Les
      valeurs de sortie, dont le nombre est égal à l'argument inumParms,
      sont stockée dans la table iOutTab, laquelle doit avoir
      été allouée auparavant par l'utilisateur et doit avoir une taille d'au moins
      inumParms. De quelle manière le mouvement du pointeur
      influence-t-il la sortie ? Lorsque le pointeur tombe dans une zone cubique
      déterminée, délimitée par exemple par 8 sommets (ou points pivots), nous
      supposons que chaque sommet est associé à un instantané différent (c'est-à-dire
      un ensemble de inumParms valeurs), la sortie sera la
      moyenne pondérée des 8 sommets, calculée en fonction de la distance du
      pointeur à chacun des 8 sommets. Dans le comportement par défaut, lorsque
      l'argument iConfigTab n'est pas défini, la sortie
      exacte est calculée en utilisant une interpolation linéaire qui est appliquée
      à chaque paramètre de la SHV. Cependant, il est possible de modifier ce
      comportement en donnant à l'argument iConfigTab le
      numéro d'une table dont le contenu peut affecter un ou plusieurs paramètres
      de la SHV. Les éléments de la table iConfigTab sont
      associés à chaque paramètre de SHV et leurs valeurs affectent la sortie de
      la SHV de la manière suivante :

            Si iConfigTab vaut -1, la sortie correspondante
            est ignorée, c'est-à-dire que l'élément n'est pas calculé, laissant
            la valeur de l'élément correspondant dans la table
            iOutTab inchangée ;

            Si iConfigTab est égal à zéro, la sortie de la
            SHV normale est calculée (en utilisant la moyenne pondérée des sommets
            les plus proches de la zone dans laquelle le pointeur mobile est
            tombé) ;

            Si iConfigTab est égal à un nombre entier >
            zéro, le contenu d'une table ayant ce numéro est utilisé comme la
            forme d'une interpolation basée sur cette table.

Exemples

      Voici un exemple de l'opcode hvs2. Il utilise le fichier
      hvs2.csd.

            Exemple 398. Exemple de l'opcode hvs2.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
; Audio out   Audio in    No messages
-odac           -iadc     -d     ;;;RT audio I/O
</CsOptions>
<CsInstruments>
sr=44100
ksmps=100
nchnls=2
0dbfs = 1
ginumLinesX init	4
ginumLinesY init	4
ginumParms	init	3
giOutTab	ftgen	5,0,8, -2,      0
giPosTab	ftgen	6,0,32, -2,     3,2,1,0,4,5,6,7,8,9,10, 11, 15, 14, 13, 12
giSnapTab	ftgen	8,0,64, -2,     1,1,1,   2,0,0,  3,2,0,  2,2,2,  5,2,1,  2,3,4,  6,1,7,    0,0,0, \
                              1,3,5,   3,4,4,  1,5,8,  1,1,5,  4,3,2,  3,4,5,  7,6,5,    7,8,9
tb0_init	giOutTab
        FLpanel	"Prova HVS2",600,400,10,100,0
gk1,    gk2,   ih1, ih2  FLjoy   "HVS controller XY", 0,    1,     1,     0,     0,     0,     -1,     -1,     300,    300,     0, 50
; *ihandle,                      *numlinesX,   *numlinesY, *iwidth, *iheight, *ix, *iy,*image;
gihandle	FLhvsBox	ginumLinesX,   ginumLinesY,  300,   300,      300,  50, 1
        FLpanel_end
        FLrun

	instr	1
; Smooth control signals to avoid clicks
kx portk gk1, 0.02
ky portk gk2, 0.02
;              kx,  ky,  inumParms,  inumlinesX,  inumlinesY,  iOutTab,  iPosTab,  iSnapTab [, iConfigTab]
        hvs2  kx, ky, ginumParms, ginumLinesX, ginumLinesY, giOutTab, giPosTab, giSnapTab  ;, iConfigTab
;                       *kx, *ky, *ihandle;
        FLhvsBoxSetValue gk1, gk2, gihandle
k0	init	0
k1	init	1
k2	init	2
printk2	tb0(k0)
printk2	tb0(k1), 10
printk2	tb0(k2), 20
  kris init 0.003
  kdur init 0.02
  kdec init 0.007
; Make parameters of synthesis depend on the table values produced by hvs
ares1 fof 0.2, tb0(k0)*100 + 50, tb0(k1)*100 + 200, 0, tb0(k2) * 10 + 50, 0.003, 0.02, 0.007, 20, \
      1, 2, p3
ares2 fof 0.2, tb0(k1)*100 + 50, tb0(k2)*100 + 200, 0, tb0(k0) * 10 + 50, 0.003, 0.02, 0.007, 20, \
      1, 2, p3
outs ares1, ares2
	endin
</CsInstruments>
<CsScore>
f 1 0 1024 10 1  ;Sine wave
f 2 0 1024 19 0.5 0.5 270 0.5  ;Grain envelope table
f0 3600
i1 0 3600
</CsScore>
</CsoundSynthesizer>

      Voici un second exemple de l'opcode hvs2. Il utilise le fichier
      hvs2-2.csd.

            Exemple 399. Second exemple de l'opcode hvs2.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
; Audio out   Audio in
-odac           -iadc    ;;;RT audio I/O
; For Non-realtime ouput leave only the line below:
; -o hvs2.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr=48000
ksmps=100
nchnls=2

; Example by James Hearon 2008
; Edited by Andres Cabrera

ginumPointsX init       16
ginumPointsY init       16
ginumParms  init        3

;Generate 9 tables with arbitrary points
gitmp ftgen 100, 0, 16, -2, 70, 260, 390, 180, 200, 300, 980, 126, \
                330, 860, 580, 467, 220, 399, 1026, 1500
gitmp ftgen 200, 0, 16, -2, 100, 200, 300, 140, 600, 700, 880, 126, \
                330, 560, 780, 167, 220, 999, 1026, 1500
gitmp ftgen 300, 0, 16, -2, 400, 200, 300, 540, 600, 700, 880, 126, \
                330, 160, 780, 167, 820, 999, 1026, 1500
gitmp ftgen 400, 0, 16, -2, 100, 200, 800, 640, 600, 300, 880, 126, \
                330, 660, 780, 167, 220, 999, 1026, 1500
gitmp ftgen 500, 0, 16, -2, 200, 200, 360, 440, 600, 700, 880, 126, \
                330, 560, 380, 167, 220, 499, 1026, 1500
gitmp ftgen 600, 0, 16, -2, 100, 600, 300, 840, 600, 700, 880, 126, \
                330, 260, 980, 367, 120, 399, 1026, 1500
gitmp ftgen 700, 0, 16, -2, 100, 200, 300, 340, 200, 500, 380, 126, \
                330, 860, 780, 867, 120, 999, 1026, 1500
gitmp ftgen 800, 0, 16, -2, 100, 600, 300, 240, 200, 700, 880, 126, \
                130, 560, 980, 167, 220, 499, 1026, 1500
gitmp ftgen 900, 0, 16, -2, 100, 800, 200, 140, 600, 700, 680, 126, \
                330, 560, 780, 167, 120, 299, 1026, 1500

giOutTab ftgen   5,0,8, -2,      0
giPosTab ftgen   6,0,32, -2, 0,1,2,3,4,5,6,7,8,9,10, 11, 15, 14, 13, 12
giSnapTab ftgen   8,0,64, -2,  1,1,1,   2,0,0,  3,2,0,  2,2,2,  \
        5,2,1,  2,3,4,  6,1,7,  0,0,0,  1,3,5,  3,4,4,  1,5,8,  1,1,5,  \
        4,3,2,  3,4,5,  7,6,5,  7,8,9

tb0_init        giOutTab

        FLpanel "hsv2",440,100,10,10,0
gk1,ih1 FLslider "X", 0,1, 0, 5, -1, 400,20, 20,10
gk2, ih2 FLslider "Y", 0, 1, 0, 5, -1, 400, 20, 20, 50
        FLpanel_end

        FLpanel "hvsBox",280,280,500,1000,0
;ihandle FLhvsBox inumlinesX, inumlinesY, iwidth, iheight, ix, iy [, image]
gih1  FLhvsBox  16, 16, 250, 250, 10, 1
        FLpanel_end
        FLrun

        instr   1
FLhvsBoxSetValue gk1, gk2, gih1

hvs2    gk1,gk2,  ginumParms, ginumPointsX, ginumPointsY, giOutTab, giPosTab, giSnapTab  ;, iConfigTab

k0      init    0
k1      init    1
k2      init    2
kspeed  init    0

kspeed = int((tb0(k2)) + 1)*.10

kenv  oscil   25000, kspeed*16, 10

k1    phasor kspeed ;slow phasor: 200 sec.
kpch  tableikt k1 * 16, int((tb0(k1)) +1)*100 ;scale phasor * length
a1    oscilikt kenv, kpch, int(tb0(k0)) +1000;scale pitch slightly
ahp butterlp a1, 2500
outs ahp, ahp

        endin

</CsInstruments>
<CsScore>

f 10  0  1024 20  5 ;use of windowing function
f1000 0 1024 10 .33 .25 .5
f1001 0 1024 10 1
f1002 0 1024 10 .5  .25  .05
f1003 0 1024 10 .05  .10  .3  .5  1
f1004 0 1024 10 1 .5  .25  .125  .625
f1005 0 1024 10 .33  .44  .55  .66
f1006 0 1024 10 1 1 1 1 1
f1007 0 1024 10 .05 .25 .05 .25 .05 1

f0 3600
i1 0 3600

</CsScore>
</CsoundSynthesizer>

Voir aussi

      hvs1,
      hvs3,
      vphaseseg

Crédits

Auteur : Gabriel Maldonado

Nouveau dans la version 5.06

          Précédent

            Niveau supérieur

           Suivant

          hvs1

            Sommaire

           hvs3


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**bcc** | [**AdvanceArg**](AdvanceArg.md) |  | [optional]
**body** | [**AdvanceArg**](AdvanceArg.md) |  | [optional]
**cc** | [**AdvanceArg**](AdvanceArg.md) |  | [optional]
**default_option** | **str** |  | [optional]
**format** | **str** |  | [optional]
**methods** | **list[str]** |  | [optional]
**reply_options** | **list[str]** |  | [optional]
**subject** | [**AdvanceArg**](AdvanceArg.md) |  | [optional]
**timings** | [**NotifyTimings**](NotifyTimings.md) |  | [optional]
**to** | [**AdvanceArg**](AdvanceArg.md) |  | [optional]

[[Back to Model list]](README.md#documentation-for-models) [[Back to API list]](README.md#documentation-for-api-endpoints) [[Back to README]](README.md)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TVS.API;

namespace TVSPlayer
{
    /// <summary>
    /// Interaction logic for SeriesInLibrary.xaml
    /// </summary>
    public partial class SeriesInLibrary : UserControl
    {
        public SeriesInLibrary(Series series)
        {
            InitializeComponent();
            this.series = series;
        }
        public Series series;
        bool showing = false;

        private async void Grid_Loaded(object sender, RoutedEventArgs e) {
            //PosterImage.ToolTip = series.seriesName;
        }

        private void Grid_MouseRightButtonUp(object sender, MouseButtonEventArgs e) {
            if (!showing) {
                Show();
                showing = true;
            } else {
                Hide();
                showing = false;
            }
        }

        private void Show() {
            DoubleAnimation animation = new DoubleAnimation(this.ActualHeight / 8, new TimeSpan(0, 0, 0, 0, 200));
            animation.AccelerationRatio = animation.DecelerationRatio = 0.5;
            DetailsGrid.BeginAnimation(HeightProperty, animation);
            RemoveIcon.Height = this.ActualHeight / 16;
            PosterIcon.Height = this.ActualHeight / 14;
            PosterIcon.Margin = new Thickness(0, 0, this.ActualWidth / 7.5, 3);
            QuestionIcon.Height = this.ActualHeight / 15;
            QuestionIcon.Margin = new Thickness(0, 0, this.ActualWidth / 3.75, 0);
            //ShowName.FontSize = this.ActualHeight / 14;
            Storyboard sb = (Storyboard)FindResource("OpacityUp");
            sb.Begin(DetailsGrid);
        }

        private void Hide() {
            DoubleAnimation animation = new DoubleAnimation(0, new TimeSpan(0, 0, 0, 0, 200));
            animation.AccelerationRatio = animation.DecelerationRatio = 0.5;
            DetailsGrid.BeginAnimation(HeightProperty, animation);
            Storyboard sb = (Storyboard)FindResource("OpacityDown");
            sb.Begin(DetailsGrid);
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e) {
            Mouse.OverrideCursor = Cursors.Hand;
            Show();
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e) {
            Mouse.OverrideCursor = null;
            Hide();
        }
    }
}


text:
package org.cyclops.commoncapabilities.modcompat.thermalexpansion.recipehandler;

import cofh.thermalexpansion.util.managers.machine.CrucibleManager;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.item.ItemStack;
import org.cyclops.commoncapabilities.Reference;
import org.cyclops.commoncapabilities.api.capability.itemhandler.ItemMatch;
import org.cyclops.commoncapabilities.api.capability.recipehandler.IPrototypedIngredientAlternatives;
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
import org.cyclops.commoncapabilities.api.capability.recipehandler.PrototypedIngredientAlternativesList;
import org.cyclops.commoncapabilities.api.capability.recipehandler.RecipeDefinition;
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
import org.cyclops.commoncapabilities.api.ingredient.PrototypedIngredient;
import org.cyclops.commoncapabilities.capability.recipehandler.TransformedRecipeHandlerAdapter;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Recipe handler for {@link CrucibleManager.CrucibleRecipe}.
 * @author rubensworks
 */
public class TileCrucibleRecipeHandler extends TransformedRecipeHandlerAdapter<CrucibleManager.CrucibleRecipe> {

    public TileCrucibleRecipeHandler() {
        super(Sets.newHashSet(IngredientComponent.ITEMSTACK),
                Sets.newHashSet(IngredientComponent.FLUIDSTACK));
    }

    @Override
    protected String getRecipeCacheKey() {
        return Reference.MOD_THERMALEXPANSION + ":crucible";
    }

    @Override
    protected IRecipeDefinition transformRecipe(CrucibleManager.CrucibleRecipe recipe) {
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredientAlternatives<?, ?>>> inputs = Maps.newIdentityHashMap();
        Map<IngredientComponent<?, ?>, List<?>> outputs = Maps.newIdentityHashMap();

        inputs.put(IngredientComponent.ITEMSTACK, Lists.newArrayList(new PrototypedIngredientAlternativesList<>(
                Lists.newArrayList(new PrototypedIngredient<>(IngredientComponent.ITEMSTACK, recipe.getInput(), ItemMatch.EXACT))
        )));

        outputs.put(IngredientComponent.FLUIDSTACK, Lists.newArrayList(recipe.getOutput()));

        return new RecipeDefinition(inputs, new MixedIngredients(outputs));
    }

    @Override
    protected CrucibleManager.CrucibleRecipe findRecipe(IMixedIngredients input) {
        return CrucibleManager.getRecipe(input.getFirstNonEmpty(IngredientComponent.ITEMSTACK));
    }

    @Override
    protected Collection<CrucibleManager.CrucibleRecipe> getRecipesRaw() {
        return Lists.newArrayList(CrucibleManager.getRecipeList());
    }

    @Override
    public boolean isValidSizeInput(IngredientComponent<?, ?> component, int size) {
        return component == IngredientComponent.ITEMSTACK && size == 1;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Gallio.Runtime.Logging;

namespace Gallio.AutoCAD.Commands
{
    /// <summary>
    /// Maps to the <c>NETLOAD</c> command.
    /// </summary>
    public class NetLoadCommand : AcadCommand
    {
        private readonly ILogger logger;
        private readonly IAcadPluginLocator pluginLocator;

        /// <summary>
        /// Initializes a new <see cref="NetLoadCommand"/> object.
        /// </summary>
        public NetLoadCommand(ILogger logger, IAcadPluginLocator pluginLocator)
            : base("NETLOAD")
        {
            if (logger == null)
                throw new ArgumentNullException("logger");
            if (pluginLocator == null)
                throw new ArgumentNullException("pluginLocator");
            this.logger = logger;
            this.pluginLocator = pluginLocator;
        }

        /// <inheritdoc/>
        protected override IEnumerable<string> GetArgumentsImpl(object application)
        {
            var version = GetAcadVersion(application);
            var path = pluginLocator.GetPluginPath(version);
            yield return path;
        }

        private string GetAcadVersion(object application)
        {
            try
            {
                return application.GetType().InvokeMember(@"Version", BindingFlags.GetProperty, null, application, null) as string;
            }
            catch (MemberAccessException e)
            {
                logger.Log(LogSeverity.Warning, "Unable to retrieve AutoCAD version.", e);
            }
            return null;
        }
    }
}


text:
#include "stdafx.h"
#include "EOSAIBrain.h"
#include "EOSAIUnitTask_MoveTo.h"
//#include "UnitTemplate.h"
//#include "Unit.h"
//#include "UnitOrder.h"
//#include "WorldDesc.h"
//#include "AISuperTask.h"
#include "EOSAIAction.h"
//#include "WorldDescServer.h"
//#include "Checkpoint.h"
#include "EOSAIWorldDistanceTool.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

EOSAI::UnitTask_MoveTo::UnitTask_MoveTo(
							EOSAI::PoiMobile* pActor,
							CEOSAIAction* pAIAction,
							EOSAI::PoiObjectState* pMyUnitsInitialState,
							CEOSAILocation TargetLocation ) : EOSAI::UnitTask( pActor, pAIAction )
{
	m_MemoryOfInitialState.Copy( pMyUnitsInitialState );
	//m_FinalState.SetWorldDesc( pWorldDesc );
	m_FinalState.Copy( pMyUnitsInitialState );
	//m_FinalState.SetLocationAndRegions( pMultiRegion );
	m_FinalState.SetLocationAndRegions( TargetLocation );
	//m_FinalState.SetContainer( pTargetToEnter );

	//CString strText;
	//strText.Format( _T("EOSAI::UnitTask_MoveTo (%x) created"), this );
	//Checkpoint::Write( strText );
}

EOSAI::UnitTask_MoveTo::~UnitTask_MoveTo()
{
	//CString strText;
	//strText.Format( _T("EOSAI::UnitTask_MoveTo (%x) deleted"), this );
	//Checkpoint::Write( strText );
}

void EOSAI::UnitTask_MoveTo::UpdateFinalState()
{
	float fOldFinalTime = GetFinalState()->GetTime();
	CEOSAILocation FinalLocation = GetFinalLocation(); // preserve the FinalLocation (it gets overwritten)
	//long iFinalGeo = GetEndGeo();
	CEOSAIMultiRegion2* pFinalMultiRegion = GetFinalState()->GetMultiRegion();

	GetFinalState()->Copy( GetMemoryOfInitialState() );
	//GetFinalState()->SetTime( GetMemoryOfInitialState()->GetTime() + m_fDuration );
	m_fArrivalTime = GetMemoryOfInitialState()->GetTime() + m_fDuration;
	GetFinalState()->SetTime( fOldFinalTime );
	GetFinalState()->SetLocationAndRegions( FinalLocation, pFinalMultiRegion );
	//GetFinalState()->SetContainer( m_pTargetToEnter );

	// If the end time changes, the score changes
	if( m_bIsTheFinalTaskInTheAction )//&& fOldFinalTime != GetEndTime() )
	{
		if( m_pAIAction )
		{
			m_pAIAction->UpdateFinalTime( m_FinalState.GetTime() );
			m_pAIAction->UpdateScore();
		}
		/*
		if( m_pDefinedAction )
		{
			m_pDefinedAction->UpdateFinalTime( GetEndTime() );
			//m_pDefinedAction->GetPoiMobileFinalState()->SetTime( GetEndTime() );
			//m_pDefinedAction->UpdateScore();
		}
		*/
	}
}

void EOSAI::UnitTask_MoveTo::CalculateTaskDistanceAndDuration()
{
	EOSAI::PoiMobile* pUnitSymbol = GetParentUnit();
	//
	ASSERT( m_MemoryOfInitialState.GetLocation().GetRealX() != 0.0f || m_MemoryOfInitialState.GetLocation().GetRealY() != 0.0f );
	ASSERT( m_FinalState.GetLocation().GetRealX() != 0.0f || m_FinalState.GetLocation().GetRealY() != 0.0f );

	//CWorldDescServer* pWorldDescServer = GetCommonState()->GetWorldDescServer();
	//m_fDistance = pWorldDescServer->GetPixelDistance( m_MemoryOfInitialState.GetLocation(), m_FinalState.GetLocation() );
	m_fDistance = g_pWorldDistanceTool->GetDistance( m_MemoryOfInitialState.GetLocation(), m_FinalState.GetLocation() );
	/*
	INCOMPLETE: This should be replaced by an actual path
	m_fDistance = pUnitSymbol->GetAIBrain()->GetAIRegionManager()->GetPixelDistance(
		m_MemoryOfInitialState.GetLocation(),
		m_FinalState.GetLocation(),
		pUnitSymbol->GetMovementType(), 0 );
	*/
	if( m_fDistance == -1.0f )
	{
		m_bTaskIsValid = false;
		SetTaskDuration( 0.0f );
		return;
	}
	else
	{
		m_bTaskIsValid = true;
	}

	// DEBUG
	#ifdef _DEBUG
	if( m_fDistance <= 0.0f )
	{
		ASSERT( false );
		//CWorldDescServer* pWorldDescServer = GetCommonState()->GetWorldDescServer();
		//m_fDistance = pWorldDescServer->GetPixelDistance( m_MemoryOfInitialState.GetLocation(), m_FinalState.GetLocation() );
		/*
		INCOMPLETE: This should be replaced by an actual path
		m_fDistance = pUnitSymbol->GetAIBrain()->GetAIRegionManager()->GetPixelDistance(
			m_MemoryOfInitialState.GetLocation(),
			m_FinalState.GetLocation(),
			pUnitSymbol->GetMovementType(), 0 );
		*/
	}
	#endif _DEBUG

	m_fDuration = m_fDistance / pUnitSymbol->GetMovementRate();
	m_fArrivalTime = m_MemoryOfInitialState.GetTime() + m_fDuration;

	ASSERT( m_fDistance > 0.0f );
	ASSERT( GetTaskDuration() > 0.0f );

	UpdateFinalState();
}
/*
void EOSAI::UnitTask_MoveTo::CreateOrders()
{
	ASSERT( m_bOrdersWereCreated == false );

	if( GetParentUnit()->GetServerPoiMobile() )
	{
		CPoiMobile* pUnit = GetParentUnit()->GetServerPoiMobile();

		ASSERT( m_pUnitOrder == NULL );
		m_pUnitOrder = new CUnitOrder();
		m_pUnitOrder->SetWorldDesc( pUnit->GetWorldDesc() );
		m_pUnitOrder->SetParent( pUnit->ObjectId() );
		//m_pUnitOrder->MoveTo( m_FinalState.m_Location.GetRealX(), m_FinalState.m_Location.GetRealY() );
		m_pUnitOrder->MoveTo( GetFinalState()->GetLocation() );
		pUnit->AppendOrder( m_pUnitOrder );
		if( m_pUnitOrder->CalculateAStar() == false )
		{
			pUnit->DeleteOrder( m_pUnitOrder );
		}
	}
	m_bOrdersWereCreated = true;
}
*/

/*
EOSAI::UnitTask_MoveTo::EOSAI::UnitTask_MoveTo(
					EOSAI::PoiMobile* pParentUnit,
					//CAISuperTask* pSuperTask,
					CAIDefinedAction* pDefinedAction,
					//CEOSAILocation InitialLocation,
					EOSAI::PoiObjectState* pMyUnitsPreviousState,
					CEOSAILocation TargetLocation ) : EOSAI::UnitTask( pParentUnit, pDefinedAction )
{
	//CWorldDesc* pWorldDesc = pParentUnit->GetAIPlayer()->GetWorldDesc();
	//m_InitialState.SetWorldDesc( pWorldDesc );
	m_InitialState.Copy( pMyUnitsPreviousState );
	//m_InitialState.SetLocationAndGeo( InitialLocation );
	//m_FinalState.SetWorldDesc( pWorldDesc );
	m_FinalState.Copy( pMyUnitsPreviousState );
	m_FinalState.SetLocationAndGeo( TargetLocation );
	int z=0;
}

void EOSAI::UnitTask_MoveTo::UpdateFinalState()
{
	float fOldFinalTime = GetEndTime();
	CEOSAILocation FinalLocation = GetFinalLocation(); // preserve the FinalLocation (it gets overwritten)
	long iFinalGeo = GetEndGeo();

	GetFinalState()->Copy( GetStartState() );
	GetFinalState()->SetTime( GetStartState()->GetTime() + m_fDuration );
	GetFinalState()->SetLocationAndGeo( FinalLocation, iFinalGeo );

	// If the end time changes, the score changes
	if( m_bIsTheFinalTaskInTheAction && fOldFinalTime != GetEndTime() )
	{
		/*
		if( m_pDefinedAction )
		{
			m_pDefinedAction->GetPoiMobileFinalState()->SetTime( GetEndTime() );
			m_pDefinedAction->UpdateScore();
		}
		*-/
	}
}

void EOSAI::UnitTask_MoveTo::CalculateTaskDistanceAndDuration()
{
	EOSAI::PoiMobile* pUnitSymbol = GetParentUnit();
	//
	ASSERT( m_InitialState.GetLocation().GetRealX() != 0.0f || m_InitialState.GetLocation().GetRealY() != 0.0f );
	ASSERT( m_FinalState.GetLocation().GetRealX() != 0.0f || m_FinalState.GetLocation().GetRealY() != 0.0f );
	m_fDistance = pUnitSymbol->GetAIPlan()->GetSpatialMap()->GetPixelDistance(
		m_InitialState.GetLocation(),
		m_FinalState.GetLocation(),
		pUnitSymbol->GetMovementType(), 0 );

	if( m_fDistance == -1.0f )
	{
		m_bTaskIsValid = false;
		SetTaskDuration( 0.0f );
		return;
	}
	else
	{
		m_bTaskIsValid = true;
	}

	// DEBUG
	#ifdef _DEBUG
	if( m_fDistance <= 0.0f )
	{
		ASSERT( false );
		m_fDistance = pUnitSymbol->GetAIPlan()->GetSpatialMap()->GetPixelDistance(
			m_InitialState.GetLocation(),
			m_FinalState.GetLocation(),
			pUnitSymbol->GetMovementType(), 0 );
	}
	#endif _DEBUG

	m_fDuration = m_fDistance / pUnitSymbol->GetMovementRate();
	m_fArrivalTime = m_InitialState.GetTime() + m_fDuration;

	ASSERT( m_fDistance > 0.0f );
	ASSERT( GetTaskDuration() > 0.0f );

	UpdateFinalState();
}

void EOSAI::UnitTask_MoveTo::CreateOrders()
{
	ASSERT( m_bOrdersWereCreated == false );
	m_bOrdersWereCreated = true;

	if( GetParentUnit()->GetPoiMobile() )
	{
		CPoiMobile* pUnit = GetParentUnit()->GetPoiMobile();

		ASSERT( m_pUnitOrder == NULL );
		m_pUnitOrder = new CUnitOrder();
		m_pUnitOrder->SetWorldDesc( pUnit->GetWorldDesc() );
		m_pUnitOrder->SetParent( pUnit->ObjectId() );
		m_pUnitOrder->MoveTo( m_FinalState.GetLocation().GetRealX(), m_FinalState.GetLocation().GetRealY() );
		pUnit->AppendOrder( m_pUnitOrder );
		//pOrder->CalculateAStar();
		if( m_pUnitOrder->CalculateAStar() == false )
		{
			pUnit->DeleteOrder( m_pUnitOrder );
		}
	}
}
*/


text:
<!DOCTYPE html>

  <title>CustomColorPalette Unit Tests</title>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.safframework.utils"
          xmlns:android="http://schemas.android.com/apk/res/android"
          >

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.safframework.app.MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package com.github.florent37.androidunittest.managers;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;

import com.github.florent37.androidunittest.AndroidUnitTest;
import com.github.florent37.androidunittest.annotations.RActivity;

import org.mockito.internal.util.reflection.FieldSetter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * Created by kevinleperf on 18/05/16.
 */
public class AnnotationActivityManager extends AbstractAnnotationManager {

    @VisibleForTesting Field activityField;

    public AnnotationActivityManager(AndroidUnitTest parent) {
        super(parent);

        //createAndInitActivity(null, FragmentActivity.class, null);
        //parent.activity().setActivityState(ActivityState.CREATED);
        //useless create() here since in createAndInitActivity
        //parent.getActivityController().create();
    }

    @Override
    public void scanned(@NonNull Field field) {
        activityField = field;
    }

    @Override
    public void execute(@NonNull Object object, @NonNull Context context) {
        if (activityField != null) {
            createAndInitActivity(object,
                    activityField.getType(),
                    activityField.getAnnotation(RActivity.class));
        }//activityField is null, using standard FragmentActivity from constructor
    }

    public Field getScanned() {
        return activityField;
    }

    public void createAndInitActivity(@Nullable Object target, Class activityClass, @Nullable RActivity activityAnnotation) {
        Activity activity = getAndroidUnitTest().activity().createAndInitActivity(activityClass, activityAnnotation);
        if (this.activityField != null && target != null) {
            new FieldSetter(target, this.activityField).set(activity);
        }
    }

    public void updateActivity(Object target) {
        new FieldSetter(target, this.activityField)
                .set(getAndroidUnitTest().getActivityController().get());
    }

    @NonNull
    @Override
    protected Class<? extends Annotation> canManagerInternal() {
        return RActivity.class;
    }
}


text:
package org.aml.java.mapping;

public @interface serializable {

}


text:
import { RequestHandler } from "../core";
import { Handler } from "../router";

import * as bodyParser from "body-parser";

// HINT: body-parser is hard coded in registrar.ts for now
// @Handler("/1" /* HACK!!!!!! */)
export class BodyParserHandler extends RequestHandler {

  constructor(request: any, response: any, next?: any) {
    super(request, response, next);

    this.context.logger.log("Parse body...");

    // HACK: parse body as simple text by default.
    // TODO: enable selective param parsing on controller level with decorators.
    bodyParser.text({ type: "application/json" })(request, response, () => {
      if (next) next();
      else this.response.end();
    });
  }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Modulargaming_Model_Battle extends Jelly_Model {

	public static function initialize(Jelly_Meta $meta)
	{

		$meta->fields += array(
			'id' => new Field_Primary,
			'character' => new Field_BelongsTo,
			'monster' => new Field_BelongsTo,

			'hp' => new Field_Integer,
			'character_atk' => new Field_Integer,
			'monster_atk' => new Field_Integer,
		);

	}

}


text:
package com.opengamma.analytics.financial.commodity.definition;

import org.threeten.bp.ZonedDateTime;

import com.opengamma.analytics.financial.ExerciseDecisionType;
import com.opengamma.analytics.financial.commodity.derivative.AgricultureFuture;
import com.opengamma.analytics.financial.commodity.derivative.AgricultureFutureOption;
import com.opengamma.analytics.financial.instrument.InstrumentDefinitionVisitor;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.util.ArgumentChecker;

/**
 * Agriculture future options definition
 */
public class AgricultureFutureOptionDefinition extends CommodityFutureOptionDefinition<AgricultureFutureDefinition, AgricultureFutureOption> {

  /**
   * Constructor for option
   *
   * @param expiryDate  the time and the day that a particular delivery month of a futures contract stops trading, as well as the final settlement price for that contract
   * @param underlying  underlying future
   * @param strike  strike price
   * @param exerciseType  exercise type - European or American
   * @param isCall  call if true, put if false
   */
  public AgricultureFutureOptionDefinition(final ZonedDateTime expiryDate, final AgricultureFutureDefinition underlying, final double strike,
      final ExerciseDecisionType exerciseType, final boolean isCall) {
    super(expiryDate, underlying, strike, exerciseType, isCall);
  }

  @Override
  public AgricultureFutureOption toDerivative(final ZonedDateTime date) {
    ArgumentChecker.inOrderOrEqual(date, this.getExpiryDate(), "date", "expiry date");
    final double timeToFixing = TimeCalculator.getTimeBetween(date, this.getExpiryDate());
    final AgricultureFuture underlyingDeriv = getUnderlying().toDerivative(date);
    return new AgricultureFutureOption(timeToFixing, underlyingDeriv, getStrike(), getExerciseType(), isCall());
  }

  @Override
  public <U, V> V accept(final InstrumentDefinitionVisitor<U, V> visitor, final U data) {
    ArgumentChecker.notNull(visitor, "visitor");
    return visitor.visitAgricultureFutureOptionDefinition(this, data);
  }

  @Override
  public <V> V accept(final InstrumentDefinitionVisitor<?, V> visitor) {
    ArgumentChecker.notNull(visitor, "visitor");
    return visitor.visitAgricultureFutureOptionDefinition(this);
  }

  @Override
  public int hashCode() {
    return super.hashCode();
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof AgricultureFutureOptionDefinition)) {
      return false;
    }
    return super.equals(obj);
  }

}


text:
layout: post
title:  "Markdown Syntax"
date:   2016-03-15
excerpt: "Just about everything you'll need to style in the theme: headings, paragraphs, blockquotes, tables, code blocks, and more."
tag:
- Markdown Example
comments: true
---

## HTML Elements

Below is just about everything you'll need to style in the theme. Check the source code to see the many embedded elements within paragraphs.

# Heading 1

## Heading 2

### Heading 3

#### Heading 4

##### Heading 5

###### Heading 6

### Body text

Lorem ipsum dolor sit amet, test link adipiscing elit. **This is strong**. Nullam dignissim convallis est. Quisque aliquam.

![Smithsonian Image](https://mmistakes.github.io/minimal-mistakes/images/3953273590_704e3899d5_m.jpg)
{: .image-right}

*This is emphasized*. Donec faucibus. Nunc iaculis suscipit dui. 53 = 125. Water is H2O. Nam sit amet sem. Aliquam libero nisi, imperdiet at, tincidunt nec, gravida vehicula, nisl. The New York Times (That's a citation). Underline.Maecenas ornare tortor. Donec sed tellus eget sapien fringilla nonummy. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus.

HTML and CSS are our tools. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus. Praesent mattis, massa quis luctus fermentum, turpis mi volutpat justo, eu volutpat enim diam eget metus.

### Blockquotes

> Lorem ipsum dolor sit amet, test link adipiscing elit. Nullam dignissim convallis est. Quisque aliquam.

## List Types

### Ordered Lists

1. Item one
   1. sub item one
   2. sub item two
   3. sub item three
2. Item two

### Unordered Lists

* Item one
* Item two
* Item three

## Tables

| Header1 | Header2 | Header3 |
|:--------|:-------:|--------:|
| cell1   | cell2   | cell3   |
| cell4   | cell5   | cell6   |
|----
| cell1   | cell2   | cell3   |
| cell4   | cell5   | cell6   |
|=====
| Foot1   | Foot2   | Foot3
{: rules="groups"}

## Code Snippets

{% highlight css %}
#container {
  float: left;
  margin: 0 -240px 0 0;
  width: 100%;
}
{% endhighlight %}

## Buttons

Make any link standout more when applying the `.btn` class.

{% highlight html %}
Success Button
{% endhighlight %}

Primary Button

Success Button

Warning Button

Danger Button

Info Button

## KBD

You can also use `<kbd>` tag for keyboard buttons.

{% highlight html %}
WASD
{% endhighlight %}

Press WASD to move your car. **Midtown Maddness!!**

## Notices

**Watch out!** You can also add notices by appending `{: .notice}` to a paragraph.
{: .notice}


text:
static SPIQYVideo *instance = nil;

@interface SPIQYVideo()<WKNavigationDelegate>
@property (nonatomic, strong)  WKWebView*webView;
@property (nonatomic, copy) void(^completeBlock)(NSString *url);

@end

@implementation SPIQYVideo

+ (instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        instance = [super allocWithZone:zone];

    });

    return instance;
}

+ (instancetype)sharedVideo{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        instance = [[self alloc] init];
        [NSURLProtocol wk_registerScheme:@"http"];
        [NSURLProtocol wk_registerScheme:@"https"];
    });

    return instance;
}

- (void)setCompleteBlock:(void (^)(NSString *))completeBlock{
    _completeBlock = completeBlock;
    if (completeBlock) {
        [NSURLProtocol registerClass:[HybridNSURLProtocol class]];
        [[UIApplication sharedApplication].keyWindow addSubview:self.webView];
    }else{
        [NSURLProtocol unregisterClass:[HybridNSURLProtocol class]];
        [self.webView removeFromSuperview];
        self.webView = nil;
    }
}
- (void)reset{
    if (self.completeBlock) {
        self.completeBlock(nil);
        self.completeBlock = nil;
    }
}
- (void)playWithURL:(NSString *)urlString
           completion:(void(^)(NSString *url))completed{

    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.completeBlock) {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reset) object:nil];
        }
        self.completeBlock = completed;

        NSMutableURLRequest *mutableReqeust = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        [mutableReqeust setValue:@"Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko)" forHTTPHeaderField:@"User-Agent"];

        [self.webView loadRequest:mutableReqeust];

        [self performSelector:@selector(reset) withObject:nil afterDelay:20.0];
    });

}

- (WKWebView *)webView{
    if (!_webView) {
        // 1.创建webview,并设置大小,"20"为状态栏高度

        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,0,375,0)];

        // 2.创建请求

        //NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];

        // 3.加载网页

        //[webView loadRequest:request];

        webView.navigationDelegate = self;
        //最后将webView添加到界面

        //[self.view addSubview:webView];

        _webView = webView;
    }

    return _webView;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *JsStr = @"(document.getElementsByTagName(\"video\")[0]).src";
    [webView evaluateJavaScript:JsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if(![response isEqual:[NSNull null]] && response != nil){
            //截获到视频地址了
            NSLog(@"response == %@",response);
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([SPIQYVideo sharedVideo].completeBlock) {
                    [SPIQYVideo sharedVideo].completeBlock(response);
                    [SPIQYVideo sharedVideo].completeBlock = nil;
                }
            });
        }else{
            //没有视频链接
        }
    }];
}

@end

static NSString*const sourUrl  = @"https://m.baidu.com/static/index/plus/plus_logo.png";
static NSString*const sourIconUrl  = @"http://m.baidu.com/static/search/baiduapp_icon.png";
static NSString*const localUrl = @"http://mecrm.qa.medlinker.net/public/image?id=57026794&certType=workCertPicUrl&time=1484625241";

static NSString* const KHybridNSURLProtocolHKey = @"KHybridNSURLProtocol";
@interface HybridNSURLProtocol ()<NSURLSessionDelegate>
@property (nonnull,strong) NSURLSessionDataTask *task;

@end

@implementation HybridNSURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSString *scheme = [[request URL] scheme];
    if ( ([scheme caseInsensitiveCompare:@"http"]  == NSOrderedSame ||
          [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame ))
    {
        //看看是否已经处理过了,防止无限循环
        if ([NSURLProtocol propertyForKey:KHybridNSURLProtocolHKey inRequest:request]
            ){
            return NO;
        }

        return YES;
    }
    return NO;
}

+ (BOOL)replaceAdHostsWebString:(NSArray *)adhosts response:(NSString **)response{
    BOOL isContain = NO;

    for (NSString *adhost in adhosts) {
        isContain = isContain | [[self class]  replaceWebString:adhost response:response];
    }
    return  isContain;
}

+ (BOOL)replaceWebString:(NSString *)adhost response:(NSString **)response{
    BOOL isContain = NO;
    if ([*response containsString:adhost]) {
        *response = [*response stringByReplacingOccurrencesOfString:adhost withString:@""];
        isContain = YES;
    }
    return  isContain;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    [mutableReqeust setValue:@"Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko)" forHTTPHeaderField:@"User-Agent"];

    //request截取重定向
    if ([request.URL.absoluteString isEqualToString:sourUrl])
    {
        NSURL* url1 = [NSURL URLWithString:localUrl];
        mutableReqeust = [NSMutableURLRequest requestWithURL:url1];
    }

    NSString *requestUrl = request.URL.absoluteString;
    // 拦截广告
    if ([requestUrl containsString:@"img.09mk.cn"]
        ||[requestUrl containsString:@"img.xiaohui2.cn"]
        ||[requestUrl containsString:@".xiaohui"]
        ||[requestUrl containsString:@".apple.com"]
        ||[requestUrl containsString:@"img2."]
        ||[requestUrl containsString:@"sysapr.cn"]
        ) {
        mutableReqeust = nil;
    }
    else
        if(
           [requestUrl containsString:@".m3u8"]
           //       [requestUrl.pathExtension hasPrefix:@"m3u8"]
//                  ||[requestUrl containsString:@".mp4"]
           )
        {
            //        if (![[UIViewController topViewController] isKindOfClass:[HLPlayerViewController class]]) {
            NSArray *urlArray = [requestUrl componentsSeparatedByString:@"url="];

            //            static bool isShow = NO;
            //            HLPlayerViewController *playerVC = [[HLPlayerViewController alloc] init];

            NSLog(@"RealVideoUrl %@", [urlArray lastObject]);
            //            playerVC.url = [NSURL URLWithString:[urlArray lastObject]];
            //            UIViewController *topVC = [UIViewController topkeyWindowViewController];
            //            __block __weak HLHomeViewController *homeVC = nil;
            //            for (UIViewController *vc in topVC.navigationController.childViewControllers) {
            //                if ([vc isKindOfClass:NSClassFromString(@"HLHomeViewController")]) {
            //                    playerVC.title = vc.title?:vc.navigationItem.title;
            //                    homeVC = (id)vc;
            //                    break;
            //                }
            //            }
            //
            //
            //            playerVC.backBlock = ^(BOOL finish){
            //                if (finish && (urlArray.count >= 2) && [[homeVC webView] respondsToSelector:@selector(canGoBack)]) {
            //                    if ([[homeVC webView] performSelector:@selector(canGoBack)]) {
            //                        [[homeVC webView] performSelector:@selector(goBack)];
            //                    }
            //                }
            //                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //                    isShow = NO;
            //                });
            //            };
            //
            //            [[UIViewController topkeyWindowViewController] presentViewController:playerVC animated:YES completion:nil];

            dispatch_async(dispatch_get_main_queue(), ^{
                if ([SPIQYVideo sharedVideo].completeBlock) {
                    [SPIQYVideo sharedVideo].completeBlock([urlArray lastObject]);
                    [SPIQYVideo sharedVideo].completeBlock = nil;
                }
//                if([[self topViewController] isKindOfClass:[MPMoviePlayerViewController class]]) return ;
//
//                MPMoviePlayerViewController *playVC = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:[urlArray lastObject]]];
//                playVC.view.frame = CGRectMake(0, 100, 414, 300);
//                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:playVC animated:YES completion:nil];
            });

            mutableReqeust = nil;
            //        }
        }
        else {
            NSLog(@"requestUrl = %@\n\r-------------------------------------------------------------------",requestUrl);
        }

    return mutableReqeust;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading
{
    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
    //给我们处理过的请求设置一个标识符, 防止无限循环,
    [NSURLProtocol setProperty:@YES forKey:KHybridNSURLProtocolHKey inRequest:mutableReqeust];

    //这里最好加上缓存判断,加载本地离线文件, 这个直接简单的例子。
    if ([mutableReqeust.URL.absoluteString isEqualToString:sourIconUrl])
    {
        NSData* data = UIImagePNGRepresentation([UIImage imageNamed:@"medlinker"]);
        NSURLResponse* response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:@"image/png" expectedContentLength:data.length textEncodingName:nil];
        [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
        [self.client URLProtocol:self didLoadData:data];
        [self.client URLProtocolDidFinishLoading:self];
    }
    else
    {
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
        self.task = [session dataTaskWithRequest:self.request];

        NSLog(@"xxxx request %@", self.request.URL.absoluteString);

        [self.task resume];
    }
}
- (void)stopLoading
{
    if (self.task != nil)
    {
        [self.task  cancel];
    }
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];

    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [[self client] URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    [self.client URLProtocolDidFinishLoading:self];
}

//FIXME:  -  自定义方法
+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];

    }
    return resultVC;
}
+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end
//FOUNDATION_STATIC_INLINE 属于属于runtime范畴,你的.m文件需要频繁调用一个函数,可以用static inline来声明。从SDWebImage从get到的。
FOUNDATION_STATIC_INLINE Class ContextControllerClass() {
    static Class cls;
    if (!cls) {
        cls = [[[WKWebView new] valueForKey:@"browsingContextController"] class];
    }
    return cls;
}

FOUNDATION_STATIC_INLINE SEL RegisterSchemeSelector() {
    return NSSelectorFromString(@"registerSchemeForCustomProtocol:");
}

FOUNDATION_STATIC_INLINE SEL UnregisterSchemeSelector() {
    return NSSelectorFromString(@"unregisterSchemeForCustomProtocol:");
}

@implementation NSURLProtocol (WebKitSupport)

+ (void)wk_registerScheme:(NSString *)scheme {
    Class cls = ContextControllerClass();
    SEL sel = RegisterSchemeSelector();
    if ([(id)cls respondsToSelector:sel]) {
        // 放弃编辑器警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [(id)cls performSelector:sel withObject:scheme];
#pragma clang diagnostic pop
    }
}

+ (void)wk_unregisterScheme:(NSString *)scheme {
    Class cls = ContextControllerClass();
    SEL sel = UnregisterSchemeSelector();
    if ([(id)cls respondsToSelector:sel]) {
        // 放弃编辑器警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [(id)cls performSelector:sel withObject:scheme];
#pragma clang diagnostic pop
    }
}

@end


text:
namespace TeamBuilder.App.Core.Commands
{
    using System;
    using System.Linq;
    using TeamBuilder.App.Utilities;
    using TeamBuilder.Data;
    using TeamBuilder.Models;

    //•	AddTeamTo <eventName> <teamName>

    public class AddTeamToCommand
    {
        public string Execute(string[] commandArgs)
        {
            Check.CheckLength(2, commandArgs);
            AuthenticationManager.Authorize();

            var user = AuthenticationManager.GetCurrentUser();
            string eventName = commandArgs[0];
            string teamName = commandArgs[1];

            if (!CommandHelper.IsUserCreatorOfEvent(eventName, user))
            {
                throw new InvalidOperationException(Constants.ErrorMessages.NotAllowed);
            }

            if (!CommandHelper.IsEventExisting(eventName))
            {
                throw new ArgumentException(String.Format(Constants.ErrorMessages.EventNotFound, eventName));
            }

            if (!CommandHelper.IsTeamExisting(teamName))
            {
                throw new ArgumentException(String.Format(Constants.ErrorMessages.TeamNotFound, teamName));
            }

            Event eventa = null;
            Team team = null;

            using(var context = new TeamBuilderContext())
            {
                eventa = context.Events
                    .Where(e => e.Name == eventName)
                    .OrderBy(e => e.StartDate)
                    .Last();

                team = context.Teams.FirstOrDefault(t => t.Name == teamName);

                if(context.EventTeams.Any(et => et.Team == team && et.Event == eventa))
                {
                    throw new InvalidOperationException("Cannot add same team twice!");
                }

                context.EventTeams.Add(new EventTeam { Event = eventa, Team = team });
                context.SaveChanges();
            }

            return $"Team {teamName} added for {eventName}!";
        }
    }
}


text:
#include "2d/CCLabel.h"
#include <vector>
#include "base/ccUTF8.h"
#include "base/CCDirector.h"
#include "2d/CCFontAtlas.h"
#include "2d/CCFontFNT.h"

NS_CC_BEGIN

void Label::computeAlignmentOffset()
{
    _linesOffsetX.clear();
    switch (_hAlignment)
    {
    case cocos2d::TextHAlignment::LEFT:
        _linesOffsetX.assign(_numberOfLines, 0);
        break;
    case cocos2d::TextHAlignment::CENTER:
        for (auto lineWidth : _linesWidth)
        {
            _linesOffsetX.push_back((_contentSize.width - lineWidth) / 2.f);
        }
        break;
    case cocos2d::TextHAlignment::RIGHT:
        for (auto lineWidth : _linesWidth)
        {
            _linesOffsetX.push_back(_contentSize.width - lineWidth);
        }
        break;
    default:
        break;
    }

    switch (_vAlignment)
    {
    case cocos2d::TextVAlignment::TOP:
        _letterOffsetY = _contentSize.height;
        break;
    case cocos2d::TextVAlignment::CENTER:
        _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2.f;
        break;
    case cocos2d::TextVAlignment::BOTTOM:
        _letterOffsetY = _textDesiredHeight;
        break;
    default:
        break;
    }
}

int Label::getFirstCharLen(const std::u32string& /*utf32Text*/, int /*startIndex*/, int /*textLen*/) const
{
    return 1;
}

int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int textLen) const
{
    int len = 0;
    auto nextLetterX = 0;
    FontLetterDefinition letterDef;
    auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();

    for (int index = startIndex; index < textLen; ++index)
    {
        char32_t character = utf32Text[index];

        if (character == StringUtils::UnicodeCharacters::NewLine
            || (!StringUtils::isUnicodeNonBreaking(character)
                && (StringUtils::isUnicodeSpace(character)
                    || StringUtils::isCJKUnicode(character))))
        {
            break;
        }

        if (!getFontLetterDef(character, letterDef))
        {
            break;
        }

        if (_maxLineWidth > 0.f)
        {
            auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;

            if (letterX + letterDef.width * _bmfontScale > _maxLineWidth)
                break;
        }

        nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;

        len++;
    }

    if (len == 0 && textLen)
        len = 1;

    return len;
}

bool Label::getFontLetterDef(char32_t character, FontLetterDefinition& letterDef) const
{
    if (character == StringUtils::UnicodeCharacters::NoBreakSpace)
    {
        // change no-break space to regular space
        // reason: some fonts have issue with no-break space:
        //   * no letter definition
        //   * not normal big width
        character = StringUtils::UnicodeCharacters::Space;
    }

    return _fontAtlas->getLetterDefinitionForChar(character, letterDef);
}

void Label::updateBMFontScale()
{
    auto font = _fontAtlas->getFont();
    if (_currentLabelType == LabelType::BMFONT) {
        FontFNT *bmFont = (FontFNT*)font;
        float originalFontSize = bmFont->getOriginalFontSize();
        _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize;
    }else{
        _bmfontScale = 1.0f;
    }
}

bool Label::multilineTextWrap(const std::function<int(const std::u32string&, int, int)>& nextTokenLen)
{
    int textLen = getStringLength();
    int lineIndex = 0;
    float nextTokenX = 0.f;
    float nextTokenY = 0.f;
    float longestLine = 0.f;
    float letterRight = 0.f;

    auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();
    float lineSpacing = _lineSpacing * contentScaleFactor;
    float highestY = 0.f;
    float lowestY = 0.f;
    FontLetterDefinition letterDef;
    Vec2 letterPosition;
    bool nextChangeSize = true;

    this->updateBMFontScale();

    for (int index = 0; index < textLen; )
    {
        char32_t character = _utf32Text[index];
        if (character == StringUtils::UnicodeCharacters::NewLine)
        {
            _linesWidth.push_back(letterRight);
            letterRight = 0.f;
            lineIndex++;
            nextTokenX = 0.f;
            nextTokenY -= _lineHeight*_bmfontScale + lineSpacing;
            recordPlaceholderInfo(index, character);
            index++;
            continue;
        }

        auto tokenLen = nextTokenLen(_utf32Text, index, textLen);
        float tokenHighestY = highestY;
        float tokenLowestY = lowestY;
        float tokenRight = letterRight;
        float nextLetterX = nextTokenX;
        bool newLine = false;
        for (int tmp = 0; tmp < tokenLen;++tmp)
        {
            int letterIndex = index + tmp;
            character = _utf32Text[letterIndex];
            if (character == StringUtils::UnicodeCharacters::CarriageReturn)
            {
                recordPlaceholderInfo(letterIndex, character);
                continue;
            }
            // \b - Next char not change x position
            if (character == StringUtils::UnicodeCharacters::NextCharNoChangeX)
            {
                nextChangeSize = false;
                recordPlaceholderInfo(letterIndex, character);
                continue;
            }

            if (!getFontLetterDef(character, letterDef))
            {
                recordPlaceholderInfo(letterIndex, character);
                CCLOG("LabelTextFormatter error: can't find letter definition in font file for letter: 0x%x", character);
                continue;
            }

            auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;
            if (_enableWrap && _maxLineWidth > 0.f && nextTokenX > 0.f && letterX + letterDef.width * _bmfontScale > _maxLineWidth
                && !StringUtils::isUnicodeSpace(character) && nextChangeSize)
            {
                _linesWidth.push_back(letterRight);
                letterRight = 0.f;
                lineIndex++;
                nextTokenX = 0.f;
                nextTokenY -= (_lineHeight*_bmfontScale + lineSpacing);
                newLine = true;
                break;
            }
            else
            {
                letterPosition.x = letterX;
            }
            letterPosition.y = (nextTokenY - letterDef.offsetY * _bmfontScale) / contentScaleFactor;
            recordLetterInfo(letterPosition, character, letterIndex, lineIndex);

            if (nextChangeSize)
            {
                if (_horizontalKernings && letterIndex < textLen - 1)
                    nextLetterX += _horizontalKernings[letterIndex + 1];
                nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;

                if (tokenLen != 1 || !StringUtils::isUnicodeSpace(character))
                {
                    tokenRight = nextLetterX / contentScaleFactor;
                }
            }
            nextChangeSize = true;

            if (tokenHighestY < letterPosition.y)
                tokenHighestY = letterPosition.y;
            if (tokenLowestY > letterPosition.y - letterDef.height * _bmfontScale)
                tokenLowestY = letterPosition.y - letterDef.height * _bmfontScale;
        }

        if (newLine)
        {
            continue;
        }

        nextTokenX = nextLetterX;
        letterRight = tokenRight;
        if (highestY < tokenHighestY)
            highestY = tokenHighestY;
        if (lowestY > tokenLowestY)
            lowestY = tokenLowestY;
        if (longestLine < letterRight)
            longestLine = letterRight;

        index += tokenLen;
    }

    _linesWidth.push_back(letterRight);

    _numberOfLines = lineIndex + 1;
    _textDesiredHeight = (_numberOfLines * _lineHeight * _bmfontScale) / contentScaleFactor;
    if (_numberOfLines > 1)
        _textDesiredHeight += (_numberOfLines - 1) * _lineSpacing;
    Size contentSize(_labelWidth, _labelHeight);
    if (_labelWidth <= 0.f)
        contentSize.width = longestLine;
    if (_labelHeight <= 0.f)
        contentSize.height = _textDesiredHeight;
    setContentSize(contentSize);

    _tailoredTopY = contentSize.height;
    _tailoredBottomY = 0.f;
    if (highestY > 0.f)
        _tailoredTopY = contentSize.height + highestY;
    if (lowestY < -_textDesiredHeight)
        _tailoredBottomY = _textDesiredHeight + lowestY;

    return true;
}

bool Label::multilineTextWrapByWord()
{
    return multilineTextWrap(CC_CALLBACK_3(Label::getFirstWordLen, this));
}

bool Label::multilineTextWrapByChar()
{
    return multilineTextWrap(CC_CALLBACK_3(Label::getFirstCharLen, this));
}

bool Label::isVerticalClamp()
{
    if (_textDesiredHeight > _contentSize.height)
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool Label::isHorizontalClamp()
{
    bool letterClamp = false;
    for (int ctr = 0; ctr < _lengthOfString; ++ctr)
    {
        if (_lettersInfo[ctr].valid)
        {
            auto& letterDef = _fontAtlas->_letterDefinitions[_lettersInfo[ctr].utf32Char];

            auto px = _lettersInfo[ctr].positionX + letterDef.width/2 * _bmfontScale;
            auto lineIndex = _lettersInfo[ctr].lineIndex;

            if(_labelWidth > 0.f){
                if(!this->_enableWrap){
                    if (px > _contentSize.width) {
                        letterClamp = true;
                        break;
                    }
                }
                else{
                    auto wordWidth = this->_linesWidth[lineIndex];
                    if(wordWidth > this->_contentSize.width && (px > _contentSize.width)){
                        letterClamp = true;
                        break;
                    }

                }

            }
        }
    }

    return letterClamp;
}

void Label::shrinkLabelToContentSize(const std::function<bool(void)>& lambda)
{
    float fontSize = this->getRenderingFontSize();

    int i = 0;
    auto letterDefinition = _fontAtlas->_letterDefinitions;
    auto tempLetterDefinition = letterDefinition;
    float originalLineHeight = _lineHeight;
    bool flag = true;
    while (lambda()) {
        ++i;
        float newFontSize = fontSize - i;
        flag = false;
        if (newFontSize <= 0) {
            break;
        }
        float scale = newFontSize / fontSize;
        std::swap(_fontAtlas->_letterDefinitions, tempLetterDefinition);
        _fontAtlas->scaleFontLetterDefinition(scale);
        this->setLineHeight(originalLineHeight * scale);
        if (_maxLineWidth > 0.f && !_lineBreakWithoutSpaces)
        {
            multilineTextWrapByWord();
        }
        else
        {
            multilineTextWrapByChar();
        }
        computeAlignmentOffset();
        tempLetterDefinition = letterDefinition;
    }
    this->setLineHeight(originalLineHeight);
    std::swap(_fontAtlas->_letterDefinitions, letterDefinition);

    if (!flag) {
        if (fontSize - i >= 0) {
            this->scaleFontSizeDown(fontSize - i);
        }
    }
}

void Label::recordLetterInfo(const cocos2d::Vec2& point, char32_t utf32Char, int letterIndex, int lineIndex)
{
    if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
    {
        LetterInfo tmpInfo;
        _lettersInfo.push_back(tmpInfo);
    }
    _lettersInfo[letterIndex].lineIndex = lineIndex;
    _lettersInfo[letterIndex].utf32Char = utf32Char;
    _lettersInfo[letterIndex].valid = _fontAtlas->_letterDefinitions[utf32Char].validDefinition;
    _lettersInfo[letterIndex].positionX = point.x;
    _lettersInfo[letterIndex].positionY = point.y;
    _lettersInfo[letterIndex].atlasIndex = -1;
}

void Label::recordPlaceholderInfo(int letterIndex, char32_t utf32Char)
{
    if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
    {
        LetterInfo tmpInfo;
        _lettersInfo.push_back(tmpInfo);
    }
    _lettersInfo[letterIndex].utf32Char = utf32Char;
    _lettersInfo[letterIndex].valid = false;
}

NS_CC_END