コード例 #1
0
		public GenerateSettingsWizard(IGenerator generator, List<Type> generatorTypeList)
			: this()
		{
			//Only show this the first time if never generated
			var cacheFile = new ModelCacheFile(generator);
			if (cacheFile.FileExists())
			{
				this.DialogResult = DialogResult.Cancel;
				this.IsValid = false;
				return;
			}

			_generatorTypeList = generatorTypeList;

			//Load all wizard files
			var xmlFileList = Directory.GetFiles(AddinAppData.Instance.ExtensionDirectory, "genwizard.*.xml");
			foreach (var fileName in xmlFileList)
			{
				this.LoadWizardFile(fileName);
			}

			if (cboItem.Items.Count == 0)
			{
				this.DialogResult = DialogResult.Cancel;
				this.IsValid = false;
				return;
			}

			cboItem.SelectedIndex = 0;

		}
コード例 #2
0
ファイル: Import.cs プロジェクト: raysearchlabs/spark
 public Import(ILocalhost localhost, IGenerator generator)
 {
     this.localhost = localhost;
     this.generator = generator;
     mapper = new Mapper<Key, Key>();
     interactions = new List<Interaction>();
 }
コード例 #3
0
ファイル: Generator.cs プロジェクト: sheigl/mustache-sharp
 /// <summary>
 /// Initializes a new instance of a Generator.
 /// </summary>
 /// <param name="generator">The text generator to wrap.</param>
 internal Generator(IGenerator generator)
 {
     _generator = generator;
     _foundHandlers = new List<EventHandler<KeyFoundEventArgs>>();
     _notFoundHandlers = new List<EventHandler<KeyNotFoundEventArgs>>();
     _valueRequestedHandlers = new List<EventHandler<ValueRequestEventArgs>>();
 }
コード例 #4
0
ファイル: Program.cs プロジェクト: uonun/Whois
        private static void GenerateWithWatch(IGenerator g)
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("\r\n{0}: ", g);
            Console.ResetColor();
            Console.Write("Working...\r\n");

            List<string> result = null;
            var sw = new Stopwatch();
            var total = 0L;
            for (int i = 0;i < _loop;i++)
            {
                sw.Reset();
                sw.Start();
                result = g.Generate(DIC, _len);
                sw.Stop();
                total += sw.ElapsedMilliseconds;
                if (i <= 10)
                {
                    Console.WriteLine("\tGot {0} items in {1,7}ms", result.Count, sw.ElapsedMilliseconds);
                    if (i == 10 && _loop > 10)
                    {
                        Console.WriteLine("\t......");
                    }
                }
            }
            Console.WriteLine("\tGenerate finished for {2} times in {0,7}ms, {1,7}ms for each time.", total, total / _loop, _loop);
            if (result != null)
            {
                PrintTheResult(result);
            }
        }
コード例 #5
0
        private void btnScramble_Click(object sender, RoutedEventArgs e)
        {
            Generator = new Shuffle(Math.Sqrt(3) / 3, 6, 18, Convert.ToInt32(tb_amounttests.Text));
			var frequencies = Generator.FrequenciesTest();
			lb_Scramble.ItemsSource = frequencies;
			tb_scrhi.Text = Generator.CriterionX(frequencies).ToString();
        }
コード例 #6
0
		public void Setup()
		{
			ccu = new CodeCompileUnit();
			mocks = new MockRepository();
			engine = Engine.GlobalEngine;
			engine.BinPath = @"C:\Program Files (x86)\MSBuild";
			project = new Project();
			buildEngine = mocks.DynamicMock<MockBuildEngine>(project);

			logger = new NullLogger();
			parserService = mocks.DynamicMock<ISiteTreeGeneratorService>();
			naming = mocks.DynamicMock<INamingService>();
			sourceStorage = mocks.DynamicMock<IParsedSourceStorageService>();
			source = mocks.DynamicMock<ISourceGenerator>();
			typeResolver = mocks.DynamicMock<ITypeResolver>();
			treeService = mocks.DynamicMock<ITreeCreationService>();
			viewSourceMapper = mocks.DynamicMock<IViewSourceMapper>();
			generator = mocks.DynamicMock<IGenerator>();

			task = new GenerateMonoRailSiteTreeTask(logger, parserService, naming, source, sourceStorage, typeResolver,
			                                         treeService, viewSourceMapper, generator);

			item = mocks.DynamicMock<ITaskItem>();
			parsedSource = mocks.DynamicMock<IParser>();
		}
コード例 #7
0
ファイル: Field.cs プロジェクト: cry-inc/mahjong
 public Field(IGenerator generator)
 {
     _generator = generator;
     _generator.Generate(this);
     if (_tiles == null || _types == null)
         throw new Exception("Generator failed. Tiles or TileTypes missing!");
 }
コード例 #8
0
 public DiscoTask(Settings settings, IGenerator<amBXScene> randomSceneGenerator, NotificationClientBase notificationService, Random random)
 {
     this.settings = settings;
       this.randomSceneGenerator = randomSceneGenerator;
       this.notificationService = notificationService;
       this.random = random;
 }
コード例 #9
0
ファイル: Toolchain.cs プロジェクト: omariom/BenchmarkDotNet
 public Toolchain(string name, IGenerator generator, IBuilder builder, IExecutor executor)
 {
     Name = name;
     Generator = generator;
     Builder = builder;
     Executor = executor;
 }
コード例 #10
0
        public HelloWorldController(IGenerator generator)
        {
            if (generator == null)
                throw new ArgumentNullException("generator");

            _Generator = generator;
        }
コード例 #11
0
ファイル: ContinuityTests.cs プロジェクト: TreeSeed/Tychaia
 public void PerformSampling(string name, IGenerator layer)
 {
     PerformSamplingIndividual(name, layer, 5, 0);
     PerformSamplingIndividual(name, layer, 5, 100);
     PerformSamplingIndividual(name, layer, 5, 10000);
     PerformSamplingIndividual(name, layer, 5, 10000000);
 }
コード例 #12
0
 public VertexSourceAdapter(IVertexSource vertexSource, IGenerator generator)
 {
     markers = new null_markers();
     this.VertexSource = vertexSource;
     this.generator = generator;
     m_status = status.initial;
 }
コード例 #13
0
ファイル: Learner.cs プロジェクト: budbjames/numl
        /// <summary>
        /// Trains a single model based on a generator
        /// a predefined number of times with the provided
        /// examples and data split and selects the best 
        /// (or most accurate) model
        /// </summary>
        /// <param name="examples">Source data</param>
        /// <param name="trainingPercentage">Data split percentage</param>
        /// <param name="repeat">Number of repetitions per generator</param>
        /// <param name="generator">Model generator used</param>
        /// <returns>Best model for provided generator</returns>
        public static LearningModel Learn(IEnumerable<object> examples, double trainingPercentage, int repeat, IGenerator generator)
        {
            var total = examples.Count();
            var descriptor = generator.Descriptor;
            var data = descriptor.Convert(examples).ToExamples();

            Matrix x = data.Item1;
            Vector y = data.Item2;

            var models = new IModel[repeat];
            var accuracy = Vector.Zeros(repeat);

            // run in parallel since they all have
            // read-only references to the data model
            // and update indices independently
            Parallel.For(0, models.Length, i =>
            {
                var t = GenerateModel(generator, x, y, examples, trainingPercentage);
                models[i] = t.Model;
                accuracy[i] = t.Accuracy;
            });

            var idx = accuracy.MaxIndex();

            return new LearningModel { Generator = generator, Model = models[idx], Accuracy = accuracy[idx] };
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: ktj007/mmo
        public static void Main(string[] args)
        {
            var targetDirectory = Path.GetFullPath(args.Length > 0 ? args[0] : ".");
            var outputDirectory = Path.GetFullPath(args.Length > 1 ? args[1] : ".");
            var options = args.Length > 2 ? args[2] : "";

            if (!Directory.Exists(targetDirectory))
                return;

            if (!Directory.Exists(outputDirectory))
                MiscUtil.CreateDirectory(outputDirectory);

            var generators = new IGenerator[]
                {
                    new MessageCodeGenerator(outputDirectory, options),
                    new DataCodeGenerator(outputDirectory),
                    new AttributeCodeGenerator(outputDirectory)
                };

            var targetFiles = Directory.GetFiles(targetDirectory, "*.xml", SearchOption.AllDirectories);
            Parallel.ForEach(targetFiles, eachFile =>
                {
                    var document = new XmlDocument();
                    document.Load(eachFile);

                    Parallel.ForEach(generators, e => e.Load(eachFile, document));
                });

            Parallel.ForEach(generators, e => e.Generate());
        }
コード例 #15
0
 ///<summary>
 ///</summary>
 ///<param name="source"></param>
 ///<param name="generator"></param>
 public ConverterAdaptorVcgen(IVertexSource source, IGenerator generator)
 {
     _markers = new NullMarkers();
     _source = source;
     _generator = generator;
     _status = EStatus.Initial;
 }
コード例 #16
0
        private void BuildBuffers(IGenerator generator)
        {
            List<MyOwnVertexFormat> vertices = new List<MyOwnVertexFormat>();

            for (int x = 0; x < sideSize; x++)
            {
                for (int z = 0; z < sideSize; z++)
                {

                    for (int y = 0; y < sideSize; y++)
                    {
                        double sample = generator.Sample(new Vector3(x, y, z) + location);
                        if ( sample > 0.6f)
                        {
                            CreateVertices(vertices, x, y, z, new Color((float)sample, (float)sample, (float)sample));
                        }

                    }
                }
            }

            if(vertices.Count > 0)
            {
                vertexBuffer = new VertexBuffer(device, MyOwnVertexFormat.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
                vertexBuffer.SetData(vertices.ToArray());
            }

            numVertices = vertices.Count;
        }
コード例 #17
0
 public void Emit(IGenerator codeEmittor)
 {
     foreach(var i in _instructions)
     {
         i.Emit(codeEmittor);
     }
 }
コード例 #18
0
ファイル: Program.cs プロジェクト: zoran-horvat/parsing-demos
        private static void ProcessTree(Option<IAbstractSyntaxTree> ast, IGenerator generator)
        {
            if (!ast.Any())
                return;

            generator.Process(ast.Single());
        }
コード例 #19
0
        private void btnAnalytic_Click(object sender, RoutedEventArgs e)
        {
            Generator = new Analytic(18, 17, 8, 1, Convert.ToInt32(tb_amounttests.Text));
           	var frequencies = Generator.FrequenciesTest();
			lB_Analytic.ItemsSource = frequencies;
			tb_anhi.Text = Generator.CriterionX(frequencies).ToString();
        }
コード例 #20
0
        public void AddFile(string fullPath, IGenerator generator)
        {
            var path = System.IO.Path.Combine(Environment.CurrentDirectory, fullPath);

            var item = new GeneratedItem(path, x => File.WriteAllText(path, generator.GetText()), File.Exists);

            Items.Add(item);
        }
コード例 #21
0
 public MD5CollisionCalculator()
 {
     _generator = new Generator();
     _workerPool = new List<IWorker>();
     _nrOfWorkerTasks = 0;
     _passCount = 0;
     _running = false;
 }
コード例 #22
0
 public MaintenanceService(Infrastructure infrastructure, FhirService service)
 {
     this.service = service;
     this.localhost = infrastructure.Localhost;
     this.generator = infrastructure.Generator;
     this.store = infrastructure.Store;
     this.index = infrastructure.Index;
 }
コード例 #23
0
 public GeneratingLeafNode(GraphicsDevice device, IGenerator generator, Vector3 pos, int size)
 {
     this.device = device;
     location = pos;
     sideSize = size;
     boundingBoxes = new List<BoundingBox>();
     BuildBuffers(generator);
 }
コード例 #24
0
ファイル: ConvAdaptorVcgen.cs プロジェクト: Kintaro/Pictor
 public ConvAdaptorVcgen(IVertexSource source, IGenerator generator)
 {
     this.markers = null;
     // TODO NullMarkers();
     this.source = source;
     this.generator = generator;
     this.status = Status.Initial;
 }
コード例 #25
0
ファイル: MaintenanceService.cs プロジェクト: Condeti/spark
 public MaintenanceService(FhirService fhirService, ILocalhost localhost, IGenerator keyGenerator, IFhirStore fhirStore, IFhirIndex fhirIndex)
 {
     this.fhirService = fhirService;
     this.localhost = localhost;
     this.keyGenerator = keyGenerator;
     this.fhirStore = fhirStore;
     this.fhirIndex = fhirIndex;
 }
コード例 #26
0
ファイル: ChunkCache.cs プロジェクト: bobtwinkles/Defence
 public ChunkCache(IGenerator Source)
 {
     _chunks = new Chunk[NUM_CHUNKS][];
     for (int i = 0; i< _chunks.Length; ++i) {
         _chunks [i] = new Chunk[NUM_CHUNKS];
     }
     _gen = Source;
 }
コード例 #27
0
ファイル: UserControl1.cs プロジェクト: BenHall/ExtendViaMEF
 public void Display(IGenerator generator)
 {
     textBox1.Text = string.Empty;
         foreach (object o in generator.Get())
         {
             textBox1.Text += o + Environment.NewLine;
         }
 }
コード例 #28
0
ファイル: FormGenerator.cs プロジェクト: filipkunc/GLGraphics
        private void darkListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            currentGenerator = darkListBox1.SelectedItem as IGenerator;

            if (currentGenerator != null)
            {
                UpdateControls();
            }
        }
コード例 #29
0
        public void Register(Type type, IGenerator generator)
        {
            if(_generators.Has(type))
            {
                _generators.Remove(type);
            }

            _generators.Fill(type, generator);
        }
コード例 #30
0
ファイル: ModelCacheFile.cs プロジェクト: nHydrate/nHydrate
        public ModelCacheFile(IGenerator root)
            : this()
        {
            if (root == null)
                throw new Exception("The root element cannot be null");

            _modelFileName = root.FileName;
            this.Load();
        }
コード例 #31
0
 public void ReplaceGenerator <T> (IGenerator <T> generator)
 {
     generators[typeof(T)] = generator;
     generators[typeof(Nullable <>).MakeGenericType(typeof(T))] = new NullableGenerator <T>(generator);
 }
コード例 #32
0
        /// <summary>
        /// Generates source code for the specified test case, assembles it, and compares
        /// the output of both steps to expected values.  The process is repeated for every
        /// known assembler.
        ///
        /// If an assembler is known but not configured, the assembly step is skipped, and
        /// does not count as a failure.
        /// </summary>
        /// <param name="pathName">Full path to test case.</param>
        /// <returns>True if all assemblers worked as expected.</returns>
        private bool GenerateAndAssemble(string pathName)
        {
            ReportProgress(Path.GetFileName(pathName) + "...\r\n");

            // Create DisasmProject object, either as a new project for a plain data file,
            // or from a project file.
            DisasmProject project = InstantiateProject(pathName,
                                                       out FileLoadReport projectLoadReport);

            if (project == null)
            {
                ReportFailure();
                return(false);
            }

            int testNum = GetTestNum(pathName);

            // Create a temporary directory to work in.
            string workDir = CreateWorkDirectory(pathName);

            if (string.IsNullOrEmpty(workDir))
            {
                ReportFailure();
                project.Cleanup();
                return(false);
            }

            AppSettings settings = CreateNormalizedSettings();

            ApplyProjectSettings(settings, project);

            // Iterate through all known assemblers.
            bool didFail = false;

            foreach (AssemblerInfo.Id asmId in
                     (AssemblerInfo.Id[])Enum.GetValues(typeof(AssemblerInfo.Id)))
            {
                if (asmId == AssemblerInfo.Id.Unknown)
                {
                    continue;
                }

                string    fileName = Path.GetFileName(pathName);
                TaskTimer timer    = new TaskTimer();
                timer.StartTask("Full Test Duration");

                // Create results object and add it to the list.  We'll add stuff to it for
                // as far as we get.
                GenTestResults results = new GenTestResults(pathName, asmId);
                mResults.Add(results);
                results.ProjectLoadReport = projectLoadReport;

                // Generate source code.
                ReportProgress("  " + asmId.ToString() + " generate...");
                IGenerator gen = AssemblerInfo.GetGenerator(asmId);
                if (gen == null)
                {
                    ReportErrMsg("generator unavailable");
                    ReportProgress("\r\n");
                    //didFail = true;
                    continue;
                }
                timer.StartTask("Generate Source");
                gen.Configure(project, workDir, fileName,
                              AssemblerVersionCache.GetVersion(asmId), settings);
                List <string> genPathNames = gen.GenerateSource(mWorker);
                timer.EndTask("Generate Source");
                if (mWorker.CancellationPending)
                {
                    // The generator will stop early if a cancellation is requested.  If we
                    // don't break here, the compare function will report a failure, which
                    // isn't too problematic but looks funny.
                    break;
                }

                ReportProgress(" verify...");
                timer.StartTask("Compare Source to Expected");
                bool match = CompareGeneratedToExpected(pathName, genPathNames);
                timer.EndTask("Compare Source to Expected");
                if (match)
                {
                    ReportSuccess();
                    results.GenerateOkay = true;
                }
                else
                {
                    ReportFailure();
                    didFail = true;

                    // The fact that it doesn't match the expected sources doesn't mean it's
                    // invalid.  Go ahead and try to build it.
                    //continue;
                }

                // Assemble code.
                ReportProgress("  " + asmId.ToString() + " assemble...");
                IAssembler asm = AssemblerInfo.GetAssembler(asmId);
                if (asm == null)
                {
                    ReportErrMsg("assembler unavailable");
                    ReportProgress("\r\n");
                    continue;
                }

                timer.StartTask("Assemble Source");
                asm.Configure(genPathNames, workDir);
                AssemblerResults asmResults = asm.RunAssembler(mWorker);
                timer.EndTask("Assemble Source");
                if (asmResults == null)
                {
                    ReportErrMsg("unable to run assembler");
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                if (asmResults.ExitCode != 0)
                {
                    ReportErrMsg("assembler returned code=" + asmResults.ExitCode);
                    ReportFailure();
                    didFail = true;
                    continue;
                }

                results.AsmResults = asmResults;

                ReportProgress(" verify...");
                timer.StartTask("Compare Binary to Expected");
                FileInfo fi = new FileInfo(asmResults.OutputPathName);
                if (fi.Length != project.FileData.Length)
                {
                    ReportErrMsg("asm output mismatch: length is " + fi.Length + ", expected " +
                                 project.FileData.Length);
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                else if (!FileUtil.CompareBinaryFile(project.FileData, asmResults.OutputPathName,
                                                     out int badOffset, out byte badFileVal))
                {
                    ReportErrMsg("asm output mismatch: offset +" + badOffset.ToString("x6") +
                                 " has value $" + badFileVal.ToString("x2") + ", expected $" +
                                 project.FileData[badOffset].ToString("x2"));
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                timer.EndTask("Compare Binary to Expected");

                // Victory!
                results.AssembleOkay = true;
                ReportSuccess();

                timer.EndTask("Full Test Duration");
                results.Timer = timer;

                // We don't scrub the directory on success at this point.  We could, but we'd
                // need to remove only those files associated with the currently assembler.
                // Otherwise, a failure followed by a success would wipe out the unsuccessful
                // temporaries.
            }

            // If something failed, leave the bits around for examination.  Otherwise, try to
            // remove the directory and all its contents.
            if (!didFail && !RetainOutput)
            {
                ScrubWorkDirectory(workDir, testNum);
                RemoveWorkDirectory(workDir);
            }

            project.Cleanup();
            return(!didFail);
        }
コード例 #33
0
 protected override CauchyDistribution GetDistWithParams(IGenerator gen, CauchyDistribution other = null)
 {
     return(new CauchyDistribution(gen, GetAlpha(other), GetGamma(other)));
 }
コード例 #34
0
 /// <summary>
 /// Constructs a new TransformGenerator that generates elements from the given generator, transformed
 /// by the given transform.
 /// </summary>
 /// <param Name="generator">The generator to use for generating elements</param>
 /// <param Name="transform">The transform to apply to generated elements before they are returned.</param>
 public TransformGenerator(IGenerator <U> generator, Func <U, T> transform)
 {
     this.generator = generator;
     this.transform = transform;
 }
コード例 #35
0
 public static IGenerator <T> Select <T, U>(this IGenerator <U> generator, Func <U, T> transform)
 {
     return(new TransformGenerator <T, U>(generator, transform));
 }
コード例 #36
0
 public static IGenerator <T> Where <T>(this IGenerator <T> generator, Func <T, bool> predicate)
 {
     return(new FilterGenerator <T>(generator, predicate));
 }
コード例 #37
0
        static void Main(string[] args)
        {
            var generators = new IGenerator[]
            {
                new ProjectsGenerator(),
                new ProtoGenerator(),
                new MessageGenerator()
            };

            List <CybtansConfig> configs = null;

            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Generate code from config files: cybtans-cli [base path]");
                Console.WriteLine("Other options:");
                foreach (var item in generators)
                {
                    Console.WriteLine();
                    item.PrintHelp();
                }
                return;
            }
            else if (args.Length == 1)
            {
                configs = CybtansConfig.SearchConfigs(args[0]).ToList();
                if (configs.Count == 0)
                {
                    Console.WriteLine("No \"cybtans.json\" config files were found");
                    return;
                }
            }

            try
            {
                if (configs != null && configs.Any())
                {
                    foreach (var config in configs)
                    {
                        foreach (var step in config.Steps)
                        {
                            foreach (var item in generators)
                            {
                                if (item.Generate(config, step))
                                {
                                    break;
                                }
                            }
                        }
                    }

                    return;
                }


                foreach (var item in generators)
                {
                    if (item.CanGenerate(args[0]) && item.Generate(args))
                    {
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;

                var ex = e;
                while (ex != null)
                {
                    Console.WriteLine(ex.Message);
                    ex = ex.InnerException;
                }
                Console.ResetColor();
            }
        }
コード例 #38
0
ファイル: Generator.cs プロジェクト: traviolia/IronScheme
        protected internal static Expression GetAst(object args, CodeBlock cb, bool istailposition)
        {
            var spanHint = SpanHint;

            if (args is Annotation)
            {
                args = ((Annotation)args).stripped;
            }
            Cons c = args as Cons;

            if (c != null)
            {
                // in debug mode, this will be (annotated-call <location> . symbol)
                // TODO: see if the discarded annotation is useful
                if (ScriptDomainManager.Options.DebugMode && c.car is Cons)
                {
                    Cons ac = c.car as Cons;
                    if (ac.car == SymbolTable.StringToObject("annotated-call"))
                    {
                        object se = ((Cons)ac.cdr).cdr;
                        if (se is SymbolId)
                        {
                            c.car = se;
                        }
                    }
                }

                if (c.car is SymbolId)
                {
                    SymbolId f = (SymbolId)c.car;

                    Variable var = cb.Lookup(f);

                    if (var != null && !assigns.ContainsKey(f))
                    {
                        var = null;
                    }

                    object m;

#if OPTIMIZATIONS
#if !BLAH
                    CodeBlockExpression cbe;

                    //// needs to do the same for overloads...
                    if (SimpleGenerator.libraryglobals.TryGetValue(f, out cbe))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            //inline here? we could for simple bodies, but we need to copy the entire structure
                            if (!(cbe.Block.HasEnvironment || cbe.Block.IsClosure))
                            {
                                if (cbe.Block.Body is ReturnStatement)
                                {
                                    ReturnStatement rs = (ReturnStatement)cbe.Block.Body;

                                    if (!cb.IsGlobal && IsSimpleExpression(rs.Expression))
                                    {
                                        return(InlineCall(cb, Ast.CodeBlockExpression(RewriteBody(cbe.Block), false, cbe.IsStronglyTyped), ppp));
                                    }
                                }
                            }
                            if (cbe.Block != cb.Parent && cbe.Block != cb) // do TCE later
                            {
                                return(CallNormal(cbe, ppp));
                            }
                        }
                    }

                    // varargs
                    if (SimpleGenerator.libraryglobalsX.TryGetValue(f, out cbe))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount - 1 <= ppp.Length)
                        {
                            //inline here?
                            return(CallVarArgs(cbe, ppp));
                        }
                    }

                    // overloads
                    CodeBlockDescriptor[] cbd;
                    if (SimpleGenerator.libraryglobalsN.TryGetValue(f, out cbd))
                    {
                        Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        foreach (CodeBlockDescriptor d in cbd)
                        {
                            if (d.codeblock.Block.ParameterCount < 9)
                            {
                                if (ppp.Length == d.arity || (d.varargs && ppp.Length > d.arity))
                                {
                                    if (d.varargs)
                                    {
                                        //inline here?
                                        return(CallVarArgs(d.codeblock, ppp));
                                    }
                                    else
                                    {
                                        //inline here?
                                        //if (d.codeblock.Block != cb.Parent && d.codeblock.Block != cb) // do TCE later, not yet
                                        {
                                            return(CallNormal(d.codeblock, ppp));
                                        }
                                    }
                                }
                            }
                        }
                    }
#endif

                    //if (!ScriptDomainManager.Options.DebugMode)
                    {
                        if (f == SymbolTable.StringToId("call-with-values"))
                        {
                            Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb);
                            if (ppp.Length == 2 && ppp[1] is MethodCallExpression)
                            {
                                MethodCallExpression consumer = ppp[1] as MethodCallExpression;

                                if (ppp[0] is MethodCallExpression)
                                {
                                    MethodCallExpression producer = ppp[0] as MethodCallExpression;
                                    if (consumer.Method == Closure_Make && producer.Method == Closure_Make)
                                    {
                                        CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression;
                                        CodeBlockExpression pcbe = producer.Arguments[0] as CodeBlockExpression;

                                        pcbe.Block.Bind();
                                        ccbe.Block.Bind();

                                        if (ccbe.Block.ParameterCount == 0)
                                        {
                                            return(InlineCall(cb, ccbe));
                                        }
                                        else if (ccbe.Block.ParameterCount == 1)
                                        {
                                            return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), InlineCall(cb, pcbe))));
                                        }
                                        else
                                        {
                                            Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[]));

                                            Expression valuesarr = Ast.Read(values);

                                            Expression[] pppp = new Expression[ccbe.Block.ParameterCount];

                                            for (int i = 0; i < pppp.Length; i++)
                                            {
                                                pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i));
                                            }

                                            return(Ast.Comma(
                                                       Ast.Void(
                                                           Ast.Write(
                                                               values,
                                                               Ast.ComplexCallHelper(
                                                                   Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"), InlineCall(cb, pcbe)),
                                                                   typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }),
                                                                   Ast.Constant(pppp.Length)))),
                                                       InlineCall(cb, ccbe, pppp)));
                                        }
                                    }
                                }
                                if (consumer.Method == Closure_Make)
                                {
                                    CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression;
                                    ccbe.Block.Bind();

                                    Expression producer = ppp[0];

                                    Expression exx = Ast.ConvertHelper(producer, typeof(Callable));

                                    MethodInfo callx = GetCallable(0);

                                    if (ccbe.Block.ParameterCount == 0)
                                    {
                                        return(InlineCall(cb, ccbe));
                                    }
                                    else if (ccbe.Block.ParameterCount == 1)
                                    {
                                        return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), Ast.Call(exx, callx))));
                                    }
                                    else
                                    {
                                        Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[]));

                                        Expression valuesarr = Ast.Read(values);

                                        Expression[] pppp = new Expression[ccbe.Block.ParameterCount];

                                        for (int i = 0; i < pppp.Length; i++)
                                        {
                                            pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i));
                                        }

                                        return(Ast.Comma(
                                                   Ast.Void(
                                                       Ast.Write(
                                                           values,
                                                           Ast.ComplexCallHelper(
                                                               Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"),
                                                                                    Ast.Call(exx, callx)),
                                                               typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }),
                                                               Ast.Constant(pppp.Length)))),
                                                   InlineCall(cb, ccbe, pppp)));
                                    }
                                }
                            }
                            else
                            {
                                ;
                            }
                        }
                    }
#endif
                    // this can be enabled once builtins are auto CPS'd.
                    // ok I tried, but there are issues still, not sure what
#if OPTIMIZATIONS
                    // check for inline emitter
                    InlineEmitter ie;
                    if (TryGetInlineEmitter(f, out ie))
                    {
                        Expression result = ie(GetAstList(c.cdr as Cons, cb));
                        // if null is returned, the method cannot be inlined
                        if (result != null)
                        {
                            if (spanHint.IsValid)
                            {
                                result.SetLoc(spanHint);
                            }
                            return(result);
                        }
                    }
#endif

                    if (Context.Scope.TryLookupName(f, out m))
                    {
                        if (var == null)
                        {
                            IGenerator gh = m as IGenerator;
                            if (gh != null)
                            {
                                return(gh.Generate(c.cdr, cb));
                            }

                            BuiltinMethod bf = m as BuiltinMethod;
                            if (bf != null)
                            {
                                MethodBinder mb   = bf.Binder;
                                Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e));

                                if (bf.AllowConstantFold && !Debugger.IsAttached)
                                {
                                    bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger));

                                    if (constant)
                                    {
                                        object[]    cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e));
                                        CallTarget0 disp  = delegate
                                        {
                                            return(bf.Call(cargs));
                                        };
                                        CallTarget1 handler = delegate(object e)
                                        {
                                            throw new CompileTimeEvaluationException();
                                        };

                                        try
                                        {
                                            object result = Runtime.R6RS.Exceptions.WithExceptionHandler(
                                                Closure.Create(handler),
                                                Closure.Create(disp));
                                            var rrrr = GetCons(result, cb);
                                            if (spanHint.IsValid)
                                            {
                                                rrrr.SetLoc(spanHint);
                                            }
                                            return(rrrr);
                                        }
                                        catch (CompileTimeEvaluationException)
                                        {
                                        }
                                    }
                                }

                                Type[]          types = GetExpressionTypes(pars);
                                MethodCandidate mc    = mb.MakeBindingTarget(CallType.None, types);
                                if (mc != null)
                                {
                                    if (mc.Target.NeedsContext)
                                    {
                                        pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars);
                                    }
                                    MethodBase meth = mc.Target.Method;

                                    var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars);
                                    if (spanHint.IsValid)
                                    {
                                        rrrr.SetLoc(spanHint);
                                    }
                                    return(rrrr);
                                }
                            }

                            Closure clos = m as Closure;
                            if (clos != null && !SetGenerator.IsAssigned(f))
                            {
                                // no provision for varargs
                                MethodInfo[] mis = clos.Targets;
                                if (mis.Length > 0)
                                {
                                    MethodBinder mb = MethodBinder.MakeBinder(binder, SymbolTable.IdToString(f), mis, BinderType.Normal);

                                    Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e));

                                    if (clos.AllowConstantFold && !Debugger.IsAttached)
                                    {
                                        bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger));

                                        if (constant)
                                        {
                                            object[] cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e));

                                            CallTarget0 disp = delegate
                                            {
                                                var rrrr = clos.Call(cargs);
                                                return(rrrr);
                                            };

                                            CallTarget1 handler = delegate(object e)
                                            {
                                                throw new CompileTimeEvaluationException();
                                            };

                                            try
                                            {
                                                object result = Runtime.R6RS.Exceptions.WithExceptionHandler(
                                                    Closure.Create(handler),
                                                    Closure.Create(disp));
                                                var rrrr = GetCons(result, cb);
                                                if (spanHint.IsValid)
                                                {
                                                    rrrr.SetLoc(spanHint);
                                                }
                                                return(rrrr);
                                            }
                                            catch (CompileTimeEvaluationException)
                                            {
                                            }
                                        }
                                    }

                                    // exclude transient members if needed
                                    if (!AllowTransientBinding)
                                    {
                                        mis = Array.FindAll(mis, x => !IsTransient(x.Module));
                                    }

                                    if (mis.Length > 0)
                                    {
                                        Type[]          types = GetExpressionTypes(pars);
                                        MethodCandidate mc    = mb.MakeBindingTarget(CallType.None, types);
                                        if (mc != null)
                                        {
                                            if (mc.Target.NeedsContext)
                                            {
                                                pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars);
                                            }
                                            MethodBase meth = mc.Target.Method;

                                            var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars);
                                            if (spanHint.IsValid)
                                            {
                                                rrrr.SetLoc(spanHint);
                                            }
                                            return(rrrr);
                                        }
                                    }
                                }
                                // check for overload thing
                            }
                        }
                    }
                }


                Expression ex = Unwrap(GetAst(c.car, cb));

                // a 'let'
                if (ex is MethodCallExpression)
                {
                    var ppp = GetAstList(c.cdr as Cons, cb);
                    MethodCallExpression mcexpr = (MethodCallExpression)ex;
                    if (mcexpr.Method == Closure_Make)
                    {
                        CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression;

                        if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            return(InlineCall(cb, cbe, istailposition, ppp));
                        }
                    }

                    // cater for varargs more efficiently, this does not seem to hit, probably needed somewhere else, hits in ironscheme-test and cut test
                    if (mcexpr.Method == Closure_MakeVarArgsX)
                    {
                        CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression;

                        if (ppp.Length < 9 && cbe.Block.ParameterCount <= ppp.Length && !NeedsContext(cbe))
                        {
                            // TODO: See why having a context fails here
                            return(CallVarArgs(cbe, ppp));
                        }
                    }
                }

                if (ex is NewExpression && typeof(ITypedCallable).IsAssignableFrom(ex.Type))
                {
                    NewExpression       mcexpr = ex as NewExpression;
                    CodeBlockExpression cbe    = mcexpr.Arguments[0] as CodeBlockExpression;
                    if (cbe == null && mcexpr.Arguments[0].Type == typeof(CodeContext) && mcexpr.Arguments[0] is ConstantExpression) // implies null
                    {
                        cbe = mcexpr.Arguments[1] as CodeBlockExpression;
                    }
                    if (cbe != null)
                    {
                        var ppp = GetAstListNoCast(c.cdr as Cons, cb);

                        if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length)
                        {
                            return(InlineCall(cb, cbe, istailposition, ppp));
                        }
                    }
                }

                if (ex is ConstantExpression)
                {
                    Builtins.SyntaxError(SymbolTable.StringToObject("generator"), "expecting a procedure", c.car, c);
                }

                Expression r = null;

                if (ex.Type.Name.StartsWith("TypedClosure"))
                {
                    Expression[] pp = GetAstListNoCast(c.cdr as Cons, cb);

                    var m = ex.Type.GetMethod("Invoke");
                    //TODO: add more checks, should we attempt some casting for types?
                    if (m.GetParameters().Length != pp.Length)
                    {
                        Builtins.SyntaxError(SymbolTable.StringToObject("apply-typed-lambda"),
                                             string.Format("incorrect number of parameters, expected {0} got {1}", m.GetParameters().Length, pp.Length),
                                             c.car, c);
                    }
                    r = Ast.SimpleCallHelper(ex, m, pp);
                }
                else
                {
                    Expression[] pp = GetAstList(c.cdr as Cons, cb);

                    if (ex.Type != typeof(Callable))
                    {
                        ex = Ast.ConvertHelper(ex, typeof(Callable));
                    }

                    MethodInfo call = GetCallable(pp.Length);

                    r = pp.Length > 8 ?
                        Ast.Call(ex, call, Ast.NewArray(typeof(object[]), pp)) :
                        Ast.Call(ex, call, pp);
                }

                if (spanHint.IsValid)
                {
                    r.SetLoc(spanHint);
                }

                return(r);
            }

            object[] v = args as object[];

            if (v != null)
            {
                return(GetConsVector(v, cb));
            }
            else if (args is byte[])
            {
                Expression[] ba = Array.ConvertAll(args as byte[], b => Ast.Constant(b));
                return(Ast.NewArray(typeof(byte[]), ba));
            }
            else
            {
                if (args is SymbolId)
                {
                    SymbolId sym = (SymbolId)args;
                    if (sym == SymbolTable.StringToId("uninitialized"))
                    {
                        return(Ast.ReadField(null, typeof(Uninitialized), "Instance"));
                    }
                    else
                    {
                        return(Read(sym, cb, typeof(object)));
                    }
                }
                if (args == Builtins.Unspecified)
                {
                    return(Ast.ReadField(null, Unspecified));
                }
                if (args is Fraction)
                {
                    Fraction f = (Fraction)args;
                    return(Ast.Constant(new FractionConstant(f)));
                }
                if (args is ComplexFraction)
                {
                    ComplexFraction f = (ComplexFraction)args;
                    return(Ast.Constant(new ComplexFractionConstant(f)));
                }
                if (args != null && args.GetType().Name == "stx")
                {
                    args = new SerializedConstant(args);
                }
                return(Ast.Constant(args));
            }
        }
コード例 #39
0
ファイル: MenuGenerator.cs プロジェクト: Hahahamemes/Ports
 /// <summary>
 ///     Initializes a new instance of the <see cref="MenuGenerator" /> class.
 /// </summary>
 /// <param name="menu">The menu.</param>
 /// <param name="generator">The menu preset.</param>
 public MenuGenerator(Menu menu, IGenerator generator)
 {
     this.Generator = generator;
     this.Menu      = menu;
 }
コード例 #40
0
ファイル: Spreader.cs プロジェクト: DrewCutch/SpellSword
 public bool CanPlace(Floor floor, Coord pos, IGenerator rng)
 {
     return(_generator.CanPlace(floor, pos, rng));
 }
コード例 #41
0
 public static IGenerator <IEnumerable <T> > Window <T>(this IGenerator <T> generator, int windowSize)
 {
     return(WindowImpl(generator, windowSize).ToGenerator());
 }
コード例 #42
0
 public static IGenerator <T> OfType <T>(this IGenerator generator) where T : class
 {
     return(OfTypeImpl <T>(generator).ToGenerator());
 }
コード例 #43
0
        public ConstantGaussianMutation(OptimizationProblem problem, double standardDeviation, IGenerator randomNumberGenerator)
        {
            //problem.CheckInput();
            this.continuousVariablesCount = problem.Dimension;

            if (standardDeviation <= 0)
            {
                throw new ArgumentException("Standard deviation must be > 0, but was " + standardDeviation);
            }
            this.standardDeviations = new double[continuousVariablesCount];
            for (int i = 0; i < problem.Dimension; ++i)
            {
                this.standardDeviations[i] = standardDeviation;
            }

            if (randomNumberGenerator == null)
            {
                throw new ArgumentException("The random number generator must not be null");
            }
            this.normalDistribution = new NormalDistribution(randomNumberGenerator, 0, 1);
        }
コード例 #44
0
 // You can also define your own extension methods
 // for making new generators from existing ones.
 // This method turns a generator that generates arbitrary
 // elements into a generator that generates the same elements
 // converted to strings using ToString
 public static IGenerator <string> ElementsToString <T>(this IGenerator <T> source)
 {
     return(source.Select(x => x.ToString()));
 }
コード例 #45
0
ファイル: CxxLibraryTarget.cs プロジェクト: Anteru/bea
 public override void Accept(IGenerator generator)
 {
     generator.Visit(this);
 }
コード例 #46
0
ファイル: Rnd.cs プロジェクト: Corniel/game-2048
 public static Move[] NextMoves(this IGenerator rnd) => nextMoves[rnd.Next(24)];
コード例 #47
0
ファイル: LayerBlender.cs プロジェクト: DeinFreund/Cyubey
 public Layer(IGenerator terrainGenerator, int startingHeight)
 {
     this.startingHeight   = startingHeight;
     this.terrainGenerator = terrainGenerator;
 }
コード例 #48
0
 public static IGenerator <T> RepeatWithProbability <T>(this IGenerator <T> generator, float probability)
 {
     //asset probability is between 0 and 1
     return(RepeatWithProbabilityImlp(generator, probability).ToGenerator());
 }
コード例 #49
0
ファイル: ViewModel.cs プロジェクト: IanAWP/MRRCesiumTiler
 public GeneratorProfile(string name, IGenerator generator)
 {
     Name      = name;
     Generator = generator;
 }
コード例 #50
0
ファイル: Specification.cs プロジェクト: Kostassoid/Liar
 public Specification(IGenerator <T> generator)
 {
     Generator = generator;
 }
コード例 #51
0
 public NullableGenerator(IGenerator <T> generator)
 {
     this.generator = generator;
 }
コード例 #52
0
        public NormalDistribution(IGenerator <double> random)
        {
            Debug.Assert(random != null);

            _random = random;
        }
コード例 #53
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.activityCode);

            _progressBar  = FindViewById <ProgressBar>(Resource.Id.progressBar);
            _codeTextView = FindViewById <TextView>(Resource.Id.textCode);

            _animationScale = Settings.Global.GetFloat(ContentResolver, Settings.Global.AnimatorDurationScale, 1.0f);

            var usernameText = FindViewById <TextView>(Resource.Id.textUsername);
            var username     = Intent.Extras.GetString("username");

            if (String.IsNullOrEmpty(username))
            {
                var issuer = Intent.Extras.GetString("issuer");
                usernameText.Text = issuer;
            }
            else
            {
                usernameText.Text = username;
            }

            var iconView      = FindViewById <ImageView>(Resource.Id.imageIcon);
            var hasCustomIcon = Intent.Extras.GetBoolean("hasCustomIcon");

            if (hasCustomIcon)
            {
                var bitmap = (Bitmap)Intent.Extras.GetParcelable("icon");

                if (bitmap != null)
                {
                    iconView.SetImageBitmap(bitmap);
                }
                else
                {
                    iconView.SetImageResource(IconResolver.GetService(IconResolver.Default, true));
                }
            }
            else
            {
                iconView.SetImageResource(IconResolver.GetService(Intent.Extras.GetString("icon"), true));
            }

            _period = Intent.Extras.GetInt("period");
            _digits = Intent.Extras.GetInt("digits");
            var algorithm = (HashAlgorithm)Intent.Extras.GetInt("algorithm");

            var secret = Intent.Extras.GetString("secret");
            var type   = (AuthenticatorType)Intent.Extras.GetInt("type");

            _generator = type switch
            {
                AuthenticatorType.MobileOtp => new MobileOtp(secret, _digits),
                AuthenticatorType.SteamOtp => new SteamOtp(secret),
                _ => new Totp(secret, _period, algorithm, _digits)
            };

            _timer = new Timer
            {
                Interval  = 1000,
                AutoReset = true
            };

            _timer.Elapsed += Tick;
        }
コード例 #54
0
        /// <summary>
        /// Trims current small dead-end paths from the given list of map areas, and removes them from the given map.
        /// </summary>
        /// <param name="map">Map to remove-dead-end paths from.</param>
        /// <param name="areas">Map areas to check for dead ends.  Dead ends not contained as one of these map areas will be ignored.</param>
        /// <param name="saveDeadEndChance">The chance out of 100 that a given dead end is left alone. Defaults to 0.</param>
        /// <param name="rng">Rng to use.  Defaults to <see cref="SingletonRandom.DefaultRNG"/>.</param>
        public static void Trim(ISettableMapView <bool> map, IEnumerable <MapArea> areas, int saveDeadEndChance = 100, IGenerator rng = null)
        {
            if (rng == null)
            {
                rng = SingletonRandom.DefaultRNG;
            }

            foreach (var area in areas)
            {
                HashSet <Coord> safeDeadEnds = new HashSet <Coord>();
                HashSet <Coord> deadEnds     = new HashSet <Coord>();

                while (true)
                {
                    foreach (var point in area.Positions)
                    {
                        var points     = AdjacencyRule.EIGHT_WAY.NeighborsClockwise(point).ToArray();
                        var directions = AdjacencyRule.EIGHT_WAY.DirectionsOfNeighborsClockwise(Direction.NONE).ToList();

                        for (int i = 0; i < 8; i += 2)
                        {
                            if (map[points[i]])
                            {
                                var  oppDir = directions[i] + 4;
                                bool found  = false;

                                // If we get here, source direction is a floor, opposite direction
                                // should be wall
                                if (!map[points[(int)oppDir.Type]])
                                {
                                    switch (oppDir.Type)
                                    {
                                    // Check for a wall pattern in the map. In this case
                                    // something like where X is a wall XXX X X
                                    case Direction.Types.UP:
                                        found = !map[points[(int)Direction.Types.UP_LEFT]] &&
                                                !map[points[(int)Direction.Types.UP_RIGHT]] &&
                                                !map[points[(int)Direction.Types.LEFT]] &&
                                                !map[points[(int)Direction.Types.RIGHT]];
                                        break;

                                    case Direction.Types.DOWN:
                                        found = !map[points[(int)Direction.Types.DOWN_LEFT]] &&
                                                !map[points[(int)Direction.Types.DOWN_RIGHT]] &&
                                                !map[points[(int)Direction.Types.LEFT]] &&
                                                !map[points[(int)Direction.Types.RIGHT]];
                                        break;

                                    case Direction.Types.RIGHT:
                                        found = !map[points[(int)Direction.Types.UP_RIGHT]] &&
                                                !map[points[(int)Direction.Types.DOWN_RIGHT]] &&
                                                !map[points[(int)Direction.Types.UP]] &&
                                                !map[points[(int)Direction.Types.DOWN]];
                                        break;

                                    case Direction.Types.LEFT:
                                        found = !map[points[(int)Direction.Types.UP_LEFT]] &&
                                                !map[points[(int)Direction.Types.DOWN_LEFT]] &&
                                                !map[points[(int)Direction.Types.UP]] &&
                                                !map[points[(int)Direction.Types.DOWN]];
                                        break;
                                    }
                                }

                                if (found)
                                {
                                    deadEnds.Add(point);
                                }

                                break;
                            }
                        }
                    }

                    deadEnds.ExceptWith(safeDeadEnds);         // Remove safeDeadEnds from deadEnds
                    area.Remove(deadEnds);                     // Remove dead ends from positions

                    if (deadEnds.Count == 0)
                    {
                        break;
                    }

                    foreach (var point in deadEnds)
                    {
                        if (PercentageCheck(saveDeadEndChance, rng))
                        {
                            safeDeadEnds.Add(point);
                        }
                        else
                        {
                            map[point] = false;
                        }
                    }

                    deadEnds.Clear();
                    break;                     // We only do 1 pass, to avoid erasing the entire map.
                }
            }
        }
コード例 #55
0
ファイル: Rnd.cs プロジェクト: Corniel/game-2048
 public static ulong NextCell(this IGenerator rnd)
 => rnd.Next(10) == 0 ? 2UL : 1UL;
コード例 #56
0
 public FunctorEqualsGeneratorPredicate(IFunctor lhs, IGenerator rhs)
 {
     functor   = lhs;
     generator = rhs;
 }
コード例 #57
0
 public MaintenanceService(IFhirService _fhirServiceFull, ILocalhost localhost, IGenerator keyGenerator, IFhirStoreAdministration fhirStoreAdministration, IFhirIndex fhirIndex)
 {
     this._fhirServiceFull        = _fhirServiceFull;
     this.localhost               = localhost;
     this.keyGenerator            = keyGenerator;
     this.fhirStoreAdministration = fhirStoreAdministration;
     this.fhirIndex               = fhirIndex;
 }
コード例 #58
0
        public bool CanGenerate(Floor floor, RoomConnection connectAt, IGenerator rng)
        {
            MapArea mapArea = GenerateArea(floor.MapInfo, connectAt, rng);

            return(floor.MapInfo.Map.Terrain.AllEmpty(mapArea.Positions));
        }
コード例 #59
0
 public static IGenerator <T> Cast <T>(this IGenerator generator)
 {
     return(CastImpl <T>(generator).ToGenerator());
 }
コード例 #60
0
        public ConstantGaussianMutation(OptimizationProblem problem, double[] standardDeviations, IGenerator randomNumberGenerator)
        {
            //problem.CheckInput();
            this.continuousVariablesCount = problem.Dimension;

            if (standardDeviations.Length != continuousVariablesCount)
            {
                throw new ArgumentException("There are " + continuousVariablesCount + " continuous design variables, but "
                                            + standardDeviations.Length + " standard deviations are provided");
            }
            this.standardDeviations = new double[continuousVariablesCount];
            for (int i = 0; i < problem.Dimension; ++i)
            {
                if (standardDeviations[i] <= 0)
                {
                    throw new ArgumentException("Standard deviations must be > 0, but at index " + i
                                                + ", the provided value is " + standardDeviations[i]);
                }
                this.standardDeviations[i] = standardDeviations[i];
            }

            if (randomNumberGenerator == null)
            {
                throw new ArgumentException("The random number generator must not be null");
            }
            this.normalDistribution = new NormalDistribution(randomNumberGenerator, 0, 1);
        }