Ejemplo n.º 1
0
        private Tuple <int, Vector3> BestQPosition(Obj_AI_Base target, List <Obj_AI_Base> targets, HitChance hitChance)
        {
            var castPos   = Vector3.Zero;
            var totalHits = 0;

            try
            {
                var enemies        = targets.Where(e => e.IsValidTarget(Q.Range * 1.5f)).ToList();
                var enemyPositions = new List <Tuple <Obj_AI_Base, Vector3> >();
                var circle         = new Geometry.Polygon.Circle(Player.Position, Player.BoundingRadius, 30).Points;

                foreach (var h in enemies)
                {
                    var ePred = Q.GetPrediction(h);
                    if (ePred.Hitchance >= hitChance)
                    {
                        circle.Add(Player.Position.Extend(ePred.UnitPosition, Player.BoundingRadius).To2D());
                        enemyPositions.Add(new Tuple <Obj_AI_Base, Vector3>(h, ePred.UnitPosition));
                    }
                }
                var targetPos = target == null ? Vector3.Zero : target.Position;
                if (target == null)
                {
                    var possibilities =
                        ListExtensions.ProduceEnumeration(enemyPositions).Where(p => p.Count > 0).ToList();
                    var count = 0;
                    foreach (var possibility in possibilities)
                    {
                        var mec = MEC.GetMec(possibility.Select(p => p.Item2.To2D()).ToList());
                        if (mec.Radius < Q.Width && possibility.Count > count)
                        {
                            count     = possibility.Count;
                            targetPos = mec.Center.To3D();
                        }
                    }
                }
                if (targetPos.Equals(Vector3.Zero))
                {
                    return(new Tuple <int, Vector3>(totalHits, castPos));
                }
                circle = circle.OrderBy(c => c.Distance(targetPos)).ToList();
                if (!enemyPositions.Any())
                {
                    return(new Tuple <int, Vector3>(totalHits, castPos));
                }

                foreach (var point in circle)
                {
                    var hits           = 0;
                    var containsTarget = false;
                    var direction      = Q.Range * (point.To3D() - ObjectManager.Player.Position).Normalized().To2D();
                    var rect1          = new Geometry.Polygon.Rectangle(
                        Player.Position, Player.Position.Extend(Player.Position + direction.To3D(), Q.Range), Q.Width);
                    var rect2 = new Geometry.Polygon.Rectangle(
                        Player.Position,
                        Player.Position.Extend(Player.Position + direction.Rotated(QAngle).To3D(), Q.Range), Q.Width);
                    var rect3 = new Geometry.Polygon.Rectangle(
                        Player.Position,
                        Player.Position.Extend(Player.Position + direction.Rotated(-QAngle).To3D(), Q.Range), Q.Width);
                    foreach (var enemy in enemyPositions)
                    {
                        var bounding = new Geometry.Polygon.Circle(enemy.Item2, enemy.Item1.BoundingRadius * 0.85f);
                        if (bounding.Points.Any(p => rect1.IsInside(p) || rect2.IsInside(p) || rect3.IsInside(p)))
                        {
                            hits++;
                            if (target != null && enemy.Item1.NetworkId.Equals(target.NetworkId))
                            {
                                containsTarget = true;
                            }
                        }
                    }
                    if ((containsTarget || target == null) && hits > totalHits)
                    {
                        totalHits = hits;
                        castPos   = Player.Position.Extend(point.To3D(), Q.Range);
                        if (totalHits >= enemies.Count)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
            return(new Tuple <int, Vector3>(totalHits, castPos));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// get random valid completed sudoku grid
        /// </summary>
        private void GetValidCompleteSudoku()
        {
            completeSudokuValues = ListExtensions.GetValidCompletedSudoku();

            for (int i = 1; i <= Board.Size; i++)
            {
                Board.GetSquareByID(i).FillWithValues(completeSudokuValues[i - 1]);
            }

            int numberOfRepetitions = generator.Next(minrowOrColumnSwaps, maxrowOrColumnSwaps);

            for (int i = 0; i < numberOfRepetitions; i++)
            {
                int option       = generator.Next(0, 5);
                int squareNumber = generator.Next(Board.SquaresPerDimension);

                int outerIndex  = squareNumber * Board.SquaresPerDimension;
                int innerIndex1 = generator.Next(Board.SquaresPerDimension);
                int innerIndex2 = generator.Next(Board.SquaresPerDimension);

                int first  = outerIndex + innerIndex1;
                int second = outerIndex + innerIndex2;

                switch (option)
                {
                case 0:
                    Board.SwapColumns(first, second);
                    break;

                case 1:
                    Board.SwapRows(first, second);
                    break;

                case 2:
                    Board.SwapColumnSquares(innerIndex1, innerIndex2);
                    break;

                case 3:
                    Board.SwapRowSquares(innerIndex1, innerIndex2);
                    break;

                case 4:
                    Board.Transponse();
                    break;

                default:
                    break;
                }
            }

            // set SolvedSudokuValues
            for (int i = 0; i < Board.Size; i++)
            {
                var row = new List <int>();
                for (int j = 0; j < Board.Size; j++)
                {
                    row.Add(int.Parse(Board[i, j].Value));
                }
                SolvedSudokuValues.Add(row);
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Verifies that a digital signature is valid by calculating the hash value of the specified data
 /// using the specified hash algorithm and padding, and comparing it to the provided signature.
 /// </summary>
 /// <param name="data">The data to sign.</param>
 /// <param name="signature">The signature data to be verified.</param>
 /// <returns>true if the signature is valid; otherwise, false.</returns>
 public bool Verify(byte[] data, byte[] signature)
 {
     return(ListExtensions.Equals(Sign(data), signature));
 }
Ejemplo n.º 4
0
 public GrandparentsItem(IEnumerable <Relative> grandparents, List <User> users)
     : base(ProfileInfoItemType.RichText)
 {
     this.Title = CommonResources.ProfilePage_Info_Grandparents;
     this.Data  = ListExtensions.GetCommaSeparated((List <string>)Enumerable.ToList <string>(Enumerable.Select <Relative, string>(grandparents, (Func <Relative, string>)(r => r.GetVKFormatted(users)))), ", ");
 }
Ejemplo n.º 5
0
 public void Impl4() => ListExtensions.CompareToImpl4(_localItems, _remoteItems, _ => _.Key);
 public IEnumerable <CategoryDto> GetAllCategories(string urlStr)
 {
     return(ListExtensions.ToCategoriesLightWeight(DataContext.Categories, urlStr));
 }
Ejemplo n.º 7
0
        public void WhenListObjectReturnSame()
        {
            List <object> sample = new List <object>();

            Assert.AreSame(sample, ListExtensions.AsObjectList(sample));
        }
Ejemplo n.º 8
0
        public async Task <List <StockPricesForUi> > GetPricesForUi(StockPricesForUiRequest request)
        {
            var ticker       = request.Tickers;
            var result       = new List <StockPricesForUi>();
            var resultPrices = new List <StockPriceHistoric>();

            if (ticker.Count != 0)
            {
                var stockSplits = ListExtensions.Split(ticker, 5);
                foreach (var stockSplit in stockSplits)
                {
                    var stockSymbols  = StringExtensions.GetSymbolsString(stockSplit);
                    var currentPrices = await _stockPriceService.GetStockPrices(stockSymbols);

                    var prices = await _stockPriceService.GetHistoricPrices(stockSymbols, DateTime.Now.AddDays(-100), DateTime.Now);

                    if (prices.HistoricalStockList != null && currentPrices != null)
                    {
                        foreach (var price in prices.HistoricalStockList)
                        {
                            var currentStockPrice = currentPrices.First(x => x.Symbol == price.Symbol).Price;
                            price.Historical.Add(new StockPriceHistoricItem()
                            {
                                AdjClose      = currentStockPrice,
                                Date          = DateTime.Now.Date,
                                Change        = price.Historical[0].AdjClose - currentStockPrice,
                                ChangePercent = (currentStockPrice - price.Historical[0].AdjClose) / price.Historical[0].AdjClose
                            });
                            price.Historical = price.Historical.OrderByDescending(x => x.Date).ToList();
                            resultPrices.Add(price);
                        }
                    }
                }
            }

            foreach (var prices in resultPrices)
            {
                var dto = new StockPricesForUi()
                {
                    Ticker = prices.Symbol
                };
                if (prices.Historical != null && prices.Historical.Count >= 61)
                {
                    if (prices.Historical[0] != null)
                    {
                        if (prices.Historical[1] != null)
                        {
                            dto.Day = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[1].AdjClose) / prices.Historical[1].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                        if (prices.Historical[2] != null)
                        {
                            dto.TwoDay = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[2].AdjClose) / prices.Historical[2].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                        if (prices.Historical[3] != null)
                        {
                            dto.ThreeDay = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[3].AdjClose) / prices.Historical[3].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                        if (prices.Historical[5] != null)
                        {
                            dto.Week = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[5].AdjClose) / prices.Historical[5].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                        if (prices.Historical[20] != null)
                        {
                            dto.Month = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[20].AdjClose) / prices.Historical[20].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                        if (prices.Historical[60] != null)
                        {
                            dto.ThreeMonths = new StockPriceForUi()
                            {
                                Performance = decimal.Round(((prices.Historical[0].AdjClose - prices.Historical[60].AdjClose) / prices.Historical[60].AdjClose), 4, MidpointRounding.AwayFromZero)
                            };
                        }
                    }
                }
                result.Add(dto);
            }

            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Parses a string to the query data.
        /// </summary>
        /// <param name="query">The query string.</param>
        /// <param name="append">true if append instead of override; otherwise, false.</param>
        /// <param name="encoding">The optional encoding.</param>
        /// <returns>The count of query item added.</returns>
        /// <exception cref="FormatException">The format is not correct.</exception>
        public int ParseSet(string query, bool append = false, Encoding encoding = null)
        {
            if (!append)
            {
                Clear();
            }
            if (string.IsNullOrWhiteSpace(query))
            {
                return(0);
            }
            var queryTrim = query.TrimStart();

            if (queryTrim.IndexOf('{') == 0)
            {
                queryTrim = queryTrim.Substring(1).Trim();
                var lastPos = queryTrim.LastIndexOf('}');
                if (lastPos >= 0)
                {
                    queryTrim = queryTrim.Substring(0, lastPos);
                }
                var count = 0;

                string        name       = null;
                StringBuilder sb         = null;
                var           level      = new List <char>();
                StringBuilder backSlash  = null;
                bool          ignoreRest = false;
                foreach (var c in queryTrim)
                {
                    if (ignoreRest)
                    {
                        switch (c)
                        {
                        case '\r':
                        case '\n':
                            ignoreRest = false;
                            break;
                        }

                        continue;
                    }

                    if (c == '\\')
                    {
                        backSlash = new StringBuilder();
                        continue;
                    }

                    if (backSlash != null)
                    {
                        if (StringExtensions.ReplaceBackSlash(sb, backSlash, c))
                        {
                            backSlash = null;
                        }
                        continue;
                    }

                    if (sb == null)
                    {
                        if (c == '/')
                        {
                            ignoreRest = true;
                            continue;
                        }

                        if (c == '"')
                        {
                            sb = new StringBuilder();
                            level.Add('"');
                            continue;
                        }

                        if (name == null)
                        {
                            if (NameChars.IndexOf(c) > -1)
                            {
                                sb = new StringBuilder();
                                level.Add(':');
                                sb.Append(c);
                            }

                            continue;
                        }

                        if (c == '{')
                        {
                            level.Add('}');
                        }
                        else if (c == '[')
                        {
                            level.Add(']');
                        }
                        else if (NumBoolChars.IndexOf(c) > -1)
                        {
                            level.Add(',');
                        }
                        else
                        {
                            continue;
                        }

                        sb = new StringBuilder();
                        sb.Append(c);
                        continue;
                    }

                    if (level.Count == 0)
                    {
                        continue;
                    }
                    var lastLevelChar = level[level.Count - 1];
                    if (c == lastLevelChar)
                    {
                        level.RemoveAt(level.Count - 1);
                        if (name == null)
                        {
                            name = sb.ToString();
                            sb   = null;
                            continue;
                        }
                        else if (level.Count == 0)
                        {
                            if (c == ',')
                            {
                                var sbStr = sb.ToString().Trim();
                                sb = new StringBuilder(sbStr);
                                if (sbStr == "null" || sbStr == "undefined")
                                {
                                    name = null;
                                    sb   = null;
                                    continue;
                                }
                            }
                            else if (c == '"')
                            {
                            }
                            else
                            {
                                sb.Append(c);
                            }

                            ListExtensions.Add(this, name, sb.ToString());
                            name = null;
                            sb   = null;
                            continue;
                        }
                    }
                    else if (lastLevelChar == ':' && name == null)
                    {
                        if (c == '\r' || c == '\n' || c == '\t' || c == ' ' || c == ',' || c == '+')
                        {
                            sb = null;
                        }
                        else if (c == '/')
                        {
                            sb         = null;
                            ignoreRest = true;
                        }
                        else if (NameChars.IndexOf(c) < 0)
                        {
                            throw new FormatException("The format of query string is not correct.");
                        }

                        if (sb == null)
                        {
                            level.RemoveAt(level.Count - 1);
                            continue;
                        }
                    }
                    else if (c == '"')
                    {
                        level.Add('"');
                    }
                    else if (lastLevelChar != '"')
                    {
                        if (c == '{')
                        {
                            level.Add('}');
                        }
                        else if (c == '[')
                        {
                            level.Add(']');
                        }
                    }

                    if (sb == null)
                    {
                        sb = new StringBuilder();
                    }
                    sb.Append(c);
                }

                if (!string.IsNullOrWhiteSpace(name) && sb != null)
                {
                    var sbStr = sb.ToString().Trim();
                    if (sbStr != "null" && sbStr != "undefined")
                    {
                        ListExtensions.Add(this, name, sbStr);
                    }
                }

                return(count);
            }

            if (encoding == null)
            {
                encoding = DefaultEncoding ?? Encoding.UTF8;
            }
            var pos = query.IndexOf("?");

            if (pos >= 0)
            {
                query = query.Substring(pos + 1);
            }
            pos = query.IndexOf("#");
            if (pos >= 0)
            {
                query = query.Substring(0, pos);
            }
            var arr = query.Split('&');

            foreach (var item in arr)
            {
                pos = item.IndexOf("=");
                if (pos < 0)
                {
                    ListExtensions.Add(this, HttpUtility.UrlDecode(item, encoding), string.Empty);
                }
                else
                {
                    ListExtensions.Add(this, HttpUtility.UrlDecode(item.Substring(0, pos), encoding), HttpUtility.UrlDecode(item.Substring(pos + 1), encoding));
                }
            }

            return(arr.Length);
        }
Ejemplo n.º 10
0
 public void WhenNullShouldReturnNull()
 {
     Assert.IsNull(ListExtensions.AsObjectList(null));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Notifies the framer instance that incoming data has been received from the stream. This method will invoke <see cref="MessageArrived"/> as necessary.
        /// </summary>
        /// <remarks>
        /// <para>This method may invoke <see cref="MessageArrived"/> zero or more times.</para>
        /// <para>Zero-length receives are ignored. May streams use a 0-length read to indicate the end of a stream, but the framer takes no action in this case.</para>
        /// </remarks>
        /// <param name="data">The data received from the stream. Cannot be null. May be a slice of the read buffer for the stream.</param>
        /// <exception cref="System.Net.ProtocolViolationException">If the data received is not a properly-formed message.</exception>
        public void DataReceived(IList <byte> data)
        {
            int i = 0;

            while (i != data.Count)
            {
                int bytesAvailable = data.Count - i;
                if (this.delimiterIndex == -1)
                {
                    // We are searching for the begin delimiter
                    bool waiting = false;
                    for (int index = 0; index != this.beginDelimiters.Length; ++index)
                    {
                        byte[] beginDelimiter = this.beginDelimiters[index];
                        int    bytesRequested = beginDelimiter.Length - this.dataBuffer.Count;
                        if (bytesRequested > bytesAvailable)
                        {
                            // Not enough data has arrived for a complete match
                            waiting = true;
                            continue;
                        }

                        // Test if this begin delimiter already has been rejected
                        if (bytesRequested <= 0)
                        {
                            continue;
                        }

                        // Test if we have a complete match
                        IList <byte> lastOfBeginDelimiter = data.Slice(i, bytesRequested);
                        if (beginDelimiter.SequenceEqual(this.dataBuffer.Concat(lastOfBeginDelimiter)))
                        {
                            this.AppendDataToDataBuffer(lastOfBeginDelimiter);
                            i += bytesRequested;
                            this.delimiterIndex = index;
                            break;
                        }
                    }

                    if (this.delimiterIndex == -1)
                    {
                        if (waiting)
                        {
                            // The data is not long enough to match at least one of the begin delimiters, and it doesn't match any that it is long enough to match.
                            this.AppendDataToDataBuffer(data.Slice(i, bytesAvailable));
                            return;
                        }
                        else
                        {
                            trace.TraceEvent(TraceEventType.Error, 0, "Message does not begin with a defined start delimieter in data " + data.Slice(i, bytesAvailable).PrettyDump());
                            throw new System.Net.ProtocolViolationException("Message does not begin with a start delimiter");
                        }
                    }
                }
                else
                {
                    // The begin delimiter has been found; we are reading data while searching for the end delimiter
                    byte[] endDelimiter = this.endDelimiters[this.delimiterIndex];
                    if (this.endDelimiterIndex != 0)
                    {
                        // A partial end delimiter was found at the end of a previous chunk of incoming data; see if this data finishes the end delimiter
#if DEBUG
                        Debug.Assert(i == 0, "This branch should only be taken when a new chunk of incoming data has arrived.");
#endif
                        int bytesToMatch = Math.Min(endDelimiter.Length - this.endDelimiterIndex, bytesAvailable);
                        if (endDelimiter.Slice(this.endDelimiterIndex, bytesToMatch).SequenceEqual(data.Slice(0, bytesToMatch)))
                        {
                            // A partial or complete match was found
                            if (bytesToMatch == endDelimiter.Length - this.endDelimiterIndex)
                            {
                                // A complete match has been found: report the message and continue processing
                                if (this.MessageArrived != null)
                                {
                                    this.MessageArrived(this.delimiterIndex, this.dataBuffer.Skip(this.beginDelimiters[this.delimiterIndex].Length));
                                }

                                i += bytesToMatch;
                                this.Reset();
                            }
                            else
                            {
                                // The partial match has been extended into a longer partial match (at the end of the data)
                                this.endDelimiterIndex += bytesAvailable;
                                return;
                            }
                        }
                        else
                        {
                            // This was a false partial end delimiter; prepend it to the incoming data and continue searching
                            List <byte> newData = new List <byte>(data.Count + this.endDelimiterIndex);
                            newData.AddRange(endDelimiter.Take(this.endDelimiterIndex));
                            newData.AddRange(data);
                            data = newData;

                            this.endDelimiterIndex = 0;
                        }
                    }
                    else
                    {
                        // The data buffer does not have an implicit partial end delimiter on it, so we can just search the incoming data
                        // Search for a complete end delimiter, or a partial end delimiter at the end of the incoming data
                        int endDelimiterFoundIndex;
                        for (endDelimiterFoundIndex = 0; endDelimiterFoundIndex != bytesAvailable; ++endDelimiterFoundIndex)
                        {
                            int bytesToMatch = Math.Min(endDelimiter.Length, bytesAvailable - endDelimiterFoundIndex);
                            if (endDelimiter.Slice(0, bytesToMatch).SequenceEqual(data.Slice(i + endDelimiterFoundIndex, bytesToMatch)))
                            {
                                // A partial or complete match was found
                                IList <byte> match = data.Slice(i, endDelimiterFoundIndex);
                                if (bytesToMatch == endDelimiter.Length)
                                {
                                    // A complete match was found: report the message and continue processing
                                    this.CheckMaxMessageSize(this.dataBuffer.Count, endDelimiterFoundIndex);
                                    IList <byte> message = ListExtensions.Concat(this.dataBuffer, match);

                                    if (this.MessageArrived != null)
                                    {
                                        this.MessageArrived(this.delimiterIndex, message.Skip(this.beginDelimiters[this.delimiterIndex].Length));
                                    }

                                    i += endDelimiterFoundIndex + bytesToMatch;
                                    this.dataBuffer.Clear();
                                    this.delimiterIndex = -1;
#if DEBUG
                                    Debug.Assert(this.endDelimiterIndex == 0, "endDelimiterIndex should already be 0");
#endif
                                    break;
                                }
                                else
                                {
                                    // A partial match was found at the end of the available data
                                    this.AppendDataToDataBuffer(match);
                                    this.endDelimiterIndex = bytesToMatch;
                                    return;
                                }
                            }
                        }

                        if (endDelimiterFoundIndex == bytesAvailable)
                        {
                            // No end delimiter match was found (not even a partial at the end of the buffer)
                            this.AppendDataToDataBuffer(data.Slice(i, bytesAvailable));
                            return;
                        }
                    }
                }
            }
        }
 public void AddRangeNullTest2()
 {
     ListExtensions.AddRange(new List <string> {
         "foobar"
     }, null);
 }
 public void AddRangeNullTest1()
 {
     ListExtensions.AddRange(null, new List <string> {
         "foobar"
     });
 }
Ejemplo n.º 14
0
    /// <summary>
    /// Gets the query value by a specific key.
    /// </summary>
    /// <param name="key">The key.</param>
    /// <param name="ignoreEmpty">true if ignore empty; otherwise, false.</param>
    /// <returns>The query value. The last one for multiple values..</returns>
    public string GetLastValue(string key, bool ignoreEmpty = false)
    {
        var col = ListExtensions.GetValues(this, key);

        return(ignoreEmpty ? col.LastOrDefault(item => !string.IsNullOrWhiteSpace(item)) : col.LastOrDefault());
    }
Ejemplo n.º 15
0
        public void ThrowExceptionWhenListArgumentIsNull()
        {
            IList <string> list = null;

            Assert.Throws <ArgumentNullException>(() => ListExtensions.PaginateList(list));
        }
Ejemplo n.º 16
0
    /// <summary>
    /// Parses the parameters from OpenSSL RSA key (PEM Base64) or the RSA parameters XML string.
    /// </summary>
    /// <param name="key">The OpenSSL RSA key string (PEM Base64) or the RSA parameters XML string.</param>
    /// <returns>The RSA parameters; or null, if parse failed.</returns>
    public static RSAParameters?Parse(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            return(null);
        }
        key = key.Trim();
        if (key.IndexOf("<") == 0 && key.LastIndexOf(">") == key.Length - 1)
        {
            var xml = XElement.Parse(key);
            if (xml == null)
            {
                return(null);
            }
            var p = new RSAParameters();
            foreach (var ele in xml.Elements())
            {
                if (string.IsNullOrWhiteSpace(ele?.Value))
                {
                    continue;
                }
                var chars = Convert.FromBase64String(ele.Value);
                switch (ele.Name?.LocalName?.ToLowerInvariant())
                {
                case "modulus":
                    p.Modulus = chars;
                    break;

                case "exponent":
                    p.Exponent = chars;
                    break;

                case "p":
                    p.P = chars;
                    break;

                case "q":
                    p.Q = chars;
                    break;

                case "dp":
                    p.DP = chars;
                    break;

                case "dq":
                    p.DQ = chars;
                    break;

                case "inverseq":
                    p.InverseQ = chars;
                    break;

                case "d":
                    p.D = chars;
                    break;
                }
            }

            if (p.Modulus == null || p.Modulus.Length == 0 || p.Exponent == null || p.Exponent.Length == 0)
            {
                return(null);
            }
            return(p);
        }

        var lines = key.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        if (lines.Length == 0)
        {
            return(null);
        }
        var isPrivate = true;
        var firstLine = lines[0].Trim();

        if (lines.Length == 1)
        {
            key = firstLine;
        }
        else if (firstLine.IndexOf("ssh-rsa ") == 0)
        {
            isPrivate = false;
            key       = string.Join(string.Empty, lines).Trim();
            if (key.Length < 16)
            {
                return(null);
            }
            key = key.Substring(8);
            var blankPos = key.IndexOf(' ');
            if (blankPos > 0)
            {
                key = key.Substring(0, blankPos);
            }
        }
        else if (lines.Length == 2)
        {
            isPrivate = firstLine.IndexOf("PRIVATE KEY") >= 0;
            key       = lines[1];
        }
        else
        {
            isPrivate = firstLine.IndexOf(" PRIVATE KEY") > 0 || firstLine.IndexOf("PRIVATE KEY") == 0;
            key       = string.Join(string.Empty, lines.Skip(1).Take(lines.Length - 2));
        }

        using (var stream = new MemoryStream(Convert.FromBase64String(key)))
        {
            using (var reader = new BinaryReader(stream))
            {
                if (isPrivate)
                {
                    var twoBytes = reader.ReadUInt16();
                    if (twoBytes == 0x8130)
                    {
                        reader.ReadByte();
                    }
                    else if (twoBytes == 0x8230)
                    {
                        reader.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }
                    if (!AreSame(reader, verPem))
                    {
                        return(null);
                    }

                    // For PKCS8.
                    if (reader.BaseStream.Position + seqOID.Length < reader.BaseStream.Length)
                    {
                        var isPkcs8 = true;
                        var i       = 0;
                        for (; i < seqOID.Length; i++)
                        {
                            if (seqOID[i] == reader.ReadByte())
                            {
                                continue;
                            }
                            isPkcs8 = false;
                            break;
                        }

                        if (isPkcs8)
                        {
                            GetIntegerSize(reader, 0x04);
                            GetIntegerSize(reader, 0x30);
                            if (!AreSame(reader, verPem))
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            i++;
                            reader.BaseStream.Seek(-i, SeekOrigin.Current);
                        }
                    }

                    return(new RSAParameters
                    {
                        Modulus = reader.ReadBytes(GetIntegerSize(reader)),
                        Exponent = reader.ReadBytes(GetIntegerSize(reader)),
                        D = reader.ReadBytes(GetIntegerSize(reader)),
                        P = reader.ReadBytes(GetIntegerSize(reader)),
                        Q = reader.ReadBytes(GetIntegerSize(reader)),
                        DP = reader.ReadBytes(GetIntegerSize(reader)),
                        DQ = reader.ReadBytes(GetIntegerSize(reader)),
                        InverseQ = reader.ReadBytes(GetIntegerSize(reader))
                    });
                }
                else
                {
                    var twoBytes = reader.ReadUInt16();
                    if (twoBytes == 0x8130) // Data read as little endian order (actual data order for Sequence is 30 81).
                    {
                        reader.ReadByte();  // Advance 1 byte.
                    }
                    else if (twoBytes == 0x8230)
                    {
                        reader.ReadInt16(); // Advance 2 bytes.
                    }
                    else
                    {
                        return(null);
                    }

                    var seq = reader.ReadBytes(15);          // Read the Sequence OID.
                    if (!ListExtensions.Equals(seq, seqOID)) // Make sure Sequence for OID is correct.
                    {
                        return(null);
                    }

                    twoBytes = reader.ReadUInt16();
                    if (twoBytes == 0x8103) // Data read as little endian order (actual data order for Bit String is 03 81).
                    {
                        reader.ReadByte();  // Advance 1 byte.
                    }
                    else if (twoBytes == 0x8203)
                    {
                        reader.ReadInt16(); // Advance 2 bytes.
                    }
                    else
                    {
                        return(null);
                    }

                    var testByte = reader.ReadByte();
                    if (testByte != 0x00) // Expect null byte next.
                    {
                        return(null);
                    }

                    twoBytes = reader.ReadUInt16();
                    if (twoBytes == 0x8130) // Data read as little endian order (actual data order for Sequence is 30 81).
                    {
                        reader.ReadByte();  // Advance 1 byte.
                    }
                    else if (twoBytes == 0x8230)
                    {
                        reader.ReadInt16(); // Advance 2 bytes.
                    }
                    else
                    {
                        return(null);
                    }

                    twoBytes = reader.ReadUInt16();
                    byte lowByte  = 0x00;
                    byte highByte = 0x00;

                    if (twoBytes == 0x8102)          // Data read as little endian order (actual data order for Integer is 02 81).
                    {
                        lowByte = reader.ReadByte(); // Read next bytes which is bytes in modulus.
                    }
                    else if (twoBytes == 0x8202)
                    {
                        highByte = reader.ReadByte();   // Advance 2 bytes.
                        lowByte  = reader.ReadByte();
                    }
                    else
                    {
                        return(null);
                    }

                    byte[] modInt    = { lowByte, highByte, 0x00, 0x00 }; // Reverse byte order since asn.1 key uses big endian order.
                    var    modsize   = BitConverter.ToInt32(modInt, 0);
                    var    firstByte = reader.PeekChar();
                    if (firstByte == 0x00)
                    {                      // Don't include it if the first byte (highest order) of modulus is zero.
                        reader.ReadByte(); // Skip this null byte.
                        modsize -= 1;      // Reduce modulus buffer size by 1.
                    }

                    var modulus = reader.ReadBytes(modsize); // Read the modulus bytes.
                    if (reader.ReadByte() != 0x02)           // Expect an Integer for the exponent data.
                    {
                        return(null);
                    }
                    var expBytes = (int)reader.ReadByte();  // Should only need one byte for actual exponent data (for all useful values).
                    var exponent = reader.ReadBytes(expBytes);

                    // Create RSACryptoServiceProvider instance and initialize with public key.
                    return(new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    });
                }
            }
        }
    }
Ejemplo n.º 17
0
            public void WhenIsNull_ThenReturnEmpty()
            {
                var result = ListExtensions.NullToEmpty(null as IList <string>);

                Assert.That(result, Is.Empty);
            }
Ejemplo n.º 18
0
        public async Task <RedditDdDtoList> GetStockPricesForUi(List <RedditDdDto> dtos, RedditOtherRequest request)
        {
            string pattern          = @"[A-Z]{2,}";
            var    regex            = new Regex(pattern);
            var    tickers          = new List <string>();
            var    validatedTickers = new List <string>();
            var    stockList        = await _stockListService.GetStockList();

            foreach (var dto in dtos)
            {
                if (!string.IsNullOrWhiteSpace(dto.title))
                {
                    var potentialTickers = dto.title.Split();
                    var uppercaseTickers = new List <string>();
                    foreach (var val in potentialTickers)
                    {
                        var match = regex.Match(val);
                        if (!string.IsNullOrWhiteSpace(match.Value) && !StockLists.TickerBlackList.Contains(match.Value))
                        {
                            if (!tickers.Contains(match.Value))
                            {
                                tickers.Add(match.Value);
                            }
                            uppercaseTickers.Add(match.Value);
                        }
                    }

                    dto.PotentialTickers = uppercaseTickers;
                }
            }

            foreach (var ticker in tickers)
            {
                if (stockList.Select(x => x.Symbol).Contains(ticker))
                {
                    validatedTickers.Add(ticker);
                }
            }

            var result = new List <StockPriceHistoric>();

            if (validatedTickers.Count != 0)
            {
                var stockSplits = ListExtensions.Split(validatedTickers, 5);
                foreach (var stockSplit in stockSplits)
                {
                    var stockSymbols = StringExtensions.GetSymbolsString(stockSplit);
                    var prices       = await _stockPriceService.GetHistoricPrices(stockSymbols, DateTime.Now.AddDays(-100), DateTime.Now);

                    if (prices.HistoricalStockList != null)
                    {
                        foreach (var price in prices.HistoricalStockList)
                        {
                            result.Add(price);
                        }
                    }
                }
            }

            foreach (var dto in dtos)
            {
                dto.Prices = new StockPricesForUi();
                foreach (var potentialTicker in dto.PotentialTickers)
                {
                    var prices = result.Where(x => x.Symbol.Contains(potentialTicker)).ToList();
                    if (prices.Count != 0 && prices[0].Historical != null && prices[0].Historical.Count >= 61)
                    {
                        dto.Ticker = prices[0].Symbol;
                        if (prices[0].Historical[0] != null)
                        {
                            if (prices[0]?.Historical[1] != null)
                            {
                                dto.Prices.Day = new StockPriceForUi()
                                {
                                    Performance =
                                        decimal.Round(((prices[0].Historical[0].AdjClose - prices[0].Historical[1].AdjClose) / prices[0].Historical[1].AdjClose), 2, MidpointRounding.AwayFromZero)

                                        //.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 })
                                };
                            }
                            if (prices[0]?.Historical[5] != null)
                            {
                                dto.Prices.Week = new StockPriceForUi()
                                {
                                    Performance =
                                        decimal.Round(((prices[0].Historical[0].AdjClose - prices[0].Historical[5].AdjClose) / prices[0].Historical[5].AdjClose), 2, MidpointRounding.AwayFromZero)


                                        //.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 })
                                };
                            }
                            if (prices[0]?.Historical[20] != null)
                            {
                                dto.Prices.Month = new StockPriceForUi()
                                {
                                    Performance =
                                        decimal.Round(((prices[0].Historical[0].AdjClose - prices[0].Historical[20].AdjClose) / prices[0].Historical[20].AdjClose), 2, MidpointRounding.AwayFromZero)

                                        //.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 })
                                };
                            }
                            if (prices[0]?.Historical[60] != null)
                            {
                                dto.Prices.ThreeMonths = new StockPriceForUi()
                                {
                                    Performance = decimal.Round(((prices[0].Historical[0].AdjClose - prices[0].Historical[60].AdjClose) / prices[0].Historical[60].AdjClose), 2, MidpointRounding.AwayFromZero)

                                                  //.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 })
                                };
                            }
                        }
                    }
                }
            }

            return(new RedditDdDtoList()
            {
                Aggregated = GetAggregateds(dtos),
                Items = dtos,
                Paging = new PagingModel()
                {
                    Page = request.Page,
                    PageSize = request.RowsPerPage,
                    TotalItems = result.Count
                }
            });
        }
Ejemplo n.º 19
0
 public void WhenSourceIsNull_ThenThrowException()
 {
     Assert.Throws <ArgumentNullException>(() => ListExtensions.GetNext(null as IList <string>, 0));
 }
Ejemplo n.º 20
0
        public void ReceiveBook(VariableViewerNetworking.NetFriendlyBook Book)
        {
            Pool();
            ID                = Book.ID;
            Title             = Book.Title;
            PresentPagesCount = 0;

            CurrentlyOpenBook = Book;

            if (History.Count > 0)
            {
                HistoryBackwards.SetActive(true);
            }
            if (!NotModifyingHistory)
            {
                if ((History.Count - 1) != HistoryLocation)
                {
                    ListExtensions.RemoveAtIndexForwards(History, HistoryLocation);
                }
                History.Add(Book.ID);
                HistoryLocation = HistoryLocation + 1;
            }
            NotModifyingHistory = false;

            if (HistoryLocation < 1)
            {
                HistoryBackwards.SetActive(false);
            }
            else
            {
                HistoryBackwards.SetActive(true);
            }

            if (HistoryLocation + 1 < History.Count)
            {
                HistoryForward.SetActive(true);
            }
            else
            {
                HistoryForward.SetActive(false);
            }

            foreach (var page in CurrentlyOpenBook.BindedPages)
            {
                if (UIShowDebugOptions.toggle == false)
                {
                    if (page.VVHighlight == VVHighlight.DEBUG || (page.VariableType == null && page.VVHighlight != VVHighlight.DEBUG))
                    {
                        continue;
                    }
                }

                GUI_PageEntry PageEntry;
                if (PooledPages.Count > 0)
                {
                    PageEntry = PooledPages[0];
                    PooledPages.RemoveAt(0);
                    PageEntry.gameObject.SetActive(true);
                    PageEntry.transform.SetParent(PagePanel.transform, true);
                }
                else
                {
                    PageEntry = Instantiate(PageEntryPrefab) as GUI_PageEntry;
                    PageEntry.transform.SetParent(PagePanel.transform, true);
                    PageEntry.transform.localScale = Vector3.one;
                }

                PageEntry.Page = page;
                //Logger.Log(JsonConvert.SerializeObject(page));
                if (PresentPagesCount > MaximumPerTwoPages)
                {
                    PageEntry.gameObject.SetActive(false);
                    int PageSetNumber = (int)Math.Floor((decimal)(PresentPagesCount / MaximumPerTwoPages));

                    if ((PagesInBook.Count - 1) != PageSetNumber)
                    {
                        PagesInBook.Add(new List <GUI_PageEntry>());
                    }
                    PagesInBook[PageSetNumber].Add(PageEntry);
                }
                else
                {
                    PagesInBook[0].Add(PageEntry);
                }
                PresentPagesCount++;
            }
            CurrentlyOpen    = PagesInBook[0];
            intCurrentlyOpen = 0;
            if (PagesInBook.Count > 1)
            {
                RightArrow.SetActive(true);
            }
        }
Ejemplo n.º 21
0
 public void WhenSourceIsNull_ThenThrowException()
 {
     Assert.Throws <ArgumentNullException>(() => ListExtensions.MoveToFirst(null, _customer1));
 }
 public CategoryDetailsDto GetCategoryDetailItemById(int id, string urlStr)
 {
     return(ListExtensions.ToCategoryDetailItem(DataContext.Categories.Where(x => x.Id == id).ToList(), urlStr).FirstOrDefault());
 }
Ejemplo n.º 23
0
 public override string ToString()
 {
     return(ListExtensions.ToString(TrainingEntries));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Verifies that a digital signature is valid by calculating the hash value of the specified data
 /// using the specified hash algorithm and padding, and comparing it to the provided signature.
 /// </summary>
 /// <param name="data">The data to sign.</param>
 /// <param name="signature">The signature data to be verified.</param>
 /// <returns>true if the signature is valid; otherwise, false.</returns>
 public bool Verify(byte[] data, byte[] signature)
 {
     return(verify != null
         ? verify(data, signature, secretBytes)
         : ListExtensions.Equals(sign(data, secretBytes), signature));
 }
Ejemplo n.º 25
0
        private void LoadInformation()
        {
            using (var ctx = new ApplicationDbContext())
            {
                #region commented

                //var minDate = DateTime.MinValue;
                //var maxDate = DateTime.MaxValue;

                //DateTime tempDateTime;

                //if (DateTime.TryParseExact(txtStartDate.Text.Trim(), "dd/MM/yyyy", null, DateTimeStyles.None,
                //    out tempDateTime))
                //{
                //    minDate = tempDateTime;
                //}

                //if (DateTime.TryParseExact(txtEndDate.Text.Trim(), "dd/MM/yyyy", null, DateTimeStyles.None,
                //    out tempDateTime))
                //{
                //    maxDate = tempDateTime;
                //}


                //// To make the endDate as the last minute of the day so that x < endDate comparision can work correctly.
                //if (maxDate.Date != DateTime.MaxValue.Date)
                //{
                //    maxDate = maxDate.AddDays(1).AddMilliseconds(-1);
                //}

                #endregion

                var transactions = ctx.Transactions.ToList();


                var transactionsExpenses = transactions.Where(
                    x =>
                    x.TransactionLegs.Single(y => y.TransactionLegType == TransactionLegType.Debit)
                    .Account.AccountCategory == AccountCategory.Nominal).ToList();


                var reversals = transactions.Where(
                    x =>
                    x.TransactionLegs.Single(y => y.TransactionLegType == TransactionLegType.Credit)
                    .Account.AccountCategory == AccountCategory.Nominal).ToList();

                reversals.ForEach(tran => ListExtensions.ForEach(tran.TransactionLegs, leg => leg.Amount *= -1));


                transactions = transactionsExpenses.Union(reversals).OrderBy(x => x.Timestamp).ToList();


                var finalData2 = transactions.Select(x => new
                {
                    TransactionDate = x.Timestamp,
                    DebitAccount    =
                        x.TransactionLegs.Single(y => y.TransactionLegType == TransactionLegType.Debit)
                        .Account.AccountName,
                    CreditAccount =
                        x.TransactionLegs.Single(y => y.TransactionLegType == TransactionLegType.Credit)
                        .Account.AccountName,
                    Amount = x.TransactionLegs.First().Amount,
                    TransactionDescription = x.Description
                })
                                 .GroupBy(g => g.TransactionDate.Date)
                                 .Select(q => new { Date = q.Key.Date, Amount = q.Sum(tr => tr.Amount) })
                                 .OrderBy(item => item.Date);


                var dayExpenses = (from dynamic item in finalData2 select new DayExpense(item.Date, item.Amount)).ToList();

                Session["_ExpensesSummary_ExpensesChart"] = dayExpenses;

                //var chartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), ddlChartType.SelectedValue);

                Chart1.Series.Clear();
                Chart1.Series.Add(new Series()
                {
                    ChartType = SeriesChartType.Column,
                });

                Chart1.Series[0]["PixelPointWidth"] = "15";
                Chart1.Series[0].XValueType         = ChartValueType.Date;

                Chart1.ChartAreas[0].AxisX.Interval     = 1;
                Chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;

                Chart1.ChartAreas[0].AxisX.MajorGrid = new Grid()
                {
                    Enabled = false
                };

                Chart1.Series[0].XValueType = ChartValueType.DateTime;
                var minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddSeconds(-1);
                var maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddSeconds(-1); // or DateTime.Now;
                Chart1.ChartAreas[0].AxisX.Minimum = minDate.ToOADate();
                Chart1.ChartAreas[0].AxisX.Maximum = maxDate.ToOADate();


                Chart1.ChartAreas[0].AxisY.Interval = 10;
                Chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot;
                Chart1.ChartAreas[0].AxisY.MajorGrid.LineColor     = Color.DarkGray;


                foreach (var item in finalData2)
                {
                    Chart1.Series[0].Points.AddXY(item.Date, item.Amount);
                }
            }
        }
        /// <summary>
        /// Called when [imports satisfied].
        /// </summary>
        public override void OnImportsSatisfied()
        {
            base.OnImportsSatisfied();

            CurrentMappingBasis = ConfigurationService.HospitalRegion;
            ReferenceExists     = !IsInitialMapping;

            AddStateToContextCommand      = new DelegateCommand(OnAddState, CanAddState);
            RemoveStateFromContextCommand = new DelegateCommand <SelectListItem>(OnRemoveStateCommand, CanRemoveState);
            ApplyContextCommand           = new DelegateCommand(OnApplyContextCommand, CanApplyContextCommand);
            NavigateBackCommand           = new DelegateCommand(OnNavigateBackCommand);
            SelectedStates = CollectionHelper.EmptyListCollectionView <SelectListItem>();
            var crit = PredicateBuilder.True <State>();

            ListExtensions.ForEach(CurrentMappingBasis.DefaultStates.OfType <string>().ToList(),
                                   ab => crit = crit.And(st => st.Abbreviation != ab));

            var availStates = new List <SelectListItem>();

            availStates.Add(SELECT_STATE);

            var allStates = HospitalRegistryService.GetStates(null).ToList();

            availStates.AddRange(allStates.AsQueryable()
                                 .Where(crit)
                                 .Select(state => new SelectListItem {
                Model = state, Text = state.Abbreviation, Value = state.Abbreviation
            })
                                 //.Concat(new[] { SELECT_STATE })
                                 .OrderBy(item => item.Text).ToList());

            AvailableStates = availStates.ToListCollectionView();

            crit = PredicateBuilder.False <State>();

            ListExtensions.ForEach(CurrentMappingBasis.DefaultStates
                                   .OfType <string>(), ab => crit = crit.Or(st => st.Abbreviation == ab));

            var selectedStates = allStates.AsQueryable().Where(crit).Select(st => new SelectListItem {
                Text = st.Abbreviation, Value = st.Abbreviation, Model = st
            }).ToList();

            // Setting the Selected Reporting States for Global use.
            //if (!MonahrqContext.ReportingStatesContext.Any(s => selectedStates.Any(s1 => s.In(s1)) ))
            //    MonahrqContext.ReportingStatesContext.AddRange(selectedStates);
            MonahrqContext.ReportingStatesContext.AddRange(selectedStates.Select(s => s.Text).ToList());

            SelectedStates = selectedStates.ToListCollectionView();
            SelectedStates.CommitNew();
            AvailableStates.CommitEdit();
            AvailableStates.MoveCurrentToFirst();

            SelectedState = SELECT_STATE;

            // Regions for combo box, Object type return "SELECT" on display, and NULL on return using
            RegionTypes = (new[] {
                typeof(object),
                typeof(CustomRegion),
                typeof(HealthReferralRegion),
                typeof(HospitalServiceArea)
            }).ToListCollectionView();

            SelectedRegionType = CurrentMappingBasis.SelectedRegionType;
        }
Ejemplo n.º 27
0
        public Task DownloadMetadataAsync(
            List <Game> games,
            MetadataDownloaderSettings settings,
            Action <Game, int, int> processCallback,
            CancellationTokenSource cancelToken)
        {
            return(Task.Run(() =>
            {
                if (games == null || games.Count == 0)
                {
                    return;
                }

                for (int i = 0; i < games.Count; i++)
                {
                    Game game = null;

                    try
                    {
                        if (cancelToken?.IsCancellationRequested == true)
                        {
                            return;
                        }

                        GameMetadata storeData = null;
                        GameMetadata igdbData = null;
                        GameMetadata gameData = null;

                        // We need to get new instance from DB in case game got edited or deleted.
                        // We don't want to block game editing while metadata is downloading for other games.
                        game = database.Games[games[i].Id];
                        if (game == null)
                        {
                            logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata download.");
                            processCallback?.Invoke(null, i, games.Count);
                            continue;
                        }

                        logger.Debug($"Downloading metadata for {game.Name}, {game.GameId}, {game.PluginId}");

                        // Name
                        if (!game.IsCustomGame && settings.Name.Import)
                        {
                            gameData = ProcessField(game, settings.Name, ref storeData, ref igdbData, (a) => a.GameData?.Name);
                            if (!string.IsNullOrEmpty(gameData?.GameData?.Name))
                            {
                                game.Name = StringExtensions.RemoveTrademarks(gameData.GameData.Name);
                                var sortingName = StringExtensions.ConvertToSortableName(game.Name);
                                if (sortingName != game.Name)
                                {
                                    game.SortingName = sortingName;
                                }
                            }
                        }

                        // Genre
                        if (settings.Genre.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Genres)))
                            {
                                gameData = ProcessField(game, settings.Genre, ref storeData, ref igdbData, (a) => a.GameData?.Genres);
                                game.Genres = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Genres) ? game.Genres : gameData.GameData.Genres;
                            }
                        }

                        // Release Date
                        if (settings.ReleaseDate.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.ReleaseDate == null))
                            {
                                gameData = ProcessField(game, settings.ReleaseDate, ref storeData, ref igdbData, (a) => a.GameData?.ReleaseDate);
                                game.ReleaseDate = gameData?.GameData?.ReleaseDate ?? game.ReleaseDate;
                            }
                        }

                        // Developer
                        if (settings.Developer.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Developers)))
                            {
                                gameData = ProcessField(game, settings.Developer, ref storeData, ref igdbData, (a) => a.GameData?.Developers);
                                game.Developers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Developers) ? game.Developers : gameData.GameData.Developers;
                            }
                        }

                        // Publisher
                        if (settings.Publisher.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Publishers)))
                            {
                                gameData = ProcessField(game, settings.Publisher, ref storeData, ref igdbData, (a) => a.GameData?.Publishers);
                                game.Publishers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Publishers) ? game.Publishers : gameData.GameData.Publishers;
                            }
                        }

                        // Tags / Features
                        if (settings.Tag.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Tags)))
                            {
                                gameData = ProcessField(game, settings.Tag, ref storeData, ref igdbData, (a) => a.GameData?.Tags);
                                game.Tags = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Tags) ? game.Tags : gameData.GameData.Tags;
                            }
                        }

                        // Description
                        if (settings.Description.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Description)))
                            {
                                gameData = ProcessField(game, settings.Description, ref storeData, ref igdbData, (a) => a.GameData?.Description);
                                game.Description = string.IsNullOrEmpty(gameData?.GameData?.Description) == true ? game.Description : gameData.GameData.Description;
                            }
                        }

                        // Links
                        if (settings.Links.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.Links == null))
                            {
                                gameData = ProcessField(game, settings.Links, ref storeData, ref igdbData, (a) => a.GameData?.Links);
                                game.Links = gameData?.GameData?.Links ?? game.Links;
                            }
                        }

                        // Critic Score
                        if (settings.CriticScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CriticScore == null))
                            {
                                gameData = ProcessField(game, settings.CriticScore, ref storeData, ref igdbData, (a) => a.GameData?.CriticScore);
                                game.CriticScore = gameData?.GameData?.CriticScore == null ? game.CriticScore : gameData.GameData.CriticScore;
                            }
                        }

                        // Community Score
                        if (settings.CommunityScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CommunityScore == null))
                            {
                                gameData = ProcessField(game, settings.CommunityScore, ref storeData, ref igdbData, (a) => a.GameData?.CommunityScore);
                                game.CommunityScore = gameData?.GameData?.CommunityScore == null ? game.CommunityScore : gameData.GameData.CommunityScore;
                            }
                        }

                        // BackgroundImage
                        if (settings.BackgroundImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.BackgroundImage)))
                            {
                                gameData = ProcessField(game, settings.BackgroundImage, ref storeData, ref igdbData, (a) => a.BackgroundImage);
                                if (!string.IsNullOrEmpty(gameData?.BackgroundImage))
                                {
                                    RemoveGameMedia(game.BackgroundImage);
                                    game.BackgroundImage = gameData.BackgroundImage;
                                }
                            }
                        }

                        // Cover
                        if (settings.CoverImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.CoverImage)))
                            {
                                gameData = ProcessField(game, settings.CoverImage, ref storeData, ref igdbData, (a) => a.Image);
                                if (gameData?.Image != null)
                                {
                                    RemoveGameMedia(game.CoverImage);
                                    game.CoverImage = database.AddFile(gameData.Image, game.Id);
                                }
                            }
                        }

                        // Icon
                        if (settings.Icon.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Icon)))
                            {
                                gameData = ProcessField(game, settings.Icon, ref storeData, ref igdbData, (a) => a.Icon);
                                if (gameData?.Icon != null)
                                {
                                    RemoveGameMedia(game.Icon);
                                    game.Icon = database.AddFile(gameData.Icon, game.Id);
                                }
                            }
                        }

                        // TODO make this configurable and re-downalodable manually
                        // Only update them if they don't exist yet
                        if (game.OtherActions?.Any() != true && storeData != null)
                        {
                            if (storeData?.GameData?.OtherActions?.Any() == true)
                            {
                                game.OtherActions = new System.Collections.ObjectModel.ObservableCollection <GameAction>();
                                foreach (var task in storeData.GameData.OtherActions)
                                {
                                    game.OtherActions.Add(task);
                                }
                            }
                        }

                        // Just to be sure check if somebody didn't remove game while downloading data
                        if (database.Games.FirstOrDefault(a => a.GameId == games[i].GameId) != null)
                        {
                            database.Games.Update(game);
                        }
                        else
                        {
                            logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata update in DB.");
                        }
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, $"Failed to download metadata for game {game?.Name}, {game?.GameId}");
                    }
                    finally
                    {
                        if (game != null)
                        {
                            processCallback?.Invoke(game, i, games.Count);
                        }
                    }
                }
            }));
        }
Ejemplo n.º 28
0
        public static Result Circle(Spell spell,
                                    Obj_AI_Hero target,
                                    HitChance hitChance,
                                    bool boundingRadius = true,
                                    bool extended       = true)
        {
            try
            {
                if (spell == null || target == null)
                {
                    return(new Result(Vector3.Zero, new List <Obj_AI_Hero>()));
                }
                var hits   = new List <Obj_AI_Hero>();
                var center = Vector3.Zero;
                var radius = float.MaxValue;
                var range  = spell.Range + (extended ? spell.Width * 0.85f : 0) +
                             (boundingRadius ? target.BoundingRadius * BoundingRadiusMultiplicator : 0);
                var positions = (from t in GameObjects.EnemyHeroes
                                 where t.IsValidTarget(range * 1.5f, true, spell.RangeCheckFrom)
                                 let prediction = spell.GetPrediction(t)
                                                  where prediction.Hitchance >= hitChance
                                                  select new Position(t, prediction.UnitPosition)).ToList();
                var spellWidth = spell.Width;
                if (positions.Any())
                {
                    var mainTarget    = positions.FirstOrDefault(p => p.Hero.NetworkId == target.NetworkId);
                    var possibilities =
                        ListExtensions.ProduceEnumeration(
                            positions.Where(
                                p => p.UnitPosition.Distance(mainTarget.UnitPosition) <= spell.Width * 0.85f).ToList())
                        .Where(p => p.Count > 0 && p.Any(t => t.Hero.NetworkId == mainTarget.Hero.NetworkId))
                        .ToList();
                    foreach (var possibility in possibilities)
                    {
                        var mec      = MEC.GetMec(possibility.Select(p => p.UnitPosition.To2D()).ToList());
                        var distance = spell.From.Distance(mec.Center.To3D());
                        if (mec.Radius < spellWidth && distance < range)
                        {
                            var lHits  = new List <Obj_AI_Hero>();
                            var circle =
                                new Geometry.Polygon.Circle(
                                    spell.From.Extend(
                                        mec.Center.To3D(), spell.Range > distance ? distance : spell.Range), spell.Width);

                            if (boundingRadius)
                            {
                                lHits.AddRange(
                                    from position in positions
                                    where
                                    new Geometry.Polygon.Circle(
                                        position.UnitPosition,
                                        position.Hero.BoundingRadius * BoundingRadiusMultiplicator).Points.Any(
                                        p => circle.IsInside(p))
                                    select position.Hero);
                            }
                            else
                            {
                                lHits.AddRange(
                                    from position in positions
                                    where circle.IsInside(position.UnitPosition)
                                    select position.Hero);
                            }

                            if ((lHits.Count > hits.Count || lHits.Count == hits.Count && mec.Radius < radius ||
                                 lHits.Count == hits.Count &&
                                 spell.From.Distance(circle.Center.To3D()) < spell.From.Distance(center)) &&
                                lHits.Any(p => p.NetworkId == target.NetworkId))
                            {
                                center = circle.Center.To3D2();
                                radius = mec.Radius;
                                hits.Clear();
                                hits.AddRange(lHits);
                            }
                        }
                    }
                    if (!center.Equals(Vector3.Zero))
                    {
                        return(new Result(center, hits));
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
            return(new Result(Vector3.Zero, new List <Obj_AI_Hero>()));
        }
Ejemplo n.º 29
0
 public override string ToString()
 {
     return(string.Format("Order(Id={0},SourceId={1},Status={2},Amount={3},DiscountAmount={4},Items={5})",
                          this.Id, this.SourceId, this.Status, this.Amount, this.DiscountAmount, ListExtensions.ToString <OrderItem>(this.Items)));
 }