public void Intervals_Are_Constructable_From_Distance() { var i = new Interval(IntervalDistance.PerfectUnison); Assert.Equal(0, i.Semitones); Assert.Equal(IntervalDistance.PerfectUnison, i.Distance); }
public void RoundTrip() { var startInstant = Instant.FromUtc(2012, 1, 2, 3, 4, 5) + Duration.FromMilliseconds(670); var endInstant = Instant.FromUtc(2013, 6, 7, 8, 9, 10) + Duration.FromNanoseconds(123456789); var interval = new Interval(startInstant, endInstant); AssertConversions(interval, "{\"Start\":\"2012-01-02T03:04:05.67Z\",\"End\":\"2013-06-07T08:09:10.123456789Z\"}", settings); }
public void testStructure() { // root object CComplexObject obj = definition; java.lang.Integer temp1 = new java.lang.Integer(1); Interval occurrences = new Interval(temp1, temp1); assertCComplexObject(obj, "ENTRY", "at0000", occurrences, 2); // first attribute of root object CAttribute attr = (CAttribute) obj.getAttributes().get(0); assertCAttribute(attr, "subject_relationship", 1); // 2nd level object obj = (CComplexObject) attr.getChildren().get(0); assertCComplexObject(obj, "RELATED_PARTY", null, occurrences, 1); // attribute of 2nd level object attr = (CAttribute) obj.getAttributes().get(0); assertCAttribute(attr, "relationship", 1); // leaf object obj = (CComplexObject) attr.getChildren().get(0); assertCComplexObject(obj, "TEXT", null, occurrences, 1); // attribute of leaf object attr = (CAttribute) obj.getAttributes().get(0); assertCAttribute(attr, "value", 1); // primitive constraint of leaf object CString str = (CString) ((CPrimitiveObject) attr.getChildren().get(0)).getItem(); Assert.AreEqual(null, str.getPattern(), "pattern"); Assert.AreEqual(1, str.getList().size(), "set.size"); Assert.IsTrue(str.getList().contains("self"), "set has"); }
public void Intervals_Are_Constructable_From_Semitones() { var i = new Interval(5); Assert.Equal(5, i.Semitones); Assert.Equal(IntervalDistance.PerfectFourth, i.Distance); }
/// <summary> /// Método estático encargado de la creación de objetos valor <see cref="IInterval"/> /// </summary> /// <remarks> /// Sin comentarios adicionales. /// </remarks> /// <param name="fromTime"> /// Parámetro que indica la hora inicial del intervalo. /// </param> /// <param name="duration"> /// Parámetro que indica la duración del intervalo. /// </param> /// <returns> /// Devuelve objeto de tipo <see cref="IInterval"/> creado. /// </returns> public static IInterval Create(DateTime? fromTime, TimeSpan duration) { // Creamos el objeto valor de periodo de vigencia. IInterval interval = new Interval(fromTime, duration); // Devolvemos el objeto valor creado. return interval; }
public static int GetDistance(Interval interval, int value1, int value2) { var point1 = CalculateValue(interval, value1); var point2 = CalculateValue(interval, value2); var distance = Math.Abs(point1 - point2); return Math.Min(distance, interval.Count - distance); }
/// <summary> /// Initializes a new instance of the AbstractEnvironmentComponent class. /// </summary> public AxisAlignedBoxEnvironmentComponentOld() : base(RS.AABoxEnvName, RS.AABoxEnvNickName, RS.AABoxEnvDescription, RS.icon_AABoxEnvironment, RS.AABoxEnvOldGuid) { Interval interval = new Interval(-RS.boxBoundsDefault, RS.boxBoundsDefault); box = new Box(Plane.WorldXY, interval, interval, interval); }
public void Construction_EqualStartAndEnd() { var interval = new Interval(SampleStart, SampleStart); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleStart, interval.End); Assert.AreEqual(NodaTime.Duration.Zero, interval.Duration); }
protected ComparerResult CompareDecimals(Interval interval, decimal actual) { if (interval.Contains(actual)) return ComparerResult.Equality; return new ComparerResult(interval.ToString()); }
/// <summary> /// Generates a code containing all intervals in a list of intervals of DateTimes. /// </summary> /// <param name="allIntervals"> The intervals to generate code for. </param> /// <param name="varName"> The variable name to use. </param> /// <returns> Returns the generated code for the data. </returns> public static string GenerateCode(Interval<DateTime>[] allIntervals, string varName) { var dateToStr = (Func<DateTime, string>)(d => d == default(DateTime) ? "default(DateTime)" : d.ToString("'new DateTime('yyyy', 'MM', 'dd', 'HH', 'mm', 'ss')'")); var str = string.Format( @" #region {0} = ... // the following snapshot was generated from a good result using the method GenerateCode(""{0}"") var {0} = new [] {{", varName) + string.Join( @", ", allIntervals.Select( i => string.Format( @" // {5} new Interval<DateTime>({0}, PointState.{1}, {2}, PointState.{3}, isPositive: {4})", dateToStr(i.Start), i.StartState, dateToStr(i.End), i.EndState, i.IsPositive ? "true" : "false", i))) + @" }; #endregion "; return str; }
public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) { IList<Interval> result = new List<Interval>(); if(intervals.Count == 0){ result.Add(newInterval); return result; } bool first = true; for(int i=0; i<intervals.Count; i++){ if(intervals[i].end<newInterval.start){ result.Add(intervals[i]); } else if(intervals[i].start>newInterval.end){ if(first){ result.Add(newInterval); first = false; } result.Add(intervals[i]); } else{ newInterval = new Interval(Math.Min(newInterval.start, intervals[i].start), Math.Max(newInterval.end, intervals[i].end)); } } if(first){ result.Add(newInterval); first = false; } return result; }
public void Construct3() { var interval = new Interval(1, "0.2"); Assert.AreEqual(IntervalMode.Interpolate, interval.Mode); Assert.AreEqual(1, interval.Time); Assert.AreEqual("0.2", interval.Value); }
public void GetIntersectionTest() { var A = new Interval(0.0f, 5.0f); var B = new Interval(2.5f, 7.5f); var C = new Interval(6.0f, 10.0f); Interval Temp; Assert.IsTrue(A.GetIntersection(B, out Temp)); Assert.AreEqual(new float[] { 2.5f, 5.0f }, Temp.ToArray()); Assert.IsTrue(B.GetIntersection(A, out Temp)); Assert.AreEqual(new float[] { 2.5f, 5.0f }, Temp.ToArray()); Assert.IsTrue(A.GetIntersection(A, out Temp)); Assert.AreEqual(A.ToArray(), Temp.ToArray()); Assert.IsTrue(B.GetIntersection(C, out Temp)); Assert.AreEqual(new float[] { 6.0f, 7.5f }, Temp.ToArray()); Assert.IsTrue(C.GetIntersection(B, out Temp)); Assert.AreEqual(new float[] { 6.0f, 7.5f }, Temp.ToArray()); Assert.IsTrue(B.GetIntersection(B, out Temp)); Assert.AreEqual(B.ToArray(), Temp.ToArray()); A.GetIntersection(C, out Temp); C.GetIntersection(A, out Temp); Assert.IsFalse(A.GetIntersection(C, out Temp)); Assert.IsFalse(C.GetIntersection(A, out Temp)); }
/// <summary> /// Initializes a new box from a base Plane and three Intervals. /// </summary> /// <param name="basePlane">Orientation plane of the box.</param> /// <param name="xSize">Dimensions along the base plane X-Axis.</param> /// <param name="ySize">Dimensions along the base plane Y-Axis.</param> /// <param name="zSize">Dimensions along the base plane Z-Axis.</param> public Box(Plane basePlane, Interval xSize, Interval ySize, Interval zSize) { m_plane = basePlane; m_dx = xSize; m_dy = ySize; m_dz = zSize; }
public void Construct1() { var interval = new Interval(); Assert.AreEqual(IntervalMode.Interpolate, interval.Mode); Assert.AreEqual(0, interval.Time); Assert.IsNull(interval.Value); }
internal static IEnumerable<Interval> RemoveIntersections(IEnumerable<Interval> source) { var result = new List<Interval>(); Interval last = null; foreach (var next in source) { if (last == null) { last = next; } else if (last.IsContainedIn(next)) { last = new Interval(last.End, next.End); } else if (last.Intersect(next)) { var newInterval = new Interval() { Start = last.Start, End = next.Start }; result.Add(newInterval); last = new Interval() { Start = Math.Min(last.End, next.End), End = Math.Max(last.End, next.End)}; } else { result.Add(next); last = next; } } result.Add(last); return result; }
/// <summary> /// Initializes a new Box that mimics a BoundingBox struct. /// <para>The orientation plane of the Box is coincident with the /// World XY plane.</para> /// </summary> /// <param name="bbox">BoundingBox to mimic.</param> public Box(BoundingBox bbox) { m_plane = Plane.WorldXY; m_dx = new Interval(bbox.m_min.m_x, bbox.m_max.m_x); m_dy = new Interval(bbox.m_min.m_y, bbox.m_max.m_y); m_dz = new Interval(bbox.m_min.m_z, bbox.m_max.m_z); }
// Constructor with initial values. public SurfaceEnvironmentType(Surface srf, bool wrap) { environment = srf; Wrap = wrap; double width, height; srf.GetSurfaceSize(out width, out height); Width = width; Height = height; Interval widthInterval = new Interval(0, width); Interval heightInterval = new Interval(0, height); Interval u = srf.Domain(0); Interval v = srf.Domain(1); Surface refEnvironment = new PlaneSurface(Plane.WorldXY, widthInterval, heightInterval); refEnvironment.SetDomain(0, u); refEnvironment.SetDomain(1, v); RefEnvironment = refEnvironment; Interval uDom = RefEnvironment.Domain(0); Interval vDom = RefEnvironment.Domain(1); minX = 0; maxX = width; minY = 0; maxY = height; }
/// <summary> /// /// </summary> /// <param name="interval"></param> public void ExpandToInclude(Interval interval) { if (interval.Max > Max) Max = interval.Max; if (interval.Min < Min) Min = interval.Min; }
public int Shall_the_result_be_correct_for_an_interval_that_has_been_built_in_reverse_order(Interval<int> value) { var tree = CreateTree(TestEntries().OrderBy(interval => interval.Start).Reverse()); return tree .Search(value) .Count(); }
public int Shall_the_result_be_correct_for_an_interval_that_has_been_built_in_unsorted_order(Interval<int> value) { var tree = CreateTree(TestEntries()); return tree .Search(value) .Count(); }
public void NonEmpty_NotContainedInterval__ReturnsFalse() { // (-10; 10) var a = new Interval(-10, false, 10, false); // (-100; -10) var b = new Interval(-100, false, -10, false); Assert.IsFalse(a.IntersectsWith(b)); Assert.IsFalse(b.IntersectsWith(a)); // [-10; 10) a = new Interval(-10, true, 10, false); // (-100; -10) b = new Interval(-100, false, -10, false); Assert.IsFalse(a.IntersectsWith(b)); Assert.IsFalse(b.IntersectsWith(a)); // (-10; 10) a = new Interval(-10, false, 10, false); // (-100; -10] b = new Interval(-100, false, -10, true); Assert.IsFalse(a.IntersectsWith(b)); Assert.IsFalse(b.IntersectsWith(a)); }
public void ConstructorDefault() { IInterval<int> interval = new Interval<int>(5, 10); Assert.AreEqual(5, interval.LowerBound); Assert.AreEqual(10, interval.UpperBound); }
//If touching, returns unit vector pointing from A towards B //else returns 0,0,0 public static Vector3 CheckRoomTouch(Bounds a, Bounds b, float minOverlap) { Interval a_x = new Interval(a.min.x, a.max.x); Interval a_y = new Interval(a.min.y, a.max.y); Interval a_z = new Interval(a.min.z, a.max.z); Interval b_x = new Interval(b.min.x, b.max.x); Interval b_y = new Interval(b.min.y, b.max.y); Interval b_z = new Interval(b.min.z, b.max.z); int roomTouchX = Interval.CheckTouching(a_x, b_x); int roomTouchY = Interval.CheckTouching(a_y, b_y); int roomTouchZ = Interval.CheckTouching(a_z, b_z); bool roomOverlapX = Interval.CheckOverlap(a_x, b_x, minOverlap); bool roomOverlapY = Interval.CheckOverlap(a_y, b_y, minOverlap); bool roomOverlapZ = Interval.CheckOverlap(a_z, b_z, minOverlap); //-.-- -.-- --.. if(roomOverlapX && roomOverlapY) return Vector3.forward * roomTouchZ; if(roomOverlapZ && roomOverlapY) return Vector3.right * roomTouchX; if(roomOverlapX && roomOverlapZ) return Vector3.up * roomTouchY; return Vector3.zero; }
public void Construction_EqualStartAndEnd() { var interval = new Interval(SampleStart, SampleStart); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleStart, interval.End); Assert.AreEqual(new Duration(0), interval.Duration); }
public void Test_AddInterval() { Interval[] empty = new Interval[] { }; Interval[] result; SortingAlgorithms algo = new SortingAlgorithms(); result = algo.AddInterval(empty, new Interval { start = 0, end = 2 } ); Assert.AreEqual(1, result.Length); result = algo.AddInterval(result, new Interval { start = 3, end = 5 } ); Assert.AreEqual(2, result.Length); result = algo.AddInterval(result, new Interval { start = 4, end = 6 } ); Assert.AreEqual(2, result.Length); result = algo.AddInterval(result, new Interval { start = 1, end = 4 } ); Assert.AreEqual(1, result.Length); }
// Constructor with initial values. public SurfaceEmitterType(Surface srf) { Interval interval = new Interval(0,1); srf.SetDomain(0, interval); srf.SetDomain(1, interval); this.srf = srf; }
public void ConstructorWrongOrder() { IInterval<int> interval = new Interval<int>(10, 5); Assert.AreEqual(5, interval.LowerBound); Assert.AreEqual(10, interval.UpperBound); }
/// <summary> /// Constructor. /// </summary> /// <param name="originalArrivingTime">Time when the vehicle originally planned to arrive at the intersection.</param> /// <param name="remainingDistance">Remaining distance of the vehicle to the intersection.</param> /// <param name="blockingTime">Time interval when the vehicle is going to block the intersection.</param> /// <param name="willWaitInFrontOfIntersection">Flag whether vehicle will wait befor intersection or proceed crossing it.</param> public CrossingVehicleTimes(double originalArrivingTime, double remainingDistance, Interval<double> blockingTime, bool willWaitInFrontOfIntersection) { this.originalArrivingTime = originalArrivingTime; this.remainingDistance = remainingDistance; this.blockingTime = blockingTime; this.willWaitInFrontOfIntersection = willWaitInFrontOfIntersection; }
public string IntervalFrom(string startNote, int interval, Interval direction) { int i; for( i = 0; i < scale.Length; i++ ) { if( scale[i] == startNote ) break; } if (i >= scale.Length) throw new Exception("Invalid start note provided!!!"); if (direction == Interval.Up) // Move right { interval--; return scale[(i + interval) % 7]; } else // Move left { interval--; while (interval > 0) { i--; if (i < 0) i = 6; interval--; } return scale[i]; } }
/// <summary> /// Return the text associated with the tokens in the interval from the /// original token stream but with the alterations given to this rewriter. /// </summary> /// <remarks> /// Return the text associated with the tokens in the interval from the /// original token stream but with the alterations given to this rewriter. /// The interval refers to the indexes in the original token stream. /// We do not alter the token stream in any way, so the indexes /// and intervals are still consistent. Includes any operations done /// to the first and last token in the interval. So, if you did an /// insertBefore on the first token, you would get that insertion. /// The same is true if you do an insertAfter the stop token. /// </remarks> public virtual string GetText(Interval interval) { return(GetText(DefaultProgramName, interval)); }
public WhereStructure(string leftColumn, string comparisionOperator, string rightColumn, Interval sourceInterval) { _comparisionOperator = comparisionOperator; _leftColumn = leftColumn; _rightExpr = rightColumn; _string = _leftColumn + " " + _comparisionOperator + " " + _rightExpr; _sourceInterval = sourceInterval; }
/// <summary> /// Get off-set timestamp /// </summary> /// <param name="timestamp">Base timestamp</param> /// <param name="interval">Time interval</param> /// <param name="sticks">Number of sticks</param> /// <returns>Calculated timestamp</returns> public long GetFromUnixTime(long timestamp, Interval interval, int sticks) { var seconds = IntervalToSeconds(interval); return(timestamp - (seconds * sticks)); }
public Toricmanifold FinalConstraintCombination(float samplingRateN, Vector3 vantageA, float deviationA, Vector3 vantageB, float deviationB, Vector2 distanceToA, Vector2 distanceToB, Vector2 desPosA, Vector2 desPosB, Vector2 visibilityValues) { samplingRateN = Mathf.Clamp(samplingRateN, 1, samplingRateN); float dPHI = 1f / (2 * Mathf.Pow(samplingRateN / 2, 1.0f / 3)); float dTHETA = 1f / (4 * Mathf.Pow(Mathf.Pow(samplingRateN / 2, 2), 1.0f / 3)); float dALPHA = 1f / (samplingRateN); List <Toricmanifold> possiblePositions = new List <Toricmanifold>(); Dictionary <float, Interval> ThetaPhi = getThetaIntervallFromVantageBothTargets(vantageA, deviationA, vantageB, deviationB, dPHI); Dictionary <float, Interval> AlphaTheta = _alphaComputer.getIntervalOfAcceptedAlpha(distanceToA, distanceToB, dTHETA); Dictionary <float, Interval> phiBetaB = _vantageCons.getPositionFromVantageOneTarget(B, vantageB, deviationB, dPHI); foreach (float phi in possiblePhiIntersect) { Interval thetaInvPhi, betaInvB; ThetaPhi.TryGetValue(phi, out thetaInvPhi); float[] possibleThetas = thetaInvPhi.filterArray(AlphaTheta.Keys.ToArray()); phiBetaB.TryGetValue(mergeKey(phi, phiBetaB.Keys.ToArray(), dPHI), out betaInvB); foreach (float theta in possibleThetas) { Interval alphaDISTTheta, alphaOSP, alphaVANTThetaPhi; AlphaTheta.TryGetValue(theta, out alphaDISTTheta); alphaOSP = _alphaComputer.getAlphaIntervalFromOnscreenPositions(desPosA, desPosB); alphaVANTThetaPhi = _alphaComputer.GetVantageAlphaInterval(theta, betaInvB); Debug.Log("AlphaOnScreenPosition: " + alphaOSP * Mathf.Rad2Deg + "Alpha DistanceToTargets: " + alphaDISTTheta * Mathf.Rad2Deg + "Alpha Vantage Constraint: " + alphaVANTThetaPhi * Mathf.Rad2Deg); Interval alphaSecond = alphaOSP.Intersect(alphaDISTTheta); if (alphaSecond != null) { Interval alphaFINAL = alphaSecond.Intersect(alphaVANTThetaPhi); if (alphaFINAL != null) { alphaFINAL._samplingRate = dALPHA; foreach (float alpha in alphaFINAL.getEveryValue()) { possiblePositions.Add(new Toricmanifold(alpha * Mathf.Rad2Deg, theta * Mathf.Rad2Deg, phi * Mathf.Rad2Deg, _target1, _target2)); } Debug.Log("alphaFinal: " + alphaFINAL); } } } } if (possiblePositions.Count == 0) { throw new Exception("No solution possible"); } float[] visibilityScores; List <KeyValuePair <float, Toricmanifold> > tmVis = new List <KeyValuePair <float, Toricmanifold> >(); foreach (Toricmanifold tm in possiblePositions) { float visibility = visibilityCheck(tm); tmVis.Add(new KeyValuePair <float, Toricmanifold>(visibility, tm)); } Lookup <float, Toricmanifold> TableVisTm = (Lookup <float, Toricmanifold>)tmVis.ToLookup((item) => item.Key, (item) => item.Value); visibilityScores = new Interval(visibilityValues.x, visibilityValues.y).filterArray(TableVisTm.Select(g => g.Key).ToArray()); float topVis = Mathf.Max(visibilityScores); List <KeyValuePair <float, Toricmanifold> > bestVisTm = tmVis.Where(g => g.Key == topVis).ToList(); return(bestVisTm.First().Value); }
public override void Flush() { if (Interval.Duration == null) { base.Flush(); return; } // Sort all the postings we saw by date ascending // [DM] Enumerable.OrderBy is a stable sort that preserve original positions for equal items AllPosts = AllPosts.OrderBy(p => p, new IntervalPostCompare()).ToList(); // only if the interval has no start use the earliest post if (!(Interval.Begin.HasValue && Interval.FindPeriod(Interval.Begin.Value))) { // Determine the beginning interval by using the earliest post if (AllPosts.Any() && !Interval.FindPeriod(AllPosts.First().GetDate())) { throw new LogicError(LogicError.ErrorMessageFailedToFindPeriodForIntervalReport); } } // Walk the interval forward reporting all posts within each one // before moving on, until we reach the end of all_posts bool sawPosts = false; for (int i = 0; i < AllPosts.Count;) { Post post = AllPosts[i]; Logger.Debug("filters.interval", () => String.Format("Considering post {0} = {1}", post.GetDate(), post.Amount)); Logger.Debug("filters.interval", () => String.Format("interval is:{0}", DebugInterval(Interval))); if (Interval.Finish.HasValue && post.GetDate() >= Interval.Finish.Value) { throw new InvalidOperationException("assert(! interval.finish || post->date() < *interval.finish)"); } if (Interval.WithinPeriod(post.GetDate())) { Logger.Debug("filters.interval", () => "Calling subtotal_posts::operator()"); base.Handle(post); ++i; sawPosts = true; } else { if (sawPosts) { Logger.Debug("filters.interval", () => "Calling subtotal_posts::report_subtotal()"); ReportSubtotal(Interval); sawPosts = false; } else if (GenerateEmptyPosts) { // Generate a null posting, so the intervening periods can be // seen when -E is used, or if the calculated amount ends up // being non-zero Xact nullXact = Temps.CreateXact(); nullXact.Date = Interval.InclusiveEnd.Value; Post nullPost = Temps.CreatePost(nullXact, EmptytAccount); nullPost.Flags |= SupportsFlagsEnum.POST_CALCULATED; nullPost.Amount = new Amount(0); base.Handle(nullPost); ReportSubtotal(Interval); } Logger.Debug("filters.interval", () => "Advancing interval"); ++Interval; } } // If the last postings weren't reported, do so now. if (sawPosts) { Logger.Debug("filters.interval", () => "Calling subtotal_posts::report_subtotal() at end"); ReportSubtotal(Interval); } // Tell our parent class to flush base.Flush(); }
private async void Calculate(object sender, RoutedEventArgs e) { try { char[] message = messageTextBox.Text.ToCharArray(); Interval interval = new Interval(); TextBox[] probablities = new TextBox[itemsNumber]; char[] letters = new char[itemsNumber]; for (int i = 0; i < itemsNumber; i++) { probablities[i] = alphabet[i, 1]; var characters = alphabet[i, 0].Text.ToCharArray(); letters[i] = characters[0]; } bool isMessageInAlphabet = false; for (int i = 0; i < message.Length; i++) { isMessageInAlphabet = checkLetterInAlphabet(message[i], letters); if (!isMessageInAlphabet) { break; } } if (!isMessageInAlphabet) { ContentDialog dialog = new ContentDialog { Title = "Error", Content = "Wiadomość niepoprawna", CloseButtonText = "ok" }; ContentDialogResult result = await dialog.ShowAsync(); return; } try { subIntervalsGrid.Children.Clear(); checkProbability(probablities); decimal[] probs = parseProbabilities(probablities); probs = ArithmeticCoding.MakeProportions(probs); for (int p = 0; p < message.GetLength(0); p++) { Interval[] intervals = ArithmeticCoding.MakeSubintervals(interval, probs); addSubinterval(intervals, message[p], letters); interval = ArithmeticCoding.SetCurrentInterval(intervals, letters, message[p]); } resultCodingGrid.Visibility = Visibility.Visible; resultCodingGrid.Opacity = 0; resultCodingGrid.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; resultCodingGrid.Opacity = 1; resultCodingTextBlock.Text = "Wynik: " + ((interval.l + interval.r) / 2).ToString(); subIntervalsGrid.Visibility = Visibility.Visible; subIntervalsGrid.Opacity = 0; subIntervalsGrid.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; subIntervalsGrid.Opacity = 1; } catch (Exception ex) { ContentDialog dialog = new ContentDialog { Title = "Error", Content = ex.Message, CloseButtonText = "ok" }; ContentDialogResult result = await dialog.ShowAsync(); } } catch (Exception ex) { ContentDialog dialog = new ContentDialog { Title = "Error", Content = ex.Message, CloseButtonText = "ok" }; ContentDialogResult result = await dialog.ShowAsync(); } }
public virtual string GetText(string programName, Interval interval) { IList <TokenStreamRewriter.RewriteOperation> rewrites; if (!programs.TryGetValue(programName, out rewrites)) { rewrites = null; } int start = interval.a; int stop = interval.b; // ensure start/end are in range if (stop > tokens.Size - 1) { stop = tokens.Size - 1; } if (start < 0) { start = 0; } if (rewrites == null || rewrites.Count == 0) { return(tokens.GetText(interval)); } // no instructions to execute StringBuilder buf = new StringBuilder(); // First, optimize instruction stream IDictionary <int, TokenStreamRewriter.RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex(rewrites); // Walk buffer, executing instructions and emitting tokens int i = start; while (i <= stop && i < tokens.Size) { TokenStreamRewriter.RewriteOperation op; if (indexToOp.TryGetValue(i, out op)) { indexToOp.Remove(i); } // remove so any left have index size-1 IToken t = tokens.Get(i); if (op == null) { // no operation at that index, just dump token if (t.Type != TokenConstants.EOF) { buf.Append(t.Text); } i++; } else { // move to next token i = op.Execute(buf); } } // execute operation and skip // include stuff after end if it's last index in buffer // So, if they did an insertAfter(lastValidIndex, "foo"), include // foo if end==lastValidIndex. if (stop == tokens.Size - 1) { // Scan any remaining operations after last token // should be included (they will be inserts). foreach (TokenStreamRewriter.RewriteOperation op in indexToOp.Values) { if (op.index >= tokens.Size - 1) { buf.Append(op.text); } } } return(buf.ToString()); }
/** Get the text matched so far for the current token. */ public String GetText(ICharStream input) { // index is first lookahead char, don't include. return(input.GetText(Interval.Of(startIndex, input.Index - 1))); }
// Added a method for comparing intervals, because the Equals method had not been overriden on Interval private static bool IntervalsAreEqual(Interval expected, Interval actual) { return(expected.Min == actual.Min && expected.Max == actual.Max && expected.Width == actual.Width); }
/// <summary> /// Return the text from the original tokens altered per the /// instructions given to this rewriter. /// </summary> /// <remarks> /// Return the text from the original tokens altered per the /// instructions given to this rewriter. /// </remarks> public virtual string GetText() { return(GetText(DefaultProgramName, Interval.Of(0, tokens.Size - 1))); }
public void TestCopyConstructor() { Assert.IsTrue(IntervalsAreEqual(Interval.Create(3, 4), Interval.Create(3, 4))); Assert.IsTrue(IntervalsAreEqual(Interval.Create(3, 4), Interval.Create(Interval.Create(3, 4)))); }
/// <summary> /// Instantiates the reservoir /// </summary> /// <param name="instanceName">The name of the reservoir instance</param> /// <param name="numOfInputNodes">Number of reservoir inputs</param> /// <param name="inputRange">Range of input values</param> /// <param name="settings">Reservoir settings</param> /// <param name="augmentedStates">Specifies whether this reservoir will add augmented states to output predictors</param> /// <param name="randomizerSeek"> /// A value greater than or equal to 0 will always ensure the same initialization of the internal /// random number generator and therefore the same reservoir structure, which is good for tuning purposes. /// A value less than 0 causes a fully random initialization each time creating a reservoir instance. /// </param> public Reservoir(string instanceName, int numOfInputNodes, Interval inputRange, ReservoirSettings settings, bool augmentedStates, int randomizerSeek = -1) { //Set instance name _instanceName = instanceName; //Copy settings _settings = settings.DeepClone(); //Random generator initialization if (randomizerSeek < 0) { _rand = new Random(); } else { _rand = new Random(randomizerSeek); } //Prepare neuron buffers //Input neurons _inputNeurons = new INeuron[numOfInputNodes]; for (int i = 0; i < numOfInputNodes; i++) { if (_settings.InputCoding == CommonEnums.InputCodingType.Analog) { //Analog input _inputNeurons[i] = new InputAnalogNeuron(i, inputRange); } else { //Spiking input _inputNeurons[i] = new InputSpikingNeuron(i, inputRange, _settings.InputDuration); } } //Pools _numOfPredictors = 0; List <INeuron> allNeurons = new List <INeuron>(); int neuronGlobalFlatIdx = 0; int totalNumOfNeurons = 0; _poolNeuronsCollection = new List <INeuron[]>(_settings.PoolSettingsCollection.Count); for (int poolID = 0; poolID < _settings.PoolSettingsCollection.Count; poolID++) { PoolSettings poolSettings = _settings.PoolSettingsCollection[poolID]; totalNumOfNeurons += poolSettings.Dim.Size; _numOfPredictors += poolSettings.RouteToReadout ? poolSettings.Dim.Size : 0; INeuron[] poolNeurons = new INeuron[poolSettings.Dim.Size]; //Retainment rates double[] retRates = new double[poolSettings.Dim.Size]; retRates.Populate(0); if (poolSettings.RetainmentNeuronsFeature) { int[] indices = new int[poolSettings.Dim.Size]; indices.ShuffledIndices(_rand); int numOfRetNeurons = (int)Math.Round(poolSettings.RetainmentNeuronsDensity * poolSettings.Dim.Size, 0); for (int i = 0; i < numOfRetNeurons; i++) { retRates[indices[i]] = _rand.NextDouble(poolSettings.RetainmentMinRate, poolSettings.RetainmentMaxRate, false, RandomClassExtensions.DistributionType.Uniform); } } //Neuron signal types distribution CommonEnums.NeuronSignalType[] sigTypes = new CommonEnums.NeuronSignalType[poolSettings.Dim.Size]; sigTypes.Populate(CommonEnums.NeuronSignalType.Excitatory); int[] inhibitoryIndices = new int[poolSettings.Dim.Size]; inhibitoryIndices.ShuffledIndices(_rand); int numOfInhibitoryNeurons = (int)Math.Round(poolSettings.InhibitoryNeuronsDensity * poolSettings.Dim.Size, 0); for (int i = 0; i < numOfInhibitoryNeurons; i++) { sigTypes[inhibitoryIndices[i]] = CommonEnums.NeuronSignalType.Inhibitory; } //Instantiate neurons int neuronPoolIdx = 0; for (int x = 0; x < poolSettings.Dim.X; x++) { for (int y = 0; y < poolSettings.Dim.Y; y++) { for (int z = 0; z < poolSettings.Dim.Z; z++) { NeuronPlacement placement = new NeuronPlacement(neuronGlobalFlatIdx, poolID, neuronPoolIdx, x, y, z); IActivationFunction activation = null; double bias = 0; if (sigTypes[neuronPoolIdx] == CommonEnums.NeuronSignalType.Excitatory) { //Activation and bias for Excitatory neuron activation = ActivationFactory.Create(poolSettings.ExcitatoryActivation); bias = _rand.NextDouble(poolSettings.ExcitatoryBias.Min, poolSettings.ExcitatoryBias.Max, poolSettings.ExcitatoryBias.RandomSign, poolSettings.ExcitatoryBias.DistrType); } else { //Activation and bias for Inhibitory neuron activation = ActivationFactory.Create(poolSettings.InhibitoryActivation); bias = _rand.NextDouble(poolSettings.InhibitoryBias.Min, poolSettings.InhibitoryBias.Max, poolSettings.InhibitoryBias.RandomSign, poolSettings.InhibitoryBias.DistrType); } //Neuron instance if (activation.OutputSignalType == ActivationFactory.FunctionOutputSignalType.Spike) { //Spiking neuron poolNeurons[neuronPoolIdx] = new ReservoirSpikingNeuron(placement, sigTypes[neuronPoolIdx], activation, bias ); } else { //Analog neuron poolNeurons[neuronPoolIdx] = new ReservoirAnalogNeuron(placement, sigTypes[neuronPoolIdx], activation, bias, retRates[neuronPoolIdx] ); } allNeurons.Add(poolNeurons[neuronPoolIdx]); ++neuronPoolIdx; ++neuronGlobalFlatIdx; } } } _poolNeuronsCollection.Add(poolNeurons); } //All neurons flat structure _neurons = allNeurons.ToArray(); //Interconnections //Banks allocations _neuronInputConnectionsCollection = new List <ISynapse> [totalNumOfNeurons]; _neuronNeuronConnectionsCollection = new List <ISynapse> [totalNumOfNeurons]; for (int n = 0; n < totalNumOfNeurons; n++) { _neuronInputConnectionsCollection[n] = new List <ISynapse>(); _neuronNeuronConnectionsCollection[n] = new List <ISynapse>(); } //Wiring setup //Pools internal connections for (int poolID = 0; poolID < _poolNeuronsCollection.Count; poolID++) { //Input connection SetPoolInputConnections(poolID, _settings.PoolSettingsCollection[poolID]); //Pool interconnection if (_settings.PoolSettingsCollection[poolID].InterconnectionAvgDistance > 0) { //Required to keep average distance SetPoolDistInterconnections(poolID, _settings.PoolSettingsCollection[poolID]); } else { //Not required to keep average distance SetPoolRandInterconnections(poolID, _settings.PoolSettingsCollection[poolID]); } } //Add pool to pool connections foreach (ReservoirSettings.PoolsInterconnection poolsInterConn in _settings.PoolsInterconnectionCollection) { SetPool2PoolInterconnections(poolsInterConn); } //Spectral radius if (_settings.SpectralRadius > 0) { double maxEigenValue = ComputeMaxEigenValue(); if (maxEigenValue == 0) { throw new Exception("Invalid reservoir weights. Max eigenvalue is 0."); } double scale = _settings.SpectralRadius / maxEigenValue; //Scale internal weights foreach (List <ISynapse> connCollection in _neuronNeuronConnectionsCollection) { foreach (ISynapse conn in connCollection) { conn.Weight *= scale; } } } //Augmented states _augmentedStatesFeature = augmentedStates; return; }
public override Widget build(BuildContext context) { D.assert(MaterialD.debugCheckHasMaterialLocalizations(context)); ThemeData themeData = Theme.of(context); AppBarTheme appBarTheme = AppBarTheme.of(context); ScaffoldState scaffold = Scaffold.of(context, nullOk: true); ModalRoute parentRoute = ModalRoute.of(context); bool hasDrawer = scaffold?.hasDrawer ?? false; bool hasEndDrawer = scaffold?.hasEndDrawer ?? false; bool canPop = parentRoute?.canPop ?? false; bool useCloseButton = parentRoute is PageRoute && ((PageRoute)parentRoute).fullscreenDialog; IconThemeData appBarIconTheme = this.widget.iconTheme ?? appBarTheme.iconTheme ?? themeData.primaryIconTheme; TextStyle centerStyle = this.widget.textTheme?.title ?? appBarTheme.textTheme?.title ?? themeData.primaryTextTheme.title; TextStyle sideStyle = this.widget.textTheme?.body1 ?? appBarTheme.textTheme?.body1 ?? themeData.primaryTextTheme.body1; if (this.widget.toolbarOpacity != 1.0f) { float opacity = new Interval(0.25f, 1.0f, curve: Curves.fastOutSlowIn).transform(this.widget.toolbarOpacity); if (centerStyle?.color != null) { centerStyle = centerStyle.copyWith(color: centerStyle.color.withOpacity(opacity)); } if (sideStyle?.color != null) { sideStyle = sideStyle.copyWith(color: sideStyle.color.withOpacity(opacity)); } appBarIconTheme = appBarIconTheme.copyWith( opacity: opacity * (appBarIconTheme.opacity ?? 1.0f) ); } Widget leading = this.widget.leading; if (leading == null && this.widget.automaticallyImplyLeading) { if (hasDrawer) { leading = new IconButton( icon: new Icon(Icons.menu), onPressed: this._handleDrawerButton, tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip); } else { if (canPop) { leading = useCloseButton ? (Widget) new CloseButton() : new BackButton(); } } } if (leading != null) { leading = new ConstrainedBox( constraints: BoxConstraints.tightFor(width: AppBarUtils._kLeadingWidth), child: leading); } Widget title = this.widget.title; if (title != null) { title = new DefaultTextStyle( style: centerStyle, softWrap: false, overflow: TextOverflow.ellipsis, child: title); } Widget actions = null; if (this.widget.actions != null && this.widget.actions.isNotEmpty()) { actions = new Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: this.widget.actions); } else if (hasEndDrawer) { actions = new IconButton( icon: new Icon(Icons.menu), onPressed: this._handleDrawerButtonEnd, tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip); } Widget toolbar = new NavigationToolbar( leading: leading, middle: title, trailing: actions, centerMiddle: this.widget._getEffectiveCenterTitle(themeData).Value, middleSpacing: this.widget.titleSpacing); Widget appBar = new ClipRect( child: new CustomSingleChildLayout( layoutDelegate: new _ToolbarContainerLayout(), child: IconTheme.merge( data: appBarIconTheme, child: new DefaultTextStyle( style: sideStyle, child: toolbar) ) ) ); if (this.widget.bottom != null) { appBar = new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: new List <Widget> { new Flexible( child: new ConstrainedBox( constraints: new BoxConstraints(maxHeight: Constants.kToolbarHeight), child: appBar ) ), this.widget.bottomOpacity == 1.0f ? (Widget)this.widget.bottom : new Opacity( opacity: new Interval(0.25f, 1.0f, curve: Curves.fastOutSlowIn).transform(this.widget .bottomOpacity), child: this.widget.bottom ) } ); } if (this.widget.primary) { appBar = new SafeArea( top: true, child: appBar); } appBar = new Align( alignment: Alignment.topCenter, child: appBar); if (this.widget.flexibleSpace != null) { appBar = new Stack( fit: StackFit.passthrough, children: new List <Widget> { this.widget.flexibleSpace, appBar } ); } Brightness brightness = this.widget.brightness ?? appBarTheme.brightness ?? themeData.primaryColorBrightness; SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark; return(new AnnotatedRegion <SystemUiOverlayStyle>( value: overlayStyle, child: new Material( color: this.widget.backgroundColor ?? appBarTheme.color ?? themeData.primaryColor, elevation: this.widget.elevation ?? appBarTheme.elevation ?? _defaultElevation, child: appBar ))); }
public void TestCentre() { Assert.AreEqual(6.5, Interval.Create(4, 9).Centre, 1E-10); }
public void IntervalLength() { var interval = new Interval(-1, 4); Assert.AreEqual(5, interval.Length); }
private void RequestIntervalHistory(string symbol, Interval interval, DateTime dtStart, DateTime dtEnd) { RequestIntervalHistory(symbol, (int)interval, dtStart, dtEnd); }
public SpectralPoint(Interval <double> seconds, Interval <double> hertz, double value) { this.Seconds = seconds; this.Hertz = hertz; this.Value = value; }
public void IntervalLength_0() { var interval = new Interval(4, 4); Assert.AreEqual(0, interval.Length); }
private string GetJsonState() { return("[" + ((Enabled) ? "true" : "false") + "," + Interval.ToString(CultureInfo.InvariantCulture) + "]"); }
public void InvalidIntervalBoundsException_Test() { var interval1 = new Interval(2, 1); }
public void FloatIntervalLengthTests(float start, float end, float expected) { var interval = new Interval<float>(start, end); Assert.That(interval.Length(), Is.EqualTo(expected)); }
public static void WriteInterval1D(GH_IWriter writer, string itemName, Interval data) { writer.SetInterval1D(itemName, data.ToIO()); }
public void ConstructorTest() { var floatInterval = new Interval<float>(1.0f, 2.0f); }
public void DoubleIntervalLengthTests(double start, double end, double expected) { var interval = new Interval<double>(start, end); Assert.That(interval.Length(), Is.EqualTo(expected)); }
/// <summary> /// Builds minimum/maximum function for the given interval. The method is used directly in AndM and OrM, and as a part of calculation in other operators. /// </summary> /// <param name="operands"></param> /// <param name="output"></param> /// <param name="minimum"></param> internal static void GetMinMax(BinaryInterval operands, ref IntervalSet output, bool minimum) { //Find all points where operand1 = operand2 for the given interval Polynomial poly1 = Interval.GetPolynomial(operands.Coefficients1); Polynomial poly2 = Interval.GetPolynomial(operands.Coefficients2); Polynomial difference = poly1 - poly2; if (Interval.IsEmpty(difference)) //both opearands are equal { output.AddInterval(new Interval(output, operands.LowerBound, operands.UpperBound, poly1)); } else { decimal[] roots = Interval.RealRoots(difference, operands.LowerBound, operands.UpperBound); if (roots.Length == 0) { //just find out which function is higher for the whole interval double r1 = poly1.Evaluate(new Complex((double)operands.LowerBound)).Re; double r2 = poly2.Evaluate(new Complex((double)operands.LowerBound)).Re; if ((minimum && r1 <= r2) || (!minimum && r1 > r2)) { output.AddInterval(new Interval(output, operands.LowerBound, operands.UpperBound, poly1)); } else { output.AddInterval(new Interval(output, operands.LowerBound, operands.UpperBound, poly2)); } } else { List <decimal> crossPoints = new List <decimal>(); crossPoints.AddRange(roots); if (!crossPoints.Contains(operands.LowerBound)) { crossPoints.Add(operands.LowerBound); } if (!crossPoints.Contains(operands.UpperBound)) { crossPoints.Add(operands.UpperBound); } crossPoints.Sort(); //Declares that value of operand1 is higher than the value of operand2 for the given range; for (int i = 0; i < crossPoints.Count() - 1; i++) { bool firstIsPreffered; if (roots.Contains(crossPoints[i])) { double deriv1 = poly1.Differentiate(new Complex((double)crossPoints[i])).Re; double deriv2 = poly2.Differentiate(new Complex((double)crossPoints[i])).Re; firstIsPreffered = (minimum && deriv1 < deriv2) || (!minimum && deriv1 > deriv2); } else { //it must be the second one, then double deriv1 = poly1.Differentiate(new Complex((double)crossPoints[i + 1])).Re; double deriv2 = poly2.Differentiate(new Complex((double)crossPoints[i + 1])).Re; firstIsPreffered = (minimum && deriv2 < deriv1) || (!minimum && deriv2 > deriv1); } output.AddInterval(new Interval(output, crossPoints[i], crossPoints[i + 1], firstIsPreffered ? poly1 : poly2)); } } } }
public void IntIntervalLengthTests(int start, int end, int expected) { var interval = new Interval<int>(start, end); Assert.That(interval.Length(), Is.EqualTo(expected)); }
// Calculate intervals in which all three flags on a Frame are set to true private void CalculateIntervals() { // firstIndex variable represents the first index in an interval of consequtive frames that meet all three requirements int firstIndex = 0; int lastIndex = 0; // Re-arrange global list of Frames by position, in ascending order framesList.Sort((x, y) => x.Position.CompareTo(y.Position)); do { // Check if frame at firstIndex meets all three requirements if (framesList[firstIndex].MeetsCSReq && framesList[firstIndex].MeetsS1Req && framesList[firstIndex].MeetsS2Req) { /*-------------------------------------firstIndex FOUND-------------------------------------*/ // Check if this firstIndex found is the last one in the list if (firstIndex == (framesList.Count - 1)) { // Create Interval object Interval interval = new Interval(firstIndex, firstIndex); interval.CalculateAverageCorrelation(framesList); interval.CalculateAverageSignalOne(framesList); interval.CalculateAverageSignalTwo(framesList); // Add interval to intervalsList intervalsList.Add(interval); } else { // Move to the next index in search for interval end lastIndex = firstIndex + 1; do { // Check if frame at lastIndex meets all three requirements if (framesList[lastIndex].MeetsCSReq && framesList[lastIndex].MeetsS1Req && framesList[lastIndex].MeetsS2Req) { // Check if frame at lastIndex is the last frame in list if (lastIndex == (framesList.Count - 1)) { // Create Interval Interval interval = new Interval(firstIndex, lastIndex); interval.CalculateAverageCorrelation(framesList); interval.CalculateAverageSignalOne(framesList); interval.CalculateAverageSignalTwo(framesList); // Add interval to intervalsList intervalsList.Add(interval); } else { // Increment lastIndex lastIndex++; } } else { // Create Interval object Interval interval = new Interval(firstIndex, (lastIndex - 1)); interval.CalculateAverageCorrelation(framesList); interval.CalculateAverageSignalOne(framesList); interval.CalculateAverageSignalTwo(framesList); // Add interval to intervalsList intervalsList.Add(interval); // Move firstIndex to the next index after this newly created interval firstIndex = lastIndex + 1; // Break out of the loop of finding the (already found) lastIndex break; } } while (lastIndex < framesList.Count); } } else { // Increment firstIndex firstIndex++; } } while (firstIndex < framesList.Count); }
public void ContainsTests<T>(Interval<T> interval, T point, bool expected) where T : struct, IComparable { Assert.That(interval.Contains(point), Is.EqualTo(expected)); }
public static void uniform(MklRng stream, Interval <double> range, Span <double> dst) => VSL.vdRngUniform(0, stream.Source, dst.Length, ref head(dst), range.Left, range.Right).ThrowOnError();
public ReportsCompiler(IReportAccumulator reportAccumulator, IStandardReportService standardReportService, Interval interval) { _reportAccumulator = reportAccumulator; _standardReportService = standardReportService; _interval = interval; }