private PrintOptions LoadPrintConfiguration(TomlTable configTable)
        {
            PrintOptions options = new PrintOptions();

            if (configTable != null && configTable.ContainsKey("PrintOptions"))
            {
                TomlTable settings = configTable.Get <TomlTable>("PrintOptions");

                if (settings.ContainsKey("Orientation"))
                {
                    options.Orientation = (FilmOrientation)settings.Get <TomlInt>("Orientation").Value;
                }
                if (settings.ContainsKey("Size"))
                {
                    options.FilmSize = (FilmSize)settings.Get <TomlInt>("Size").Value;
                }
                if (settings.ContainsKey("Magnification"))
                {
                    options.MagnificationType = (MagnificationType)settings.Get <TomlInt>("Magnification").Value;
                }
                if (settings.ContainsKey("Medium"))
                {
                    options.MediumType = (MediumType)settings.Get <TomlInt>("Medium").Value;
                }
            }

            return(options);
        }
Exemple #2
0
        internal static IRunControlTask Create(TomlTable taskSpec, IAppState appState, IAppService appService)
        {
            RequireTrue(
                taskSpec.ContainsKey("samples_file"),
                "File sampling task spec has missing path to samples file"
                );
            RequireTrue(
                taskSpec.ContainsKey("outputs"),
                "File sampling task spec has missing outputs"
                );

            var name = taskSpec["name"].Get <string>();

            RequireNotNullEmptyWhiteSpace(name, "Invalid task name");

            var pathToSamplesFile = taskSpec["samples_file"].Get <string>();

            RequireFile(pathToSamplesFile, "Invalid samples_file");

            Arr <(string Parameter, Arr <double> Correlations)> correlation = default;

            if (taskSpec.ContainsKey("correlation"))
            {
                var correlationSpec = taskSpec["correlation"] as TomlTableArray;
                RequireNotNull(correlationSpec, "Expecting correlation specified as table array");
                correlation = correlationSpec.Items
                              .Cast <TomlTable>()
                              .Select(tt => (
                                          Parameter: tt["name"].Get <string>(),
                                          Correlations: tt["values"].Get <double[]>().ToArr()))
                              .ToArr();
            }

            var outputSpecs = taskSpec["outputs"] as TomlArray;

            RequireNotNull(
                outputSpecs,
                "Distribution sampling task spec has missing or misspecified outputs"
                );
            RequireTrue(
                outputSpecs.Length > 0,
                "Distribution sampling task spec has empty outputs"
                );

            var outputNames = outputSpecs.To <string>().ToArr();

            return(new FileSamplingTask(
                       name,
                       pathToSamplesFile,
                       correlation,
                       outputNames,
                       appState,
                       appService
                       ));
        }
        // Seriously, f**k this TOML Library.
        // WHY DOESN'T IT SUPPORT GENERICS

        public TomlObject SetValueInternal <T>(string key, T value, string comment)
        {
            TomlObject field;

            if (value is bool)
            {
                bool v = (bool)(object)value;
                field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v);
            }
            else if (value is string)
            {
                string v = (string)(object)value;
                field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v);
            }
            else if (value is int)
            {
                int v = (int)(object)value;
                field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v);
            }
            else if (value is float)
            {
                float v = (float)(object)value;
                field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v);
            }
            else
            {
                throw new NotSupportedException();
            }

            AttatchComments(field, comment);
            Flush();
            return(field);
        }
Exemple #4
0
        public static GeneratorConfig GetGeneratorConfig(string tomlFile)
        {
            TomlTable config  = Toml.ReadFile(tomlFile);
            var       gConfig = new GeneratorConfig();

            gConfig.Id             = config.Get <String>("Id");
            gConfig.Type           = config.Get <String>("Type");
            gConfig.BrokerHostName = config.ContainsKey("BrokerHostName") ? config.Get <String>("BrokerHostName") : null;
            gConfig.OutputFilePath = config.ContainsKey("OutputFilePath") ? config.Get <String>("OutputFilePath") : null;
            gConfig.Description    = config.Get <String>("Description");
            gConfig.DateTimeFormat = config.Get <String>("DateTimeFormat");
            gConfig.Seed           = config.ContainsKey("Seed") ? config.Get <int>("Seed") : -1;
            gConfig.Duration       = config.ContainsKey("Duration") ? config.Get <long>("Duration") : -1;
            return(gConfig);
        }
Exemple #5
0
        public CredentialManager()
        {
            if (File.Exists(upmconfigFile))
            {
                var upmconfig = Toml.Parse(File.ReadAllText(upmconfigFile));
                if (upmconfig.HasErrors)
                {
                    Debug.LogError("Cannot load upmconfig, invalid format");
                    return;
                }


                TomlTable table = upmconfig.ToModel();

                if (table != null && table.ContainsKey("npmAuth"))
                {
                    TomlTable auth = (TomlTable)table["npmAuth"];
                    if (auth != null)
                    {
                        foreach (var registry in auth)
                        {
                            NPMCredential cred = new NPMCredential();
                            cred.url = registry.Key;
                            TomlTable value = (TomlTable)registry.Value;
                            cred.token      = (string)value["token"];
                            cred.alwaysAuth = (bool)value["alwaysAuth"];

                            credentials.Add(cred.url, cred);
                        }
                    }
                }
            }
        }
Exemple #6
0
 public override void SetConfig(TomlTable toml)
 {
     base.SetConfig(toml);
     if (toml.ContainsKey("socks"))
     {
         server = toml.Get <AddrPort>("socks");
     }
 }
        public static T GetOr <T>(this TomlTable table, string key, T @default = default) where T : struct
        {
            if (!table.ContainsKey(key))
            {
                return(@default);
            }

            return(table[key] as T? ?? @default);
        }
        public static T MaybeGet <T>(this TomlTable table, string key) where T : class
        {
            if (!table.ContainsKey(key))
            {
                return(null);
            }

            return(table[key] as T);
        }
Exemple #9
0
        public bool HasSetting(string spec)
        {
            List <bool> exists = new List <bool>();

            string[] parts = spec.Split(',');
            foreach (string p in parts)
            {
                string trimmedParts = p.Trim();

                string[] set = trimmedParts.Split('=');
                if (set.Length == 2)
                {
                    string trimmedName = set[0].Trim();
                    string trimmedVal  = set[1].Trim();

                    exists.Add(_toml.ContainsKey(trimmedName));
                }
            }

            return(exists.Count > 0 && exists.All(s => s));
        }
        private string LoadPrinterConfiguration(TomlTable configTable)
        {
            if (configTable != null && configTable.ContainsKey("PrinterSettings"))
            {
                TomlTable settings = configTable.Get <TomlTable>("PrinterSettings");

                if (settings.ContainsKey("Printer"))
                {
                    return(settings.Get <TomlString>("Printer").Value);
                }
            }

            return("Microsoft XPS Document Writer");
        }
Exemple #11
0
        // This method generate BaseParticle in system by side effect.
        internal void GenerateIntegratorManagers(
            GameObject scene_builder, List <GameObject> base_particles, float kb_scaled, float timescale)
        {
            if (SimulatorTable.ContainsKey("integrator"))
            {
                TomlTable integrator = SimulatorTable.Get <TomlTable>("integrator");
                if (integrator.ContainsKey("type"))
                {
                    string integrator_type = integrator.Get <string>("type");
                    if (integrator_type == "UnderdampedLangevin")
                    {
                        if (integrator.ContainsKey("gammas"))
                        {
                            int base_particles_num         = base_particles.Count;
                            List <TomlTable> gammas_tables = integrator.Get <List <TomlTable> >("gammas");
                            float[]          gammas        = new float[base_particles.Count];
                            foreach (TomlTable gamma_table in gammas_tables)
                            {
                                // TODO: check dupulicate and lacking of declaration.
                                gammas[gamma_table.Get <int>("index")] = gamma_table.Get <float>("gamma");
                            }
                            var temperature = SystemTable.Get <TomlTable>("attributes").Get <float>("temperature");

                            UnderdampedLangevinManager ul_manager
                                = scene_builder.AddComponent <UnderdampedLangevinManager>() as UnderdampedLangevinManager;
                            ul_manager.Init(kb_scaled, temperature, base_particles, gammas, timescale);
                            Debug.Log("UnderdampedLangevinManager initialization finished.");
                        }
                        else
                        {
                            throw new System.Exception(
                                      "When you use UnderdampedLangevin integrator, you must specify gammas for integrator.");
                        }
                    }
                }
            }
        }
Exemple #12
0
        public static T ToModel <T>(this DocumentSyntax documentSyntax) where T : new()
        {
            T         instance = new T();
            TomlTable model    = documentSyntax.ToModel();

            foreach (PropertyInfo property in instance.GetType().GetProperties())
            {
                TomlPropertyAttribute?attribute = property.GetCustomAttribute <TomlPropertyAttribute>();

                if (attribute is null)
                {
                    continue;
                }

                if (attribute.Header is null)
                {
                    if (attribute.Required && !model.ContainsKey(property.Name))
                    {
                        throw new Exception($"Toml file does not have required property '{property.Name}'.");
                    }

                    property.SetValue(instance, Convert.ChangeType(model[property.Name], property.PropertyType));
                }
                else
                {
                    if ((attribute.Required && !model.ContainsKey(attribute.Header)) || !((TomlTable)model[attribute.Header]).ContainsKey(property.Name))
                    {
                        throw new Exception($"Toml file does not have required property '{property.Name}'.");
                    }

                    property.SetValue(instance, Convert.ChangeType(((TomlTable)model[attribute.Header])[property.Name], property.PropertyType));
                }
            }

            return(instance);
        }
        private AppConfiguration LoadAppConfiguration(TomlTable configTable)
        {
            AppConfiguration appConfiguration = new AppConfiguration();

            if (configTable != null && configTable.ContainsKey("Application"))
            {
                TomlTable settings = configTable.Get <TomlTable>("Application");

                if (settings.ContainsKey("ListenPort"))
                {
                    appConfiguration.ListenPort = (int)settings.Get <TomlInt>("ListenPort").Value;
                }
            }

            return(appConfiguration);
        }
Exemple #14
0
        private void LoadConfig()
        {
            if (ConfigTable.ContainsKey("Application"))
            {
                TomlTable appSettings = ConfigTable.Get <TomlTable>("Application");

                if (appSettings.ContainsKey("ListenPort"))
                {
                    ServerPort = (int)appSettings.Get <TomlInt>("ListenPort").Value;
                    Messenger.Default.ServerPort = ServerPort;
                }
            }

            foreach (var item in Items)
            {
                (item as IConfigViewModel).LoadConfigs(ConfigTable);
            }
        }
Exemple #15
0
        public void Parse(RenderSettings renderSettings, TomlTable toml)
        {
            if (toml == null)
            {
                return;
            }
            bool hasEaSetting = toml.ContainsKey(ENTERPRISE_ARCHITECT);

            if (!hasEaSetting)
            {
                return;
            }
            var ea = toml[ENTERPRISE_ARCHITECT] as TomlTable;

            if (!ea.ContainsKey(FILE))
            {
                return;
            }
            var file = ea[FILE] as string;

            File = new File(renderSettings.SourceFolder, file);
        }
Exemple #16
0
        public void ReplaceOrAdd(string dottedKey, string value)
        {
            string[]  segments = dottedKey.Split(".");
            TomlTable table    = this.document;

            for (int i = 0; i < segments.Length - 1; i++)
            {
                string tableKey = segments[i];

                try
                {
                    table = (TomlTable)table[tableKey];
                }
                catch (KeyNotFoundException)
                {
                    // Nett does not provide a function to easily add table subkeys.
                    // A hack workaround is to serialize the table, append the new table as a string, then deserialize.
                    // This only needs to be done once to create the new subtable.
                    // After that, Nett functions can be used to modify the subtable.
                    string tableName = string.Join(".", segments.Take(segments.Length - 1));
                    this.AddTable(tableName, segments[segments.Length - 1], value);
                    return;
                }
            }

            string key = segments[segments.Length - 1];

            if (table.ContainsKey(key))
            {
                table.Update(key, value);
            }
            else
            {
                table.Add(key, value);
            }
        }
        static Config()
        {
            FilePath = Path.Combine(Core.BasePath, "Config.cfg");
            if (!File.Exists(FilePath))
            {
                Save();
                return;
            }
            string filestr = File.ReadAllText(FilePath);

            if (string.IsNullOrEmpty(filestr))
            {
                return;
            }
            DocumentSyntax docsyn = Toml.Parse(filestr);

            if (docsyn == null)
            {
                return;
            }
            TomlTable model = docsyn.ToModel();

            if (model.Count <= 0)
            {
                return;
            }
            TomlTable tbl = (TomlTable)model["AssemblyGenerator"];

            if (tbl == null)
            {
                return;
            }
            if (tbl.ContainsKey("UnityVersion"))
            {
                UnityVersion = (string)tbl["UnityVersion"];
            }
            if (tbl.ContainsKey("Cpp2IL"))
            {
                Cpp2ILVersion = (string)tbl["Cpp2IL"];
            }
            if (tbl.ContainsKey("Il2CppAssemblyUnhollower"))
            {
                Il2CppAssemblyUnhollowerVersion = (string)tbl["Il2CppAssemblyUnhollower"];
            }
            if (tbl.ContainsKey("GameAssemblyHash"))
            {
                GameAssemblyHash = (string)tbl["GameAssemblyHash"];
            }
            if (!tbl.ContainsKey("OldFiles"))
            {
                return;
            }
            TomlArray oldfilesarr = (TomlArray)tbl["OldFiles"];

            if (oldfilesarr.Count <= 0)
            {
                return;
            }
            for (int i = 0; i < oldfilesarr.Count; i++)
            {
                string file = (string)oldfilesarr[i];
                if (!string.IsNullOrEmpty(file))
                {
                    OldFiles.Add(file);
                }
            }
        }
Exemple #18
0
 public static bool Has <T>(this TomlTable table, string key)
 {
     return(table.ContainsKey(key) && table[key] is T);
 }
Exemple #19
0
        internal static IRunControlTask Create(TomlTable taskSpec, IAppState appState, IAppService appService)
        {
            RequireTrue(
                taskSpec.ContainsKey("n_samples"),
                "Distribution sampling task spec has missing n_samples setting"
                );
            RequireTrue(
                taskSpec.ContainsKey("distributions"),
                "Distribution sampling task spec has missing distributions"
                );
            RequireTrue(
                taskSpec.ContainsKey("outputs"),
                "Distribution sampling task spec has missing outputs"
                );

            var name = taskSpec["name"].Get <string>();

            RequireNotNullEmptyWhiteSpace(name, "Invalid task name");

            var nSamples = taskSpec["n_samples"].Get <int>();

            RequireTrue(nSamples > 0, "Invalid n_samples");

            var distributionSpecs = taskSpec["distributions"] as TomlArray;

            RequireNotNull(
                distributionSpecs,
                "Distribution sampling task spec has missing or misspecified distributions"
                );
            RequireTrue(
                distributionSpecs.Length > 0,
                "Distribution sampling task spec has empty distributions"
                );

            var distributions = distributionSpecs.Items
                                .Select(tv => Distribution.ParseRelation(tv.Get <string>()))
                                .ToArr();

            LatinHypercubeDesign latinHypercubeDesign = LatinHypercubeDesign.Default;

            if (taskSpec.ContainsKey("latin_hypercube"))
            {
                var latinHypercubeSpec = taskSpec["latin_hypercube"] as TomlTable;
                RequireNotNull(latinHypercubeSpec, "Expecting Latin hypercube specified as table array");
                RequireTrue(latinHypercubeSpec.ContainsKey("type"), "Latin hypercube missing type");

                var type       = latinHypercubeSpec["type"].Get <LatinHypercubeDesignType>();
                var t0         = latinHypercubeSpec.ContainsKey("t0") ? latinHypercubeSpec["t0"].Get <double>() : NaN;
                var c          = latinHypercubeSpec.ContainsKey("c") ? latinHypercubeSpec["c"].Get <double>() : NaN;
                var iterations = latinHypercubeSpec.ContainsKey("iter") ? latinHypercubeSpec["iter"].Get <int>() : default;
                var p          = latinHypercubeSpec.ContainsKey("p") ? latinHypercubeSpec["p"].Get <double>() : NaN;
                var profile    = latinHypercubeSpec.ContainsKey("profile") ? latinHypercubeSpec["profile"].Get <TemperatureDownProfile>() : default;
                var imax       = latinHypercubeSpec.ContainsKey("imax") ? latinHypercubeSpec["imax"].Get <int>() : default;

                var haveDesignType = type != LatinHypercubeDesignType.None;

                var hasValidSA = IsNaN(t0) || (!IsNaN(c) && iterations > 0 && !IsNaN(p));

                RequireTrue(
                    !haveDesignType || hasValidSA,
                    "Invalid Latin hypercube configuration"
                    );

                latinHypercubeDesign = new LatinHypercubeDesign(type, t0, c, iterations, p, profile, imax);
            }

            Arr <(string Parameter, Arr <double> Correlations)> correlation = default;

            if (taskSpec.ContainsKey("correlation"))
            {
                var correlationSpec = taskSpec["correlation"] as TomlTableArray;
                RequireNotNull(correlationSpec, "Expecting correlation specified as table array");
                correlation = correlationSpec.Items
                              .Cast <TomlTable>()
                              .Select(tt => (
                                          Parameter: tt["name"].Get <string>(),
                                          Correlations: tt["values"].Get <double[]>().ToArr()))
                              .ToArr();

                var correlationComplete = distributions.ForAll(
                    d => correlation.Exists(c => c.Parameter == d.Variable)
                    );
                RequireTrue(correlationComplete, "Incomplete correlation matrix");
                RequireTrue(correlation.Count == distributions.Count, "Unexpected data in correlation matrix");
            }

            var outputSpecs = taskSpec["outputs"] as TomlArray;

            RequireNotNull(
                outputSpecs,
                "Distribution sampling task spec has missing or misspecified outputs"
                );
            RequireTrue(
                outputSpecs.Length > 0,
                "Distribution sampling task spec has empty outputs"
                );

            var outputNames = outputSpecs.To <string>().ToArr();

            return(new DistributionSamplingTask(
                       name,
                       nSamples,
                       distributions,
                       latinHypercubeDesign,
                       correlation,
                       outputNames,
                       appState,
                       appService
                       ));
        }
Exemple #20
0
        // Start is called before the first frame update
        void Start()
        {
            // read input file
            string input_file_path = Application.dataPath + "/../input/input.toml";

            Debug.Log($"input file path is {input_file_path}.");
            InputToml input = new InputToml(input_file_path);

            // generate initial particle position, velocity and system temperature
            TomlTable system = input.SystemTable;

            temperature = system.Get <TomlTable>("attributes").Get <float>("temperature");

            // read particles information
            List <GameObject> base_particles = input.GenerateBaseParticles(m_BaseParticle, kb_scaled);

            // read simulator information
            input.GenerateIntegratorManagers(gameObject, base_particles, kb_scaled, timescale);

            // read boundary_shape information
            input.GenerateBoundaryManager(gameObject, base_particles);

            // read forcefields information
            TomlTable ff = input.ForceFieldTable;

            if (ff.ContainsKey("local"))
            {
                input.GenerateLocalInteractionManagers(gameObject, base_particles, timescale);
            }

            if (ff.ContainsKey("global"))
            {
                input.GenerateGlobalInteractionManagers(base_particles, timescale);
            }
            Debug.Log("ForceField initialization finished.");

            // Initialize SystemObserver
            m_SystemObserver = GetComponent <SystemObserver>();
            m_SystemObserver.Init(base_particles, timescale);
            Debug.Log("SystemObserver initialization finished.");

            // set particle colors
            int          particle_num = base_particles.Count;
            float        color_step   = 2.0f / (particle_num - 1);
            List <Color> color_list   = new List <Color>();
            float        color_val    = 0.0f;

            color_list.Add(new Color(1.0f, 0.0f, 0.0f));
            foreach (GameObject base_particle in base_particles)
            {
                color_val += color_step;
                Material particle_material = base_particle.GetComponent <Renderer>().material;
                if (color_val < 1.0f)
                {
                    particle_material.SetColor("_Color", new Color(1.0f, color_val, color_val));
                }
                else
                {
                    particle_material.SetColor("_Color", new Color(2.0f - color_val, 2.0f - color_val, 1.0f));
                }
            }


            // Set Player position
            GameObject player = GameObject.Find("OVRPlayerController");

            float max_radius = 0.0f;

            if (gameObject.GetComponent <ReflectingBoundaryManager>() != null)
            {
                foreach (GameObject base_particle in base_particles)
                {
                    float radius = base_particle.transform.localScale.x;
                    if (max_radius < radius)
                    {
                        max_radius = radius;
                    }
                }

                var     rb_manager      = gameObject.GetComponent <ReflectingBoundaryManager>();
                Vector3 upper_boundary  = rb_manager.UpperBoundary;
                Vector3 lower_boundary  = rb_manager.LowerBoundary;
                Vector3 box_length_half = upper_boundary - lower_boundary;
                Vector3 box_center      = box_length_half + lower_boundary;
                player.transform.position = new Vector3(box_center.x,
                                                        box_center.y,
                                                        lower_boundary.z - box_length_half.z);
            }
            else
            {
                Vector3 upper_edge             = detect_upper_edge(base_particles);
                Vector3 lower_edge             = detect_lower_edge(base_particles);
                Vector3 pseudo_box_center      = (upper_edge + lower_edge) * 0.5f;
                Vector3 pseudo_box_length_half = (upper_edge - lower_edge) * 0.5f;
                Vector3 upper_boundary         = upper_edge + pseudo_box_length_half;
                Vector3 lower_boundary         = lower_edge - pseudo_box_length_half;
                player.transform.position = new Vector3(pseudo_box_center.x,
                                                        upper_boundary.y,
                                                        lower_boundary.z - pseudo_box_length_half.z);
                player.transform.localScale = new Vector3(upper_boundary.y,
                                                          upper_boundary.y,
                                                          upper_boundary.y);
            }
        }
Exemple #21
0
 public static bool Has(this TomlTable table, string key)
 {
     return(table.ContainsKey(key));
 }