public void Solve_When_Determinant_Is_Zero_Should_Return_Equal_Roots() { Roots roots = Solve(1, 12, 36); Assert.AreEqual(-6, roots.X1); Assert.AreEqual(-6, roots.X2); }
public void Solve_When_Determinant_Is_Negative_Should_Return_No_Roots() { Roots roots = Solve(5, 3, 7); Assert.AreEqual(double.NaN, roots.X1); Assert.AreEqual(double.NaN, roots.X2); }
public static void CohortTotalMortality(object sender, Landis.Library.BiomassCohorts.DeathEventArgs eventArgs) { ExtensionType disturbanceType = eventArgs.DisturbanceType; PoolPercentages cohortReductions = Module.Parameters.CohortReductions[disturbanceType]; ICohort cohort = (Landis.Library.LeafBiomassCohorts.ICohort)eventArgs.Cohort; ActiveSite site = eventArgs.Site; float foliar = cohort.LeafBiomass; float wood = cohort.WoodBiomass; float foliarInput = ReduceInput(foliar, cohortReductions.Foliar, site); float woodInput = ReduceInput(wood, cohortReductions.Wood, site); //PlugIn.ModelCore.UI.WriteLine("EVENT: Cohort Died: species={0}, age={1}, disturbance={2}.", cohort.Species.Name, cohort.Age, eventArgs.DisturbanceType); //PlugIn.ModelCore.UI.WriteLine(" Cohort Reductions: Foliar={0:0.00}. Wood={1:0.00}.", cohortReductions.Foliar, cohortReductions.Wood); //PlugIn.ModelCore.UI.WriteLine(" InputB/TotalB: Foliar={0:0.00}/{1:0.00}, Wood={2:0.0}/{3:0.0}.", foliarInput, foliar, woodInput, wood); ForestFloor.AddWoodLitter(woodInput, cohort.Species, site); ForestFloor.AddFoliageLitter(foliarInput, cohort.Species, site); Roots.AddCoarseRootLitter(wood, cohort, cohort.Species, site); // All of cohorts roots are killed. Roots.AddFineRootLitter(foliar, cohort, cohort.Species, site); }
public async Task <FullPath> ParsePathAsync(string target) { if (string.IsNullOrEmpty(target)) { return(null); } string volumePrefix = null; string pathHash = null; for (int i = 0; i < target.Length; i++) { if (target[i] == '_') { pathHash = target.Substring(i + 1); volumePrefix = target.Substring(0, i + 1); break; } } var root = Roots.First(r => r.VolumeId == volumePrefix); string path = HttpEncoder.DecodePath(pathHash); string dirUrl = path != root.RootDirectory ? path : string.Empty; var dir = new AzureStorageDirectory(root.RootDirectory + dirUrl); if (await dir.ExistsAsync) { return(new FullPath(root, dir, target)); } else { var file = new AzureStorageFile(root.RootDirectory + dirUrl); return(new FullPath(root, file, target)); } }
public override SignedDistance GetSignedDistance(Vector2 origin, out double t) { Vector2 qa = p0 - origin; Vector2 ab = p1 - p0; Vector2 br = p0 + p2 - p1 - p1; double a = Vector2.Dot(br, br); double b = 3 * Vector2.Dot(ab, br); double c = 2 * Vector2.Dot(ab, ab) + Vector2.Dot(qa, br); double d = Vector2.Dot(qa, ab); Roots roots = new Roots(); int solutions = SolveCubic(ref roots, a, b, c, d); double minDistance = NonZeroSign(Cross(ab, qa)) * qa.Length(); t = -Vector2.Dot(qa, ab) / Vector2.Dot(ab, ab); { double distance = NonZeroSign(Cross(p2 - p1, p2 - origin)) * (p2 - origin).Length(); if (Math.Abs(distance) < Math.Abs(minDistance)) { minDistance = distance; t = Vector2.Dot(origin - p1, p2 - p1) / Vector2.Dot(p2 - p1, p2 - p1); } } for (int i = 0; i < solutions; i++) { if (roots[i] > 0 && roots[i] < 1) { Vector2 endPoint = p0 + ((float)(2 * roots[i]) * ab) + ((float)(roots[i] * roots[i]) * br); double distance = NonZeroSign(Cross(p2 - p0, endPoint - origin)) * (endPoint - origin).Length(); if (Math.Abs(distance) <= Math.Abs(minDistance)) { minDistance = distance; t = roots[i]; } } } if (t >= 0 && t <= 1) { return(new SignedDistance(minDistance, 0)); } if (t < .5) { return(new SignedDistance(minDistance, Math.Abs(Vector2.Dot(Vector2.Normalize(ab), Vector2.Normalize(qa))))); } else { return(new SignedDistance( minDistance, Math.Abs(Vector2.Dot( Vector2.Normalize(p2 - p1), Vector2.Normalize(p2 - origin) )) )); } }
public void DetectMinimumCircularDependencyBetweenTwoNodes() { var a = new Node { Name = "A" }; var b = new Node { Name = "B" }; a.Edges.Add(b); b.Edges.Add(a); var roots = new Roots(); roots.Entangle(a); var serializers = new Serializers(new SerializerFactory()); var stateMaps = new StateMaps(serializers); var persister = new Persister(new InMemoryStorageEngine(), roots, serializers, stateMaps); persister.DetectSerializeAndPersistChanges(); var circularChain = CircularDependencyDetector.Check(serializers[0], stateMaps, serializers); circularChain.IsCircular.ShouldBeTrue(); circularChain.Path.Count().ShouldBe(3); circularChain.ToString().ShouldBe("A->B->A"); }
public Roots GiaiPhuongTrinh(int a, int b, int c) { Roots r = new Roots(); int delta = b * b - 4 * a * c; if (delta < 0) { r.RootsNumber = 0; return(r); } else if (delta == 0) { r.Root1 = GetDualRoots(); r.Root2 = GetDualRoots(); r.RootsNumber = 1; return(r); } else { r.Root1 = GetRoot1(); r.Root2 = GetRoot2(); r.RootsNumber = 2; return(r); } }
private void SolveQuadratic(double a, double b) { var sqrD = ShitMath.Sqrt(Discriminant); var rootVal = (-b + sqrD) / (2 * a); var rootStr = _shouldNotReduceFraction ? "" + (-b + sqrD + "/" + 2 * a) : "" + rootVal; if (Regex.Match(rootStr, @"\-.+\/\-.+").Success) { rootStr = rootStr.Replace("-", ""); } Steps.Add( $"[Calculating first root]\tx0 = (-b + sqrt(D)) / 2a = ({-b} + {sqrD}) / {2 * a} = {rootStr}"); Roots.Add(rootStr); if (Discriminant > 0) { rootVal = (-b - sqrD) / (2 * a); rootStr = _shouldNotReduceFraction ? "" + (-b - sqrD + "/" + 2 * a) : "" + rootVal; if (Regex.Match(rootStr, @"\-.+\/\-.+").Success) { rootStr = rootStr.Replace("-", ""); } Steps.Add( $"[Calculating second root]\tx0 = (-b - sqrt(D)) / 2a = ({-b} - {sqrD}) / {2 * a} = {rootStr}"); Roots.Add(rootStr); } }
public async Task <ICollection <CloudBlob> > GetFileInfosAsync(bool secure, Roots root, string prefix) { var container = GetContainer(secure); var tenant = await CurrentTenant.GetTenantAsync(); var name = ConstructRealName(tenant, root, prefix); var dir = container.GetDirectoryReference(name); var results = new List <CloudBlob>(); BlobContinuationToken continuationToken = null; do { var segment = await dir.ListBlobsSegmentedAsync(false, BlobListingDetails.Metadata, null, continuationToken, null, null); foreach (var item in segment.Results) { if (item is CloudBlob) { results.Add((CloudBlob)item); } } continuationToken = segment.ContinuationToken; } while (continuationToken != null); return(results); }
static void Main(string[] args) { System.Console.WriteLine("Программа вычисления корней квадратного уравнения"); double a = GetNumber("a"); double b = GetNumber("b"); double c = GetNumber("c"); double x1; double x2; Roots result = Calc(a, b, c, out x1, out x2); if (result == Roots.Two) { Console.WriteLine("x1= {0}\nx2= {1}", x1, x2); } else if (result == Roots.One) { Console.WriteLine("Уравнение имеет один корень x= {0}", x1); } else if (result == Roots.None) { Console.WriteLine("Действительных корней нет"); } }
public override void GetBounds(ref double left, ref double bottom, ref double right, ref double top) { PointBounds(p0, ref left, ref bottom, ref right, ref top); PointBounds(p3, ref left, ref bottom, ref right, ref top); Vector2 a0 = p1 - p0; Vector2 a1 = 2 * (p2 - p1 - a0); Vector2 a2 = p3 - 3 * p2 + 3 * p1 - p0; Roots roots = new Roots(); int solutions = SolveQuadratic(ref roots, a2.X, a1.X, a0.X); for (int i = 0; i < solutions; i++) { if (roots[i] > 0 && roots[i] < 1) { PointBounds(GetPoint(roots[i]), ref left, ref bottom, ref right, ref top); } } solutions = SolveQuadratic(ref roots, a2.Y, a1.Y, a0.Y); for (int i = 0; i < solutions; i++) { if (roots[i] > 0 && roots[i] < 1) { PointBounds(GetPoint(roots[i]), ref left, ref bottom, ref right, ref top); } } }
public FileSystemCollector(CollectorOptions?opts = null, Action <CollectObject>?changeHandler = null) : base(opts, changeHandler) { Roots.AddRange(opts?.SelectedDirectories ?? Array.Empty <string>()); if (!Roots.Any()) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { foreach (var driveInfo in DriveInfo.GetDrives()) { if (driveInfo.IsReady && driveInfo.DriveType == DriveType.Fixed) { Roots.Add(driveInfo.Name); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Roots.Add("/"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Roots.Add("/"); } } }
public async Task <FullPath> ParsePathAsync(string target) { if (string.IsNullOrEmpty(target)) { return(null); } int underscoreIndex = target.IndexOf('_'); string pathHash = target.Substring(underscoreIndex + 1); string volumePrefix = target.Substring(0, underscoreIndex + 1); var root = Roots.First(r => r.VolumeId == volumePrefix); var rootDirectory = new DirectoryInfo(root.RootDirectory); string path = HttpEncoder.DecodePath(pathHash); string dirUrl = path != rootDirectory.Name ? path : string.Empty; var dir = new FileSystemDirectory(root.RootDirectory + dirUrl); if (await dir.ExistsAsync) { return(new FullPath(root, dir, target)); } else { var file = new FileSystemFile(root.RootDirectory + dirUrl); return(new FullPath(root, file, target)); } }
// This is a non-recursive chain/path building algorithm. // // At this stage we only checks for PartialChain, Cyclic and UntrustedRoot errors are they // affect the path building (other errors are verification errors). // // Note that the order match the one we need to match MS and not the one defined in RFC3280, // we also include the trusted root certificate (trust anchor in RFC3280) in the list. // (this isn't an issue, just keep that in mind if you look at the source and the RFC) private X509ChainStatusFlags BuildChainFrom(X509Certificate2 certificate) { elements.Add(certificate); while (!IsChainComplete(certificate)) { certificate = FindParent(certificate); if (certificate == null) { return(X509ChainStatusFlags.PartialChain); } if (elements.Contains(certificate)) { return(X509ChainStatusFlags.Cyclic); } elements.Add(certificate); } // roots may be supplied (e.g. in the ExtraStore) so we need to confirm their // trustiness (what a cute word) in the trusted root collection if (!Roots.Contains(certificate)) { elements [elements.Count - 1].StatusFlags |= X509ChainStatusFlags.UntrustedRoot; } return(X509ChainStatusFlags.NoError); }
protected int SolveQuadratic(ref Roots roots, double a, double b, double c) { if (Math.Abs(a) < 1e-14) { if (Math.Abs(b) < 1e-14) { if (c == 0) { return(-1); } return(0); } roots.x0 = -c / b; return(1); } double discriminant = b * b - 4 * a * c; if (discriminant > 0) { discriminant = Math.Sqrt(discriminant); roots.x0 = (-b + discriminant) / (2 * a); roots.x1 = (-b - discriminant) / (2 * a); return(2); } else if (discriminant == 0) { roots.x0 = -b / (2 * a); return(1); } else { return(0); } }
//todo deactivated as it crashed the test framework [TestMethod] public void OutgoingMessageIsResetOnSocketReset() { const string hostname = "127.0.0.1"; const int port = 10100; const string connectionIdentifier = "1"; var server = new SingleConnectionServer(); server.StartListening(); var engine = ExecutionEngineFactory.StartNew(new InMemoryStorageEngine()); engine.Schedule(() => { var unackedMessageQueue = new OutgoingMessageQueue(); var deliverer = new OutgoingMessageDeliverer(hostname, port, connectionIdentifier, unackedMessageQueue); Roots.Entangle(deliverer); Roots.Entangle(unackedMessageQueue); deliverer.Send("HELLO WORLD".GetUtf8Bytes()); }); Thread.Sleep(1_000); server.DisposeConnectedSocket(); Thread.Sleep(1_000); server.GetNodeIdentifier().ShouldBe("1"); server.GetReceivedMessages().Count.ShouldBe(2); }
internal static void Build(Menu menu, JObject translations, bool createSaveHandler) { if (Roots.Exists(root => root.Id == menu.Id)) { throw new InvalidOperationException($"Menu with id \"{menu.Id}\" already exists as root!"); } Roots.Add(menu); if (translations != null) { menu.translations.Add(translations); } else { menu.UpdateSizes(); } if (createSaveHandler) { menu.CreateSaveHandler(Folder.Menu); } else { menu.SetToken(null); } menu.UpdateTranslations(); }
void FinishPlacing() { if (_placing) { return; } var position = cam.transform.position; int x = Mathf.RoundToInt(position.x), y = Mathf.RoundToInt(position.y); if (FieldMatrix.Get(x, y, out _)) { Animator.Interpolate( new Color(0.3f, 0f, 0f, DarkenAlpha), new Color(0f, 0f, 0f, DarkenAlpha), 1f) .Type(InterpolationType.Square) .PassValue(v => background.color = v); return; } _placing = true; Animator.Interpolate(DarkenAlpha, 0f, 1f).Type(InterpolationType.Linear) .PassValue(v => { background.color = new Color(0, 0, 0, v); }) .WhenDone(() => { gameObject.SetActive(false); Roots.CreateRoot(x, y, -1, palette.ColorsId); _placing = false; }); }
static void Main(string[] args) { Console.WriteLine("Giai phuong trinh bac 2: \n"); int a, b, c; Console.Write("Nhap a: "); a = int.Parse(Console.ReadLine()); Console.Write("Nhap b: "); b = int.Parse(Console.ReadLine()); Console.Write("Nhap c: "); c = int.Parse(Console.ReadLine()); if (a != 0) { Quadratic ptb2 = new Quadratic(a, b, c); Roots r = ptb2.GiaiPhuongTrinh(a, b, c); if (r.RootsNumber == 0) { Console.WriteLine("Phuong trinh vo nghiem"); } else if (r.RootsNumber == 1) { Console.WriteLine("Phuong trinh co 2 nghiem kep x1 = x2 = {0}", r.Root1); } else { Console.WriteLine("Phuong trinh co hai nghiem phan biet: "); Console.WriteLine("x1 = {0}", r.Root1); Console.WriteLine("x2 = {0}", r.Root2); } } }
public void Solve_Should_Find_Roots() { Roots roots = Solve(1, -2, -3); Assert.AreEqual(3, roots.X1); Assert.AreEqual(-1, roots.X2); }
public void DetectCircularDependencyInComplexGraph() { var a = new Node { Name = "A" }; var b = new Node { Name = "B" }; var c = new Node { Name = "C" }; var d = new Node { Name = "D" }; var e = new Node { Name = "E" }; var f = new Node { Name = "F" }; var g = new Node { Name = "G" }; var h = new Node { Name = "H" }; a.Add(b); a.Add(c); c.Add(g); c.Add(f); g.Add(b); b.Add(d); d.Add(h); d.Add(f); f.Add(e); e.Add(d); var roots = new Roots(); roots.Entangle(a); var serializers = new Serializers(new SerializerFactory()); var stateMaps = new StateMaps(serializers); var persister = new Persister(new InMemoryStorageEngine(), roots, serializers, stateMaps); persister.DetectSerializeAndPersistChanges(); var circularChain = CircularDependencyDetector.Check(serializers[0], stateMaps, serializers); circularChain.IsCircular.ShouldBe(true); circularChain.Path.Count().ShouldBe(4); circularChain.ToString().ShouldBe("F->E->D->F"); }
public Roots Solve(double a, double b, double c) { double d = b * b - (4 * a * c); Roots roots = new Roots(); roots.X1 = (-b + Math.Sqrt(d)) / (2 * a); roots.X2 = (-b - Math.Sqrt(d)) / (2 * a); return roots; }
public void Cut(NodeTree x, NodeTree y) { y.Childrens.Remove(x); y.Degree--; Roots.Add(x); x.Parent = null; x.Mark = false; }
/// <summary> Adds a file object (with the appropriate divisions and pages) to this tree </summary> /// <param name="New_File"> New file object to add </param> /// <param name="Label"> Label for the page containing this file, if it is a new page </param> /// <remarks> This is generally used to add just a single file. To add many files, better logic should be implemented </remarks> public void Add_File(SobekCM_File_Info New_File, string Label) { // Determine the upper case name string systemname_upper = New_File.File_Name_Sans_Extension; // Look for a page/entity which has the same file name, else it will be added to the last division foreach (abstract_TreeNode rootNode in Roots) { if (recursively_add_file(rootNode, New_File, systemname_upper)) { return; } } // If not found, find the last division if (Roots.Count > 0) { if (!Roots[Roots.Count - 1].Page) { // Get his last division Division_TreeNode lastDivision = (Division_TreeNode)Roots[Roots.Count - 1]; // Find the last division then while ((lastDivision.Nodes.Count > 0) && (!lastDivision.Nodes[lastDivision.Nodes.Count - 1].Page)) { lastDivision = (Division_TreeNode)lastDivision.Nodes[lastDivision.Nodes.Count - 1]; } // Add this as a new page on the last division Page_TreeNode newPage = new Page_TreeNode(Label); lastDivision.Add_Child(newPage); // Now, add this file to the page newPage.Files.Add(New_File); } else { // No divisions at all, but pages exist at the top level, which is okay Page_TreeNode pageNode = (Page_TreeNode)Roots[Roots.Count - 1]; // Now, add this file to the page pageNode.Files.Add(New_File); } } else { // No nodes exist, so add a MAIN division node Division_TreeNode newDivNode = new Division_TreeNode("Main", String.Empty); Roots.Add(newDivNode); // Add this as a new page on the new division Page_TreeNode newPage = new Page_TreeNode(Label); newDivNode.Add_Child(newPage); // Now, add this file to the page newPage.Files.Add(New_File); } }
protected int SolveCubic(ref Roots roots, double a, double b, double c, double d) { if (Math.Abs(a) < 1e-14) { return(SolveQuadratic(ref roots, b, c, d)); } return(SolveCubicNormed(ref roots, b / a, c / a, d / a)); }
public void ReduceTree(NodeGrouper nodeGrouper) { var templateMatcher = new TemplateMatcher(nodeGrouper); Roots = Roots.ToDictionary(r => r.Key, r => templateMatcher.Reduce(r.Value)); NoOutputInstructions = NoOutputInstructions.ToDictionary(r => r.Key, r => templateMatcher.Reduce(r.Value)); }
public Roots Solve(double a, double b, double c) { double d = b * b - (4 * a * c); Roots roots = new Roots(); roots.X1 = (-b + Math.Sqrt(d)) / (2 * a); roots.X2 = (-b - Math.Sqrt(d)) / (2 * a); return(roots); }
public void AddChild(long?parentId, long id, T data) { if (Data.ContainsKey(id)) { throw new ArgumentException($"id {id} already exists in tree."); } if (parentId != null && !Data.ContainsKey((long)parentId)) { throw new ArgumentException($"parentId {parentId} not found in tree."); } var link = new NodeLink { Id = id, Parent = parentId }; var depth = 0; if (parentId == null) { if (Roots.Any()) { Links[Roots[Roots.Count - 1]].Next = id; } Roots.Add(id); } else { var parentLink = Links[(long)parentId]; depth = parentLink.Depth + 1; if (parentLink.Child != null) { link.Next = parentLink.Child; } else { Leaves.Remove((long)parentId); } parentLink.Child = id; } // Saves data Data.Add(id, data); // Saves link link.Depth = depth; Links.Add(id, link); // Registers as leaf Leaves.Add(id); }
bool SetIconAutoSingleImpl(DirectoryInfo current, FolderIconCommandArguments options) { if (!current.Exists && options.CreateDirectories) { current.Create(); } var paths = GetRelativePaths(current).ToArray(); var label = paths.FirstOrDefault()?.SubPath; var altLabel = Roots.GetAlternateRootLabels(label).FirstOrDefault(); var labels = string.IsNullOrWhiteSpace(label) ? new string[0] : Paths.Split(label); var name = labels.FirstOrDefault(x => x.ToUpperInvariant() != x && x.Length > 4); var icon = GetCurrentIcon(current); if (icon.IsEmpty || !icon.Exists) { ReportError($"Could not find Folder Icon for <<LINK:{current.FullName}::800>>"); return(false); } var newIcon = icon.ChangeDirectory(current); var ini = new DesktopIniParser(current) { IconResource = newIcon }; var depth = current.GetDepth(options.Root); var verbosity = Math.Min(MAX_VERBOSITY - 1, depth + 1); if (options.LastIcon.FullName != icon.FullName) { verbosity = Math.Min(verbosity, 1); } if (label?.IndexOf(Paths.DirectorySeparatorChar) == -1) { verbosity = Math.Min(verbosity, MANUAL_VERBOSITY - 2); } if (altLabel != null) { verbosity = Math.Min(verbosity, MANUAL_VERBOSITY - 1); } if (name == null || newIcon.FullName.Contains(name)) { verbosity = Math.Min(verbosity, MANUAL_VERBOSITY - 1); } if (newIcon.FullName.Contains("..\\")) { verbosity = Math.Min(verbosity, 2); } ReportProgress(0, new ReportedStatus($"Setting Folder Icon To <<LINK:{newIcon.Resource}||{newIcon.FullName}::500>> for <<LINK:{current.FullName}::800>> [<<LINK:{icon.Info}>>]", options.Command, current.FullName, newIcon.Resource, verbosity: verbosity)); var success = ini.Save(); if (!success) { ReportError($"Unable to save INI for {current.FullName}"); } options.LastIcon = icon; return(true); }
public PersistentSleeper(DateTime expires, CAwaitable awaitable, bool rootify) { _expires = expires; _awaitable = awaitable; if (rootify) { Roots.EntangleAnonymously(this); } }
public CallAfterSleeper(DateTime expires, Action callAfterSleep, bool rootify) { _expires = expires; _callAfterSleep = callAfterSleep; if (rootify) { Roots.EntangleAnonymously(this); } }