Esempio n. 1
0
        /// <summary>Builds the descriptor internally.</summary>
        /// <returns>Controller information.</returns>
        protected virtual ControllerInfo <T> BuildDescriptorInternal()
        {
            var assembly = (typeof(T).IsGenericType) &&
                           (typeof(T).GetGenericArguments()[0].GetInterfaces().Contains(typeof(IController))) ?
                           typeof(T).GetGenericArguments()[0].Assembly : typeof(T).Assembly;
            var            globalRoutePrefix = assembly.GetCustomAttribute <RouteAttribute>();
            var            prefix            = GetControllerRoute();
            EntryPointInfo entryPoint        = null;

            if (globalRoutePrefix != null)
            {
                prefix     = new RouteAttribute(((HttpUrl)prefix.Url).InsertSegments(0, ((HttpUrl)globalRoutePrefix.Url).Segments).ToString());
                entryPoint = new EntryPointInfo(globalRoutePrefix.Url).WithSecurityDetailsFrom(assembly);
            }

            IList <OperationInfo> operations = new List <OperationInfo>();
            var methods = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                          .Except(typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                  .SelectMany(property => new[] { property.GetGetMethod(), property.GetSetMethod() }))
                          .Where(item => item.DeclaringType != typeof(object));

            foreach (var method in methods)
            {
                operations.AddRange(BuildMethodDescriptor(method, prefix));
            }

            return(new ControllerInfo <T>(entryPoint, prefix.Url, operations.ToArray()).WithSecurityDetailsFrom(typeof(T)));
        }
Esempio n. 2
0
        private void ScanForEntryPoints(LoadableClassInfo info)
        {
            var type = info.LoaderType;

            // Scan for entry points.
            foreach (var methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
            {
                var attr = methodInfo.GetCustomAttributes(typeof(TlcModule.EntryPointAttribute), false).FirstOrDefault() as TlcModule.EntryPointAttribute;
                if (attr == null)
                {
                    continue;
                }

                var entryPointInfo = new EntryPointInfo(methodInfo, attr,
                                                        methodInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false).FirstOrDefault() as ObsoleteAttribute);

                _entryPoints.Add(entryPointInfo);
                if (_entryPointMap.ContainsKey(entryPointInfo.Name))
                {
                    // Duplicate entry point name. We need to show a warning here.
                    // REVIEW: we will be able to do this once catalog becomes a part of env.
                    continue;
                }

                _entryPointMap[entryPointInfo.Name] = entryPointInfo;
            }

            // Scan for components.
            // First scan ourself, and then all nested types, for component info.
            ScanForComponents(type);
            foreach (var nestedType in type.GetTypeInfo().GetNestedTypes())
            {
                ScanForComponents(nestedType);
            }
        }
Esempio n. 3
0
 public Task <IQuantumMachineOutput <TOutput> > ExecuteAsync <TInput, TOutput>(
     EntryPointInfo <TInput, TOutput> info,
     TInput input,
     IQuantumMachineSubmissionContext submissionContext,
     IQuantumMachineExecutionContext executionContext,
     IQuantumMachine.ConfigureJob configureJobCallback) =>
 throw new NotSupportedException();
 //ExitInfo - номера клеток по вертикали, соответствующие входам и выходам из сектора
 // MapSize - размер карты в клетках
 //Cell - клетка, в конструктор передается CellType (Wall или Road)
 public Cell[][] getMapPrototype(EntryPointInfo pointInfo, MapSize mapSize)
 {
     /* туду:
      * Нужно запилить лабиринт c точками входа из pointInfo размерами из mapSize
      */
     throw new NotImplementedException();
 }
Esempio n. 5
0
        /// <summary>
        /// Submits a job to Azure Quantum.
        /// </summary>
        /// <typeparam name="TIn">The input type.</typeparam>
        /// <typeparam name="TOut">The output type.</typeparam>
        /// <param name="machine">The quantum machine target.</param>
        /// <param name="info">The information about the entry point.</param>
        /// <param name="input">The input argument tuple to the entry point.</param>
        /// <param name="settings">The submission settings.</param>
        /// <returns>The exit code.</returns>
        private static async Task <int> SubmitJob <TIn, TOut>(
            IQuantumMachine machine, EntryPointInfo <TIn, TOut> info, TIn input, AzureSettings settings)
        {
            try
            {
                var job = await machine.SubmitAsync(info, input, new SubmissionContext
                {
                    FriendlyName = settings.JobName,
                    Shots        = settings.Shots
                });

                DisplayJob(job, settings.Output);
                return(0);
            }
            catch (AzureQuantumException ex)
            {
                DisplayError(
                    "Something went wrong when submitting the program to the Azure Quantum service.",
                    ex.Message);
                return(1);
            }
            catch (QuantumProcessorTranslationException ex)
            {
                DisplayError(
                    "Something went wrong when performing translation to the intermediate representation used by the " +
                    "target quantum machine.",
                    ex.Message);
                return(1);
            }
        }
 public void Setup()
 {
     UrlParser.Register<RelativeUrlParser>();
     var controllerType = typeof(TestController);
     var operationUrl = "/api/test/operation";
     var methodInfo = controllerType.GetMethod("Operation");
     var entryPoint = new EntryPointInfo(UrlParser.Parse("/api")).WithSecurityDetailsFrom(controllerType.Assembly);
     _operationInfo = new FakeOperationInfo(methodInfo, UrlParser.Parse(operationUrl), null, new Regex(operationUrl)).WithSecurityDetailsFrom(methodInfo);
     new FakeControllerInfo(entryPoint, UrlParser.Parse("/api/test"), _operationInfo).WithSecurityDetailsFrom(controllerType);
 }
Esempio n. 7
0
        public void Setup()
        {
            UrlParser.Register <RelativeUrlParser>();
            var controllerType = typeof(TestController);
            var operationUrl   = "/api/test/operation";
            var methodInfo     = controllerType.GetMethod("Operation");
            var entryPoint     = new EntryPointInfo(UrlParser.Parse("/api")).WithSecurityDetailsFrom(controllerType.Assembly);

            _operationInfo = new FakeOperationInfo(methodInfo, UrlParser.Parse(operationUrl), null, new Regex(operationUrl)).WithSecurityDetailsFrom(methodInfo);
            new FakeControllerInfo(entryPoint, UrlParser.Parse("/api/test"), _operationInfo).WithSecurityDetailsFrom(controllerType);
        }
Esempio n. 8
0
 /// <summary>
 /// Validates the program for the quantum machine target.
 /// </summary>
 /// <typeparam name="TIn">The input type.</typeparam>
 /// <typeparam name="TOut">The output type.</typeparam>
 /// <param name="machine">The quantum machine target.</param>
 /// <param name="info">The information about the entry point.</param>
 /// <param name="input">The input argument tuple to the entry point.</param>
 /// <returns>The exit code.</returns>
 private static int Validate <TIn, TOut>(IQuantumMachine machine, EntryPointInfo <TIn, TOut> info, TIn input)
 {
     var(isValid, message) = machine.Validate(info, input);
     Console.WriteLine(isValid ? "✔️  The program is valid!" : "❌  The program is invalid.");
     if (!string.IsNullOrWhiteSpace(message))
     {
         Console.WriteLine();
         Console.WriteLine(message);
     }
     return(isValid ? 0 : 1);
 }
    public Cell[,] getMapPrototype(EntryPointInfo exitInfo, MapSize mapSize)
    {
        int width  = mapSize.Horizontal;
        int height = mapSize.Vertical;

        MazeCell[,] mazeCells               = MazeCellsGenerator((int)Math.Floor((mapSize.Horizontal - 1.0) / 2.0), (int)Math.Floor((mapSize.Vertical - 1.0) / 2.0));
        Cell[,] Map                         = MapFromMaze(mazeCells, height, width);
        Map[0, exitInfo.leftPoint]          = new Cell(CellType.Road);
        Map[width - 1, exitInfo.rightPoint] = new Cell(CellType.Road);
        Map = FindTheWay(Map, height, width, exitInfo);
        return(Map);
    }
    public Cell[,] getMapPrototype(EntryPointInfo exitInfo, MapSize mapSize)
    {
        int width  = mapSize.Horizontal;
        int height = mapSize.Vertical;

        Cell[,] cellMatrix = new Cell[width, height];
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                cellMatrix[i, j] = new Cell(CellType.Road);
            }
        }
        return(cellMatrix);
    }
Esempio n. 11
0
        private ModuleCatalog(IExceptionContext ectx)
        {
            Contracts.AssertValue(ectx);

            _entryPointMap = new Dictionary <string, EntryPointInfo>();
            _componentMap  = new Dictionary <string, ComponentInfo>();
            _components    = new List <ComponentInfo>();

            var moduleClasses = ComponentCatalog.FindLoadableClasses <SignatureEntryPointModule>();
            var entryPoints   = new List <EntryPointInfo>();

            foreach (var lc in moduleClasses)
            {
                var type = lc.LoaderType;

                // Scan for entry points.
                foreach (var methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
                {
                    var attr = methodInfo.GetCustomAttributes(typeof(TlcModule.EntryPointAttribute), false).FirstOrDefault() as TlcModule.EntryPointAttribute;
                    if (attr == null)
                    {
                        continue;
                    }

                    var info = new EntryPointInfo(ectx, methodInfo, attr,
                                                  methodInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false).FirstOrDefault() as ObsoleteAttribute);

                    entryPoints.Add(info);
                    if (_entryPointMap.ContainsKey(info.Name))
                    {
                        // Duplicate entry point name. We need to show a warning here.
                        // REVIEW: we will be able to do this once catalog becomes a part of env.
                        continue;
                    }

                    _entryPointMap[info.Name] = info;
                }

                // Scan for components.
                // First scan ourself, and then all nested types, for component info.
                ScanForComponents(ectx, type);
                foreach (var nestedType in type.GetTypeInfo().GetNestedTypes())
                {
                    ScanForComponents(ectx, nestedType);
                }
            }
            _entryPoints = entryPoints.ToArray();
        }
Esempio n. 12
0
    private Cell[,] FindTheWay(Cell[,] Map, int _height, int _width, EntryPointInfo exitInfo)
    {
        int res = 0;

        for (int i = 0; i < _height; i++)
        {
            if (exitInfo.leftPoint + i < _height && Map[1, exitInfo.leftPoint + i].Type == CellType.Road)
            {
                res = i;
                break;
            }
            if (exitInfo.leftPoint - i >= 0 && Map[1, exitInfo.leftPoint - i].Type == CellType.Road)
            {
                res = -i;
                break;
            }
        }
        while (res != 0)
        {
            Map[0, exitInfo.leftPoint + res] = new Cell(CellType.Road);
            res = res + (-res / Math.Abs(res));
        }
        for (int i = 0; i < _height; i++)
        {
            if (exitInfo.rightPoint + i < _height && Map[_width - 2, exitInfo.rightPoint + i].Type == CellType.Road)
            {
                res = i;
                break;
            }
            if (exitInfo.rightPoint - i >= 0 && Map[_width - 2, exitInfo.rightPoint - i].Type == CellType.Road)
            {
                res = -i;
                break;
            }
        }
        while (res != 0)
        {
            Map[_width - 1, exitInfo.rightPoint + res] = new Cell(CellType.Road);
            res = res + (-res / Math.Abs(res));
        }
        return(Map);
    }
Esempio n. 13
0
        /// <summary>
        /// Submits the entry point to Azure Quantum.
        /// </summary>
        /// <typeparam name="TIn">The entry point's argument type.</typeparam>
        /// <typeparam name="TOut">The entry point's return type.</typeparam>
        /// <param name="info">The information about the entry point.</param>
        /// <param name="input">The input argument tuple to the entry point.</param>
        /// <param name="settings">The submission settings.</param>
        /// <returns>The exit code.</returns>
        public static async Task <int> Submit <TIn, TOut>(EntryPointInfo <TIn, TOut> info, TIn input, AzureSettings settings)
        {
            if (settings.Verbose)
            {
                Console.WriteLine(settings);
                Console.WriteLine();
            }

            var machine = CreateMachine(settings);

            if (machine is null)
            {
                DisplayWithColor(ConsoleColor.Red, Console.Error,
                                 $"The target '{settings.Target}' was not recognized.");
                return(1);
            }

            return(settings.DryRun
                ? Validate(machine, info, input)
                : await SubmitJob(machine, info, input, settings));
        }
Esempio n. 14
0
    public Map CreateMap(EntryPointInfo entryPointInfo, MapSize mapSize, IMapGenerator generator)
    {
        var   MapPrototype = generator.getMapPrototype(entryPointInfo, mapSize);
        float x            = transform.position.x;
        float y            = transform.position.y;

        for (int i = 0; i < mapSize.Horizontal; i++)
        {
            for (int j = 0; j < mapSize.Vertical; j++)
            {
                GameObject gameObject = Cells.First(g => g.name == MapPrototype[i, j].getTypeName());
                Instantiate(gameObject, new Vector3(x + i * SpriteSize.x, y + j * SpriteSize.y), Quaternion.identity, transform);
            }
        }
        CreateItems(MapPrototype, mapSize);
        MapInfo.mapPrototype   = MapPrototype;
        MapInfo.entryPointInfo = entryPointInfo;
        MapInfo.MapSize        = mapSize;
        MapInfo.Width          = mapSize.Horizontal * SpriteSize.x;
        MapInfo.Height         = mapSize.Vertical * SpriteSize.y;
        return(MapInfo);
    }
Esempio n. 15
0
    public void AddNewMap()
    {
        GameObject     newMap  = Instantiate(MapObject, startVector, Quaternion.identity, transform);
        MapSize        mapSize = new MapSize(defaultMapSize.Horizontal, defaultMapSize.Vertical);
        EntryPointInfo entryPointInfo;
        int            startPos;
        int            endPos;

        if (lastMap == null)
        {
            startPos = Random.Range(2, mapSize.Vertical - 1);
        }
        else
        {
            startPos = lastMap.entryPointInfo.rightPoint;
        }
        endPos         = Random.Range(2, mapSize.Vertical - 1);
        entryPointInfo = new EntryPointInfo(startPos, endPos);
        MapController mapController = newMap.GetComponent <MapController>();

        lastMap = mapController.CreateMap(entryPointInfo, mapSize, generator);
        Maps.Add(lastMap);
        startVector += new Vector2(lastMap.Width, 0);
    }
Esempio n. 16
0
 internal FakeControllerInfo(EntryPointInfo entryPoint, Url url, params OperationInfo[] operations)
     : base(entryPoint, url, operations)
 {
 }
Esempio n. 17
0
 public Task <IQuantumMachineJob> SubmitAsync <TIn, TOut>(
     EntryPointInfo <TIn, TOut> entryPoint, TIn argument, SubmissionOptions options) =>
 Task.FromResult <IQuantumMachineJob>(new ExampleJob());
Esempio n. 18
0
 public string?Validate <TIn, TOut>(EntryPointInfo <TIn, TOut> entryPoint, TIn argument) => null;
Esempio n. 19
0
 public Task <IQuantumMachineJob> SubmitAsync <TInput, TOutput>(
     EntryPointInfo <TInput, TOutput> info,
     TInput input,
     IQuantumMachineSubmissionContext submissionContext,
     IQuantumMachine.ConfigureJob configureJobCallback) =>
 SubmitAsync(info, input);
Esempio n. 20
0
 public Task <IQuantumMachineJob> SubmitAsync <TInput, TOutput>(
     EntryPointInfo <TInput, TOutput> info, TInput input) =>
 Task.FromResult <IQuantumMachineJob>(new DefaultJob());
 internal FakeControllerInfo(EntryPointInfo entryPoint, Url url, params OperationInfo[] operations)
     : base(entryPoint, url, operations)
 {
 }
Esempio n. 22
0
 public Task <IQuantumMachineJob> SubmitAsync <TInput, TOutput>(
     EntryPointInfo <TInput, TOutput> info, TInput input) =>
 throw new AzureQuantumException("This quantum machine always has an error.");
Esempio n. 23
0
        public Task <IQuantumMachineJob> SubmitAsync(IQuantumMachine machine, AzureSubmissionContext submissionContext)
        {
            var parameterTypes  = new List <Type>();
            var parameterValues = new List <object>();

            foreach (var parameter in OperationInfo.RoslynParameters)
            {
                if (!submissionContext.InputParameters.ContainsKey(parameter.Name))
                {
                    throw new ArgumentException($"Required parameter {parameter.Name} was not specified.");
                }

                string rawParameterValue = submissionContext.InputParameters[parameter.Name];
                try
                {
                    var parameterValue = submissionContext.InputParameters.DecodeParameter(parameter.Name, type: parameter.ParameterType);

                    if (parameterValue != null)
                    {
                        parameterTypes.Add(parameter.ParameterType);
                        parameterValues.Add(parameterValue);
                    }
                }
                catch (Exception e)
                {
                    throw new ArgumentException($"The value {rawParameterValue} provided for parameter {parameter.Name} could not be converted to the expected type: {e.Message}");
                }
            }

            var entryPointInput = parameterValues.Count switch
            {
                0 => QVoid.Instance,
                1 => parameterValues.Single(),
                _ => InputType.GetConstructor(parameterTypes.ToArray()).Invoke(parameterValues.ToArray())
            };

            // Find and invoke the method on IQuantumMachine that is declared as:
            // Task<IQuantumMachineJob> SubmitAsync<TInput, TOutput>(EntryPointInfo<TInput, TOutput> info, TInput input, SubmissionContext context)
            var submitMethod = typeof(IQuantumMachine)
                               .GetMethods()
                               .Single(method =>
                                       method.Name == "SubmitAsync" &&
                                       method.IsGenericMethodDefinition &&
                                       method.GetParameters().Length == 3 &&
                                       method.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == EntryPointInfo.GetType().GetGenericTypeDefinition() &&
                                       method.GetParameters()[1].ParameterType.IsGenericMethodParameter &&
                                       method.GetParameters()[2].ParameterType == typeof(IQuantumMachineSubmissionContext))
                               .MakeGenericMethod(new Type[] { InputType, OutputType });
            var submitParameters = new object[] { EntryPointInfo, entryPointInput, submissionContext };

            return((Task <IQuantumMachineJob>)submitMethod.Invoke(machine, submitParameters));
        }
    }
Esempio n. 24
0
 public Task <IQuantumMachineOutput <TOutput> > ExecuteAsync <TInput, TOutput>(
     EntryPointInfo <TInput, TOutput> info,
     TInput input,
     IQuantumMachineExecutionContext executionContext) =>
 throw new NotSupportedException();
Esempio n. 25
0
 internal bool TryFindEntryPoint(string name, out EntryPointInfo entryPoint)
 {
     Contracts.CheckNonEmpty(name, nameof(name));
     return(_entryPointMap.TryGetValue(name, out entryPoint));
 }
Esempio n. 26
0
 /// <summary>
 /// Creates a Q# entry point submission.
 /// </summary>
 /// <param name="entryPointInfo">The entry point info.</param>
 /// <param name="argument">The entry point argument.</param>
 public QSharpSubmission(EntryPointInfo <TIn, TOut> entryPointInfo, TIn argument) =>
 (this.EntryPointInfo, this.Argument) = (entryPointInfo, argument);