protected static void GuerillaPreProcessMethod(BinaryReader binaryReader, IList<tag_field> fields)
 {
     var field = fields.Last(x => x.type != field_type._field_terminator);
     fields.Remove(field);
     field = fields.Last(x => x.type != field_type._field_terminator);
     fields.Remove(field);
 }
        private IList<TripleExponentialEntry> BuildLastSeason(IList<TripleExponentialEntry> currSeason,
                                                              IEnumerable<DataEntry> dataEntries, int currPeriod)
        {
            //building the last season is similar to NextSeason, but uses the same Ft and Tt once calculated for the first entry.
            var currentFt = currSeason.Last().Ft;
            var currentTt = currSeason.Last().Tt;
            double currentSt = currSeason.Last().St, lastSt = currSeason.Last().St;
            var lastActual = dataEntries.Last().Value;
            IList<TripleExponentialEntry> newSeason = new List<TripleExponentialEntry>();

            currentFt = (_alpha*(lastActual/lastSt)) + ((1 - _alpha)*(currentTt + currentFt));
            currentTt = (_beta*(currentFt - currSeason.Last().Ft)) + ((1 - _beta)*currentTt);

            for (var currSeasonIndex = 1; currSeasonIndex <= _periodsPerSeason; currSeasonIndex++)
            {
                var lastPeriodActual =
                    dataEntries.ElementAt((currPeriod + currSeasonIndex) - _periodsPerSeason - 2).Value;
                var lastPeriodFt = currSeason.ElementAt(currSeasonIndex - 1).Ft;
                var lastPeriodSt = currSeason.ElementAt(currSeasonIndex - 1).St;

                currentSt = (_gamma*(lastPeriodActual/lastPeriodFt)) + ((1 - _gamma)*lastPeriodSt);

                newSeason.Add(new TripleExponentialEntry
                    {
                        Ft = currentFt,
                        Tt = currentTt,
                        St = currentSt,
                        Forecast = (currentFt + (currentTt*currSeasonIndex))*currentSt
                    });
            }

            return newSeason;
        }
Example #3
1
        public void Invoke(char[] code)
        {
            Tokens = new List<CToken>();
              var currentToken = new StringBuilder();
              // todo remove whitespace and comments

              foreach (char c in code)
              {
            if (char.IsWhiteSpace(c))
            {
              continue;
            }
            switch (c)
            {
              case Punctuations.OPEN_PARENS:
            Tokens.Add(new CToken(currentToken.ToString(), NodeType.Caller));
            Tokens.Add(new CToken(Punctuations.OPEN_PARENS.ToString(), NodeType.Punctuation));
            currentToken = new StringBuilder();
            break;
              case Punctuations.CLOSE_PARENS:
            Tokens.Add(new CToken(currentToken.ToString(), NodeType.Variable));
            Tokens.Add(new CToken(Punctuations.CLOSE_PARENS.ToString(), NodeType.Punctuation));
            currentToken = new StringBuilder();
            break;
              case Punctuations.COMMA:
            if (currentToken.Length != 0)
            {
              Tokens.Add(new CToken(currentToken.ToString(), NodeType.Variable));
            }
            Tokens.Add(new CToken(Punctuations.COMMA.ToString(), NodeType.Punctuation));
            currentToken = new StringBuilder();
            break;
              case Punctuations.DOUBLE_QUOTE:
            if (currentToken.Length == 0)
            {
              Tokens.Add(new CToken(Punctuations.DOUBLE_QUOTE.ToString(), NodeType.Punctuation));
            }
            else
            {
              Tokens.Add(new CToken(currentToken.ToString(), NodeType.String));
              Tokens.Add(new CToken(Punctuations.DOUBLE_QUOTE.ToString(), NodeType.Punctuation));
              currentToken = new StringBuilder();
            }
            break;
              case Punctuations.SEMI_COL:
            {
              Tokens.Add(new CToken(Punctuations.SEMI_COL.ToString(), NodeType.Punctuation));
              break;
            }
            }
            if (char.IsLetterOrDigit(c) || (Tokens.Last() != null && Tokens.Last().Value == "\"" && c != '"'))
            {
              currentToken.Append(c);
            }
              }
        }
 public PropertyAccessor(IList<PropertyInfo> propertyChain, Type genericType, Type collectionType) : this(propertyChain)
 {
     if (genericType == null) throw new ArgumentNullException("genericType");
     GenericType = genericType;
     CollectionType = collectionType;
     AddMethod = CollectionType.GetMethod("Add");
     ItemPropertyInfo = propertyChain.Last().PropertyType.GetProperty("Item");
     RemoveAtMethod = propertyChain.Last().PropertyType.GetMethod("RemoveAt");
     IsCollection = true;
 }
        public static void AddWays(this Polygon<OSMNode> polygon, IList<OSMWay> ways, OSMDB db)
        {
            if (ways.Count == 1) {
                // Check if the created polygon is closed
                if (ways[0].Nodes.Count > 0 && ways[0].Nodes.First() != ways[0].Nodes.Last()) {
                    throw new ArgumentException("Ways does not form a closed polygon");
                }

                for (int i = 0; i < ways[0].Nodes.Count - 1; i++) {
                    polygon.AddVertex(db.Nodes[ways[0].Nodes[i]]);
                }
            }
            else {
                int lastVertexID = 0;

                if (ways[0].Nodes.First() == ways.Last().Nodes.First() || ways[0].Nodes.Last() == ways.Last().Nodes.First()) {
                    lastVertexID = ways.Last().Nodes.First();
                }
                else {
                    lastVertexID = ways.Last().Nodes.Last();
                }
                //// Check orientation of the first way
                //if (ways[0].Nodes.First() == ways[1].Nodes.First() || ways[0].Nodes.First() == ways[1].Nodes.First()) {
                //  for (int ii = ways[0].; ii < verticesToAdd.Count - 1; ii++) {
                //    AddVertex(verticesToAdd[ii]);
                //  }
                //}

                for (int i = 0; i < ways.Count; i++) {
                    List<int> verticesToAdd = new List<int>();

                    // Checks the way orienatation and picks nodes in correct order
                    if (lastVertexID == ways[i].Nodes[0]) {
                        verticesToAdd.AddRange(ways[i].Nodes);
                    }
                    else if (lastVertexID == ways[i].Nodes.Last()) {
                        verticesToAdd.AddRange(ways[i].Nodes.Reverse());
                    }
                    else {
                        throw new ArgumentException("Can not create polygon, ways aren't connected");
                    }

                    for (int ii = 0; ii < verticesToAdd.Count - 1; ii++) {
                        polygon.AddVertex(db.Nodes[verticesToAdd[ii]]);
                    }

                    lastVertexID = verticesToAdd.Last();
                }

                // Check if the created polygon is closed
                if (polygon.VerticesCount > 0 && polygon.Vertices.First() != db.Nodes[lastVertexID]) {
                    throw new ArgumentException("Ways does not form a closed polygon");
                }
            }
        }
 static IEnumerable<BottomProfilePoint> Filter(IList<BottomProfilePoint> source)
 {
     var curProfilePoint = source[0];
     yield return curProfilePoint;
     foreach (var point in source.Where(point => curProfilePoint.Depth != point.Depth)) 
     {
         curProfilePoint = point;
         yield return point;
     }
     if (curProfilePoint.Range < source.Last().Range) yield return source.Last();
 }
		public void AssignFragmentPeak(IList<IAtomContainer> fragments, IEnumerable<Peak> peakList, double mzabs, double mzppm)
		{
			hits = new List<PeakMolPair>();
			hitsAll = new List<PeakMolPair>();			

			foreach (var peak in peakList)
			{
				var haveFoundAMatch = false;
				foreach (var fragment in fragments)
				{
					//matched peak
					int hydrogensAdded;
					double matchedMass;
					double hydrogenPenalty;
					if (MatchByMass(fragment, peak.Mass, mzabs, mzppm, out matchedMass, out hydrogenPenalty, out hydrogensAdded))
					{
                        var match = new PeakMolPair(fragment, peak, matchedMass, GetMolecularFormulaAsString(fragment), hydrogenPenalty, double.Parse((string)fragment.getProperty("BondEnergy"), CultureInfo.InvariantCulture), GetNeutralChange(fragment, hydrogensAdded));
						hitsAll.Add(match);

						// If we don't yet have a match, add it
						if (!haveFoundAMatch)
						{
							hits.Add(match);
							haveFoundAMatch = true;
						}
						// If we do have a match, replace it if this new match has a lower hydrogen penalty
						else if (hydrogenPenalty < hits.Last().HydrogenPenalty)
						{
							hits.RemoveAt(hits.Count - 1);
							hits.Add(match);
						}						
					}
				}
			}
		}
        public FromImportCompletionAnalysis(IList<ClassificationSpan> tokens, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
            : base(span, textBuffer, options)
        {
            Debug.Assert(tokens[0].Span.GetText() == "from");

            int beforeImportToken = tokens
                .TakeWhile(tok => !(tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) && tok.Span.GetText() == "import"))
                .Count();

            bool lastIsDot = tokens.Last().ClassificationType.IsOfType(JPredefinedClassificationTypeNames.Dot);
            _modulesOnly = beforeImportToken == tokens.Count;
            _noCompletions = !_modulesOnly && lastIsDot;
            _includeStar = beforeImportToken == tokens.Count - 1;

            if (beforeImportToken >= 2) {
                // If there are at least two tokens ('from' <name>) before the
                // 'import' token, use completions from that package.
                if (beforeImportToken < tokens.Count || lastIsDot) {
                    _namespace = tokens
                        .Take(beforeImportToken)
                        .Where(tok => tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier))
                        .Select(tok => tok.Span.GetText())
                        .ToArray();
                } else {
                    _importKeywordOnly = true;
                }
            }
        }
 void SortCollectedList()
 {
     var sorted = _collectedList.OrderByDescending(x => x.Value);
     _collectedList = null;
     _collectedList = sorted.Cast<MapData>().ToList();
     _lowest = _collectedList.Last().Value;
 }
Example #10
1
        protected PropertyExpression(object obj, IEnumerable<PropertyExpressionPart> parts)
        {
            if (obj == null)
                throw new ArgumentNullException("obj");
            if (parts == null)
                throw new ArgumentNullException("parts");
            /*foreach (object item in parts)
            {
                if (item == null)
                {
                    throw new ArgumentException("An item inside the enumeration was null.", "parts");
                }
            }*/
            if (parts.Cast<object>().Any(item => item == null))
            {
                throw new ArgumentException(Resources.AnItemWasNull, "parts");
            }

            _parts = new List<PropertyExpressionPart>(parts);

            if (_parts.Count == 0)
                throw new ArgumentException(Resources.OnePartRequired, "parts");

            _finalPart = _parts.Last();
            //whenever the final part's value changes, that means the value of the expression as a whole has changed
            _finalPart.ValueChanged += delegate
                {
                    OnValueChanged();
                };

            //assign the initial object in the potential chain of objects resolved by the expression parts
            _parts[0].Object = obj;
        }
 private void ParseRealization(IList<Double> realization)
 {
     Double repeatedValue = realization.Last(); // last value it's the same as cycle start value
     Int32 cycleStartIndex = realization.IndexOf(repeatedValue);
     Appendix = realization.Take(cycleStartIndex).ToList();
     Cycle = realization.Skip(cycleStartIndex).Take(realization.Count - cycleStartIndex - 1).ToList();
 }
Example #12
1
 private void CheckFirstAndLastPoint(IList<Point> points)
 {
     if (this.DistanceIsTooSmall(points.Last(), points.First()))
     {
         points.RemoveAt(points.Count - 1);
     }
 }
 private void CheckFirstAndLastPoint(IList<DepthPointEx> points)
 {
     if (PointsAreClose(points.Last(), points.First()))
     {
         points.RemoveAt(points.Count - 1);
     }
 }
Example #14
1
        public MainWindow()
        {
            InitializeComponent();
            Loaded += (sender, e) => ClearValue(SizeToContentProperty);

            _allControllerViewModels =
                (from type in GetType().Assembly.GetTypes()
                 where !type.IsInterface && typeof(IController).IsAssignableFrom(type)
                 let viewModel = new ControllerViewModel((IController)Activator.CreateInstance(type))
                 orderby viewModel.SortIndex, viewModel.Library, viewModel.Description
                 select viewModel).ToList();
            _allControllerViewModels.First().IsChecked = true;
            ControllerGroups.ItemsSource = _allControllerViewModels.GroupBy(viewModel => viewModel.Library);

            _allResolutionViewModels = new[] {
                new ResolutionViewModel(800, 600, 50, 42),
                new ResolutionViewModel(1024, 768, 64, 54),
                new ResolutionViewModel(1280, 1024, 80, 73),
                new ResolutionViewModel(1440, 900, 90, 64),
            };
            _allResolutionViewModels.Last(
                res => res.Width <= SystemParameters.PrimaryScreenWidth &&
                res.Height <= SystemParameters.PrimaryScreenHeight).IsChecked = true;
            Resolutions.ItemsSource = _allResolutionViewModels;

            RunResults.ItemsSource = _runResults;
        }
 private int SolveFive(BombSettings settings, IList<Color> colors)
 {
     if (settings.SerialLastDigit == Parity.NotSet)
     {
         throw new NeedSerialLastDigitException();
     }
     // If the last wire is black and the last digit of the serial number is odd, cut the fourth wire.
     else if (colors.Last() == Color.Black && settings.SerialLastDigit == Parity.Odd)
     {
         return 4;
     }
     // Otherwise, if there is exactly one red wire and there is more than one yellow wire, cut the first wire.
     else if (colors.Count(c => c == Color.Red) == 1 && colors.Count(c => c == Color.Yellow) > 1)
     {
         return 1;
     }
     // Otherwise, if there are no black wires, cut the second wire.
     else if (colors.Count(c => c == Color.Black) == 0)
     {
         return 2;
     }
     // Otherwise, cut the first wire.
     else
     {
         return 1;
     }
 }
Example #16
0
 private static void GenerateChains(IList<int> chain, int n)
 {
     var count = chain.Count;
     if (count >= n) return;
     var last = chain.Last();
     var nextElems = _dict[last].Where(k => !chain.Contains(k)).ToList();
     if (nextElems.Any() && count < n)
     {
         foreach (var next in nextElems)
         {
             var deeper = chain.ToList();
             deeper.Add(next);
             GenerateChains(deeper, n);
         }
     }
     else if (IsPrime(last + 1) && count == n - 1)
     {
         _nrOfChains++;
         /*foreach (var elem in chain)
         {
             Console.Write(elem+" ");
         }
         Console.WriteLine(1);*/
     }
 }
Example #17
0
 protected void AddLastIndexAsSentenceBoundary(IList<int> indices, int lastIndex)
 {
     if (indices.Count != 0 && indices.Last() != lastIndex)
     {
         indices.Add(lastIndex);
     }
 }
Example #18
0
		public Path(IList<SimplePoint> points)
		{
			if (points == null) { throw new ArgumentNullException("points"); }
			if (points.Any(x => x == null)) { throw new ArgumentException("points", ErrorMessages.msgPath_Error_NoNullPointAllowedInTheCollection); }
			if (points.Count < MINIMUM_AMMOUNT_OF_POINTS) { throw new ArgumentException("points", ErrorMessages.msgPath_Error_AtLeastTwoPointsInTheCollection); }
			if (points.First().Equals(points.Last())) { throw new ArgumentException("points", ErrorMessages.msgPath_Error_FirstAndLastPointInTheCollectionShouldNotBeTheSame); }

			this._points = points;
		}
Example #19
0
 public PenaltyProcessor(IList<Jam> jams, Dictionary<string, Player> homePlayers, Dictionary<string, Player> awayPlayers)
 {
     _jams = jams;
     _players = homePlayers.Values.ToDictionary(p => p.ID);
     foreach(Player player in awayPlayers.Values)
     {
         _players[player.ID] = player;
     }
     _lastJam = _jams.Last();
 }
Example #20
0
 public IList<IEdge> GetEdgePath(IList<IVertex> items)
 {
     var result = new List<IEdge>();
     if (items.Count == 2 & items.First() == items.Last()) return result;
     for (var i = 0; i < items.Count - 1; i++)
     {
         result.Add(_edges[items[i].Number, items[i + 1].Number]);
     }
     return result;
 }
Example #21
0
        private static Panel GetPlayerPanel(IList<PictureBox> cardHolders)
        {
            Panel panel = new Panel();
            panel.Location = new Point(cardHolders.First().Left - 10, cardHolders.Last().Top - 10);
            panel.BackColor = Color.DarkBlue;
            panel.Height = 150;
            panel.Width = 180;
            panel.Visible = false;

            return panel;
        }
Example #22
0
 private IList<int> GetThetas(IList<int> sortedCardinalities)
 {
     var result = new List<int>();
     var maxCardinality = sortedCardinalities.First();
     var minCardinality = sortedCardinalities.Last();
     for (int j = maxCardinality; j >= minCardinality; j--)
     {
         int theta = this.GetTheta(j, sortedCardinalities);
         result.Add(theta);
     }
     return result;
 }
 private string GetStringFromYearsList(IList<short> list)
 {
     switch (list.Count)
     {
         case 1:
             return list[0].ToString();
         case 2:
             return string.Join(" ", list[0], "in", list[1]);
         default:
             return string.Join(" ",
                                string.Join(", ", list.Select(l => l.ToString()).ToArray<string>(), 0, list.Count - 1),
                                "in", list.Last());
     }
 }
		public static Color GetColorAtOffset(IList<GradientStop> stops, double offset)
		{
			GradientStop s1 = stops[0], s2 = stops.Last();
			foreach (var item in stops) {
				if (item.Offset < offset && item.Offset > s1.Offset) s1 = item;
				if (item.Offset > offset && item.Offset < s2.Offset) s2 = item;
			}
			return Color.FromArgb(
				(byte)((s1.Color.A + s2.Color.A) / 2),
				(byte)((s1.Color.R + s2.Color.R) / 2),
				(byte)((s1.Color.G + s2.Color.G) / 2),
				(byte)((s1.Color.B + s2.Color.B) / 2)
			);
		}
    private void TryInitializeViews()
    {
      if (_doc != null && this.IsLoaded)
      {
        _leftView = new MergeView(editLeft).SetDocument(_doc, MergeLocation.Left);
        _parentView = new MergeView(editParent).SetDocument(_doc, MergeLocation.Parent);
        _rightView = new MergeView(editRight).SetDocument(_doc, MergeLocation.Right);
        _outputView = new MergeView(editOutput).SetDocument(_doc, MergeLocation.Output);
        _scrollBoundaries = MergeView.GetScrollBoundaries(_leftView, _parentView, _rightView, _outputView);
        _views = new MergeView[] { _leftView, _parentView, _rightView, _outputView };

        vertScroll.Minimum = 0.0;
        vertScroll.Maximum = _scrollBoundaries.Last();
      }
    }
 private static void BuildRoute(IList<TransitEdge> currentPath, string destinationNode, IEnumerable<TransitEdge> edges, Constraints constraints, ICollection<TransitPath> paths)
 {
    var currentEdge = currentPath.Last();
    if (currentEdge.To == destinationNode)
    {
       var path = new TransitPath(currentPath);
       paths.Add(path);
       return;
    }
    var possibleEdges = FindPossibleEdges(currentEdge.To, currentEdge.ToDate, edges, constraints);
    foreach (var possibleEdge in possibleEdges)
    {
       var newPath = new List<TransitEdge>(currentPath) {possibleEdge};
       BuildRoute(newPath, destinationNode,edges, constraints, paths);
    }
 }
        double CalculateTimeToSLABreach(IList<DataPoint> snapshots)
        {
            //need at least 2 data points to be able to calculate
            if (snapshots.Count < 2)
            {
                return double.MaxValue;
            }

            DataPoint previous = null;

            var criticalTimeDelta = TimeSpan.Zero;

            foreach (var current in snapshots)
            {
                if (previous != null)
                {
                    criticalTimeDelta += current.CriticalTime - previous.CriticalTime;
                }

                previous = current;
            }

            if (criticalTimeDelta.TotalSeconds <= 0.0)
            {
                return double.MaxValue;
            }

            var elapsedTime = snapshots.Last().OccurredAt - snapshots.First().OccurredAt;

            if (elapsedTime.TotalSeconds <= 0.0)
            {
                return double.MaxValue;
            }

            var lastKnownCriticalTime = snapshots.Last().CriticalTime.TotalSeconds;

            var criticalTimeDeltaPerSecond = criticalTimeDelta.TotalSeconds/elapsedTime.TotalSeconds;

            var secondsToSLABreach = (endpointSLA.TotalSeconds - lastKnownCriticalTime)/criticalTimeDeltaPerSecond;

            if (secondsToSLABreach < 0.0)
            {
                return 0.0;
            }

            return secondsToSLABreach;
        }
        public static string Construct(IList<string> elements)
        {
            if(elements == null || !elements.Any())
            {
                return "";
            }

            var returnString = new StringBuilder();

            foreach (var element in elements)
            {
                returnString.Append(element);

                if(element != elements.Last())
                {
                    returnString.Append(", ");
                }
            }

            return returnString.ToString();
        }
Example #29
0
        /// <summary>
        /// Поиск подпоследовательности в потоке данных
        /// </summary>
        /// <remarks>
        /// Простейший вариант алгоритма Бойера — Мура
        /// </remarks>
        /// <param name="file">Поток данных</param>
        /// <param name="template">Подпоследовательность</param>
        /// <returns>true - если найдена</returns>
        public static bool searchInFile(Stream file, IList<byte> template)
        {
            // incorrect input
            if (file == null
                || template == null
                || template.Count == 0)
                return false;

            CircularQueue<byte> buff = new CircularQueue<byte>(template.Count);

            for (int t = file.ReadByte(); t != -1; t = file.ReadByte())
            {
                buff.push((byte)t);

                if (template.Last().Equals((byte)t))
                {
                    if (buff.cmp(template))
                        return true;
                }
            }
            return false;
        }
        private int SolveFour(BombSettings settings, IList<Color> colors)
        {
            if (settings.SerialLastDigit == Parity.NotSet)
            {
                throw new NeedSerialLastDigitException();
            }
            // If there is more than one red wire and the last digit of the serial number is odd, cut the last red wire.
            else if (colors.Count(c => c == Color.Red) > 1 && settings.SerialLastDigit == Parity.Odd)
            {
                var index = colors.Select((w, i) => new KeyValuePair<int, Color>(i, w))
                    .Where(p => p.Value == Color.Red)
                    .Last()
                    .Key;

                return index + 1;
            }
            // Otherwise, if the last wire is yellow and there are no red wires, cut the first wire.
            else if (colors.Last() == Color.Yellow && colors.Count(c => c == Color.Red) == 0)
            {
                return 1;
            }
            // Otherwise, if there is exactly one blue wire, cut the first wire.
            else if (colors.Count(c => c == Color.Blue) == 1)
            {
                return 1;
            }
            // Otherwise, if there is more than one yellow wire, cut the last wire.
            else if (colors.Count(c => c == Color.Yellow) > 1)
            {
                return 4;
            }
            // Otherwise, cut the second wire.
            else
            {
                return 2;
            }
        }