System.Collections.Generic.IEnumerable.Aggregate(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Aggregate(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

581 Examples 7

19 View Source File : Monitor.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void Log(
        string key, 
        object value, 
        MonitorType displayType = MonitorType.text, 
        Transform target = null)
    {



        if (!isInstanciated)
        {
            InstanciateCanvas();
            isInstanciated = true;

        }

        if (target == null)
        {
            target = canvas.transform;
        }

        if (!displayTransformValues.Keys.Contains(target))
        {
            displayTransformValues[target] = new Dictionary<string, DisplayValue>();
        }

        Dictionary<string, DisplayValue> displayValues = displayTransformValues[target];

        if (value == null)
        {
            RemoveValue(target, key);
            return;
        }
        if (!displayValues.ContainsKey(key))
        {
            DisplayValue dv = new DisplayValue();
            dv.time = Time.timeSinceLevelLoad;
            dv.value = value;
            dv.monitorDisplayType = displayType;
            displayValues[key] = dv;
            while (displayValues.Count > 20)
            {
                string max = displayValues.Aggregate((l, r) => l.Value.time < r.Value.time ? l : r).Key;
                RemoveValue(target, max);
            }
        }
        else
        {
            DisplayValue dv = displayValues[key];
            dv.value = value;
            displayValues[key] = dv;
        }
    }

19 View Source File : PlusConverter.cs
License : MIT License
Project Creator : Accelerider

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            double? result = values.Select(value => double.Parse(value.ToString())).Aggregate((sum, value) => sum + value);
            return result <= 0 ? null : result;
        }

19 View Source File : Files.vm.cs
License : MIT License
Project Creator : Accelerider

private string CombinePath(params string[] paths)
        {
            return paths.Aggregate((acc, item) =>
                item.StartsWith("/") || item.StartsWith("\\")
                    ? acc + item
                    : Path.Combine(acc, item));
        }

19 View Source File : Print.cs
License : MIT License
Project Creator : Accelerider

private static void WriteToConsole(string message, OutType outType = OutType.Info)
        {
            var backupBackground = Console.BackgroundColor;
            var backupForeground = Console.ForegroundColor;

            Console.BackgroundColor = OutColors[outType];
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write($"[{outType.ToString().ToUpper()}]");
            Console.BackgroundColor = backupBackground;

            Console.ForegroundColor = OutColors[outType];
            var spaces = Enumerable.Repeat(" ", 8 - outType.ToString().Length).Aggregate((acc, item) => acc + item);
            Console.WriteLine($"{spaces}{message}");
            Console.ForegroundColor = backupForeground;
        }

19 View Source File : ConstantRemotePathProvider.cs
License : MIT License
Project Creator : Accelerider

public virtual Task<string> GetAsync()
        {
            if (RemotePaths.Values.All(item => item < 0))
                throw new RemotePathExhaustedException(this);

            return Task.FromResult(
                RemotePaths.Aggregate((acc, item) => acc.Value < item.Value ? item : acc).Key);
        }

19 View Source File : CommandParameterHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";
            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List<ACECommandParameter> acps = parameters.ToList();
            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                            case ACECommandParameterType.PositiveLong:
                                Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match4.Success)
                                {
                                    if (!long.TryParse(match4.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    if (val <= 0)
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                                }
                                break;
                            case ACECommandParameterType.Long:
                                Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match3.Success)
                                {
                                    if (!long.TryParse(match3.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.ULong:
                                Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match2.Success)
                                {
                                    if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.Location:
                                Position position = null;
                                Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    string ns = match.Groups[1].Value;
                                    string ew = match.Groups[2].Value;
                                    if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                    {
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMessage);
                                        }
                                        return false;
                                    }
                                    else
                                    {
                                        acp.Value = position;
                                        acp.Defaulted = false;
                                        int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                        parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                    }
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer == null)
                                {
                                    string errorMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMsg);
                                    }
                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerNameOrIid:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }

                                if (!parameterBlob.Contains(' '))
                                {
                                    if (uint.TryParse(parameterBlob, out uint iid))
                                    {
                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {iid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            break;
                                        }
                                    }
                                }
                                Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer3 == null)
                                {
                                    string logMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(logMsg);
                                    }

                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer3;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerIid:
                                Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
                                if (matcha5.Success)
                                {
                                    string strIid = "";
                                    if (matcha5.Groups[2].Success)
                                    {
                                        strIid = matcha5.Groups[2].Value;
                                    }
                                    else if (matcha5.Groups[1].Success)
                                    {
                                        strIid = matcha5.Groups[1].Value;
                                    }
                                    try
                                    {
                                        uint iid = 0;
                                        if (strIid.StartsWith("0x"))
                                        {
                                            iid = Convert.ToUInt32(strIid, 16);
                                        }
                                        else
                                        {
                                            iid = uint.Parse(strIid);
                                        }

                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {strIid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        string errorMsg = $"Unable to parse {strIid} into a player iid";
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMsg);
                                        }
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.PlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                if (string.IsNullOrWhiteSpace(parameterBlob))
                                {
                                    break;
                                }
                                else
                                {
                                    acp.Value = parameterBlob;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.Uri:
                                Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[[email protected]:%._\+~#=]{2,256}\.[a-z]{2,6}\b([[email protected]:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
                                if (match5.Success)
                                {
                                    string strUri = match5.Groups[1].Value;
                                    try
                                    {
                                        Uri url = new Uri(strUri);
                                        acp.Value = url;
                                        acp.Defaulted = false;
                                        parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.DoubleQuoteEnclosedText:
                                Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
                                if (match6.Success)
                                {
                                    string txt = match6.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.Trim('"');
                                        acp.Defaulted = false;
                                        parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.CommaPrefixedText:
                                if (i == 0)
                                {
                                    throw new Exception("this parameter type is not appropriate as the first parameter");
                                }
                                if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
                                {
                                    break;
                                }
                                Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
                                if (match7.Success)
                                {
                                    string txt = match7.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(new char[] { ' ', ',' });
                                        acp.Defaulted = false;
                                        parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.SimpleWord:
                                Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match8.Success)
                                {
                                    string txt = match8.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(' ');
                                        acp.Defaulted = false;
                                        parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.Enum:
                                if (acp.PossibleValues == null)
                                {
                                    throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
                                }
                                if (!acp.PossibleValues.IsEnum)
                                {
                                    throw new Exception("PossibleValues must be an enum type");
                                }
                                Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match9.Success)
                                {
                                    string txt = match9.Groups[1].Value;
                                    try
                                    {
                                        txt = txt.Trim(new char[] { ' ', ',' });
                                        Array etvs = Enum.GetValues(acp.PossibleValues);
                                        foreach (object etv in etvs)
                                        {
                                            if (etv.ToString().ToLower() == txt.ToLower())
                                            {
                                                acp.Value = etv;
                                                acp.Defaulted = false;
                                                parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
                                                break;
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                if (acp.Defaulted)
                {
                    acp.Value = acp.DefaultValue;
                }

                if (acp.Required && acp.Defaulted)
                {
                    if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
                    {
                        if (session != null)
                        {
                            ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
                        }
                        else
                        {
                            Console.WriteLine(acp.ErrorMessage);
                        }
                    }

                    return false;
                }
            }
            return true;
        }

19 View Source File : PacketHeaderOptional.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public override string ToString()
        {
            if (Size == 0 || !IsValid)
            {
                return string.Empty;
            }

            string nice = "";
            if (Header.HasFlag(PacketHeaderFlags.Flow))
            {
                nice = $" {FlowBytes} Interval: {FlowInterval}";
            }
            if (RetransmitData != null)
            {
                nice += $" requesting {RetransmitData.DefaultIfEmpty().Select(t => t.ToString()).Aggregate((a, b) => a + "," + b)}";
            }
            if (Header.HasFlag(PacketHeaderFlags.AckSequence))
            {
                nice += $" AckSeq: {AckSequence}";
            }
            return nice.Trim();
        }

19 View Source File : NetworkSession.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private void DoRequestForRetransmission(uint rcvdSeq)
        {
            var desiredSeq = lastReceivedPacketSequence + 1;
            List<uint> needSeq = new List<uint>();
            needSeq.Add(desiredSeq);
            uint bottom = desiredSeq + 1;
            if (rcvdSeq < bottom || rcvdSeq - bottom > CryptoSystem.MaximumEffortLevel)
            {
                session.Terminate(SessionTerminationReason.AbnormalSequenceReceived);
                return;
            }
            uint seqIdCount = 1;
            for (uint a = bottom; a < rcvdSeq; a++)
            {
                if (!outOfOrderPackets.ContainsKey(a))
                {
                    needSeq.Add(a);
                    seqIdCount++;
                    if (seqIdCount >= MaxNumNakSeqIds)
                    {
                        break;
                    }
                }
            }

            ServerPacket reqPacket = new ServerPacket();
            byte[] reqData = new byte[4 + (needSeq.Count * 4)];
            MemoryStream msReqData = new MemoryStream(reqData, 0, reqData.Length, true, true);
            msReqData.Write(BitConverter.GetBytes((uint)needSeq.Count), 0, 4);
            needSeq.ForEach(k => msReqData.Write(BitConverter.GetBytes(k), 0, 4));
            reqPacket.Data = msReqData;
            reqPacket.Header.Flags = PacketHeaderFlags.RequestRetransmit;

            EnqueueSend(reqPacket);

            LastRequestForRetransmitTime = DateTime.UtcNow;
            packetLog.DebugFormat("[{0}] Requested retransmit of {1}", session.LoggingIdentifier, needSeq.Select(k => k.ToString()).Aggregate((a, b) => a + ", " + b));
            NetworkStatistics.S2C_RequestsForRetransmit_Aggregate_Increment();
        }

19 View Source File : PacketHeaderFlagsUtil.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string UnfoldFlags(PacketHeaderFlags flags)
        {
            List<string> result = new List<string>();
            foreach (PacketHeaderFlags r in System.Enum.GetValues(typeof(PacketHeaderFlags)))
            {
                if ((flags & r) != 0)
                {
                    result.Add(r.ToString());
                }
            }
            return result.DefaultIfEmpty().Aggregate((a, b) => a + " | " + b);
        }

19 View Source File : ManaStone.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public override void HandleActionUseOnTarget(Player player, WorldObject target)
        {
            WorldObject invTarget;

            var useResult = WeenieError.None;

            if (player.IsOlthoiPlayer)
            {
                player.SendUseDoneEvent(WeenieError.OlthoiCannotInteractWithThat);
                return;
            }

            if (player != target)
            {
                invTarget = player.FindObject(target.Guid.Full, Player.SearchLocations.MyInventory | Player.SearchLocations.MyEquippedItems);
                if (invTarget == null)
                {
                    // Haven't looked to see if an error was sent for this case; however, this one fits
                    player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.YouDoNotOwnThareplacedem));
                    return;
                }

                target = invTarget;
            }

            if (!ItemCurMana.HasValue)
            {
                if (target == player)
                    useResult = WeenieError.ActionCancelled;
                else if (target.ItemCurMana.HasValue && target.ItemCurMana.Value > 0 && target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    // absorb mana from the item
                    if (target.Retained)
                        useResult = WeenieError.ActionCancelled;
                    else
                    {
                        if (!player.TryConsumeFromInventoryWithNetworking(target, 1) && !player.TryDequipObjectWithNetworking(target.Guid, out _, Player.DequipObjectAction.ConsumeItem))
                        {
                            log.Error($"Failed to remove {target.Name} from player inventory.");
                            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.ActionCancelled));
                            return;
                        }

                        //The Mana Stone drains 5,253 points of mana from the Wand.
                        //The Wand is destroyed.

                        //The Mana Stone drains 4,482 points of mana from the Pantaloons.
                        //The Pantaloons is destroyed.

                        var manaDrained = (int)Math.Round(Efficiency.Value * target.ItemCurMana.Value);
                        ItemCurMana = manaDrained;
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The Mana Stone drains {ItemCurMana:N0} points of mana from the {target.Name}.\nThe {target.Name} is destroyed.", ChatMessageType.Broadcast));
                        SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Magical);
                    }
                }
                else
                {
                    useResult = WeenieError.ItemDoesntHaveEnoughMana;
                }
            }
            else if (ItemCurMana.Value > 0)
            {
                if (target == player)
                {
                    // dump mana into equipped items
                    var origItemsNeedingMana = player.EquippedObjects.Values.Where(k => k.ItemCurMana.HasValue && k.ItemMaxMana.HasValue && k.ItemCurMana < k.ItemMaxMana).ToList();
                    var itemsGivenMana = new Dictionary<WorldObject, int>();

                    while (ItemCurMana > 0)
                    {
                        var itemsNeedingMana = origItemsNeedingMana.Where(k => k.ItemCurMana < k.ItemMaxMana).ToList();
                        if (itemsNeedingMana.Count < 1)
                            break;

                        var ration = Math.Max(ItemCurMana.Value / itemsNeedingMana.Count, 1);

                        foreach (var item in itemsNeedingMana)
                        {
                            var manaNeededForTopoff = (int)(item.ItemMaxMana - item.ItemCurMana);
                            var adjustedRation = Math.Min(ration, manaNeededForTopoff);

                            ItemCurMana -= adjustedRation;

                            if (player.LumAugItemManaGain != 0)
                            {
                                adjustedRation = (int)Math.Round(adjustedRation * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                                if (adjustedRation > manaNeededForTopoff)
                                {
                                    var diff = adjustedRation - manaNeededForTopoff;
                                    adjustedRation = manaNeededForTopoff;
                                    ItemCurMana += diff;
                                }
                            }

                            item.ItemCurMana += adjustedRation;
                            if (!itemsGivenMana.ContainsKey(item))
                                itemsGivenMana[item] = adjustedRation;
                            else
                                itemsGivenMana[item] += adjustedRation;

                            if (ItemCurMana <= 0)
                                break;
                        }
                    }

                    if (itemsGivenMana.Count < 1)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat("You have no items equipped that need mana.", ChatMessageType.Broadcast));
                        useResult = WeenieError.ActionCancelled;
                    }
                    else
                    {
                        //The Mana Stone gives 4,496 points of mana to the following items: Fire Compound Crossbow, Qafiya, Celdon Sleeves, Amuli Leggings, Messenger's Collar, Heavy Bracelet, Scalemail Bracers, Olthoi Alduressa Gauntlets, Studded Leather Girth, Shoes, Chainmail Greaves, Loose Pants, Mechanical Scarab, Ring, Ring, Heavy Bracelet
                        //Your items are fully charged.

                        //The Mana Stone gives 1,921 points of mana to the following items: Haebrean Girth, Chiran Helm, Ring, Baggy Breeches, Scalemail Greaves, Alduressa Boots, Heavy Bracelet, Heavy Bracelet, Lorica Breastplate, Pocket Watch, Heavy Necklace
                        //You need 2,232 more mana to fully charge your items.

                        var additionalManaNeeded = origItemsNeedingMana.Sum(k => k.ItemMaxMana.Value - k.ItemCurMana.Value);
                        var additionalManaText = (additionalManaNeeded > 0) ? $"\nYou need {additionalManaNeeded:N0} more mana to fully charge your items." : "\nYour items are fully charged.";
                        var msg = $"The Mana Stone gives {itemsGivenMana.Values.Sum():N0} points of mana to the following items: {itemsGivenMana.Select(c => c.Key.Name).Aggregate((a, b) => a + ", " + b)}.{additionalManaText}";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }

                        if (UnlimitedUse && ItemMaxMana.HasValue)
                            ItemCurMana = ItemMaxMana;
                    }
                }
                else if (target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    var targereplacedemCurMana = target.ItemCurMana ?? 0;

                    if (targereplacedemCurMana >= target.ItemMaxMana)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The {target.Name} is already full of mana.", ChatMessageType.Broadcast));
                    }
                    else
                    {
                        // The Mana Stone gives 3,502 points of mana to the Focusing Stone.

                        // The Mana Stone gives 3,267 points of mana to the Protective Drudge Charm.

                        var targetManaNeeded = target.ItemMaxMana.Value - targereplacedemCurMana;
                        var manaToPour = Math.Min(targetManaNeeded, ItemCurMana.Value);

                        if (player.LumAugItemManaGain != 0)
                        {
                            manaToPour = (int)Math.Round(manaToPour * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                            manaToPour = Math.Min(targetManaNeeded, manaToPour);
                        }

                        target.ItemCurMana = targereplacedemCurMana + manaToPour;
                        var msg = $"The Mana Stone gives {manaToPour:N0} points of mana to the {target.Name}.";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }
                    }
                }
                else
                {
                    useResult = WeenieError.ActionCancelled;
                }
            }

            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, useResult));
        }

19 View Source File : EditorExtensions.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ITextBuffer CreateTextBuffer(this ITextBufferFactoryService textBufferFactoryService, IContentType contentType, params string[] lines)
        {
            textBufferFactoryService.ThrowOnNull(nameof(textBufferFactoryService));

            var textBuffer = contentType != null
                ? textBufferFactoryService.CreateTextBuffer(contentType)
                : textBufferFactoryService.CreateTextBuffer();

            if (lines.Length != 0)
            {
                var text = lines.Aggregate((x, y) => x + Environment.NewLine + y);
                textBuffer.Replace(new Span(0, 0), text);
            }

            return textBuffer;
        }

19 View Source File : TextSpan.cs
License : MIT License
Project Creator : adamant

[System.Diagnostics.Contracts.Pure]
        public static TextSpan Covering(params TextSpan?[] spans)
        {
            return spans.Where(s => s != null).Cast<TextSpan>().Aggregate(Covering);
        }

19 View Source File : GCD.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static BigInteger FindLCM(params BigInteger[] numbers)
		{
			return numbers.Aggregate(FindLCM);
		}

19 View Source File : GCD.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static BigInteger FindGCD(params BigInteger[] numbers)
		{
			return numbers.Aggregate(FindGCD);
		}

19 View Source File : BigIntegerHelper.cs
License : MIT License
Project Creator : AdamWhiteHat

public static BigInteger GCD(IEnumerable<BigInteger> numbers)
		{
			return numbers.Aggregate(GCD);
		}

19 View Source File : BigIntegerHelper.cs
License : MIT License
Project Creator : AdamWhiteHat

public static BigInteger LCM(IEnumerable<BigInteger> numbers)
		{
			return numbers.Aggregate(LCM);
		}

19 View Source File : SendToFlow.cs
License : MIT License
Project Creator : adoprog

private static string GetFieldsJson(IList<IViewModel> fields)
    {
      var sb = new StringBuilder();
      sb.Append("{");
      var fieldDescriptors = new List<string>();
      foreach (var field in fields)
      {
        if(field is StringInputViewModel)
        {
          var stringField = field as StringInputViewModel;
          fieldDescriptors.Add(" \"" + stringField.replacedle + "\" : \"" +
                               HttpUtility.JavaScriptStringEncode(stringField.Value) + "\" ");
        }
      }

      sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      sb.Append("}");
      return sb.ToString();
    }

19 View Source File : PostToFlow.cs
License : MIT License
Project Creator : adoprog

private static string GetFieldsJson(AdaptedResultList adaptedFields)
    {
      var sb = new StringBuilder();
      sb.Append("{");
      var fieldDescriptors = new List<string>();
      foreach (AdaptedControlResult adaptedField in adaptedFields)
      {
        fieldDescriptors.Add(" \"" + adaptedField.FieldName + "\" : \"" +
                             HttpUtility.JavaScriptStringEncode(adaptedField.Value) + "\" ");
      }

      sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      sb.Append("}");
      return sb.ToString();
    }

19 View Source File : SchemaPage.cs
License : MIT License
Project Creator : adoprog

private string GetFromFormFields(Item item)
    {
      var sb = new StringBuilder();
      var fieldItems = item.Axes.GetDescendants().Where(x => x.IsDerived(InputFieldTemplateId));
      sb.Append([email protected]"{{ {Environment.NewLine}  ""type"": ""object"",{Environment.NewLine}  ""properties"": {{ ");
      var fieldDescriptors = new List<string>();
      foreach (var fieldItem in fieldItems)
      {
        fieldDescriptors.Add(
          $"{Environment.NewLine}\"{HttpUtility.JavaScriptStringEncode(fieldItem["replacedle"])}\": {{\"type\": \"string\"}}");
      }

      if (fieldDescriptors.Any())
      {
        sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      }

      sb.Append(Environment.NewLine + "  } " + Environment.NewLine + "}");
      return sb.ToString();
    }

19 View Source File : SchemaPage.cs
License : MIT License
Project Creator : adoprog

private string GetFromItemFields(Item item)
    {
      var sb = new StringBuilder();
      var fields = item.Fields;
      sb.Append([email protected]"{{ {Environment.NewLine}  ""type"": ""object"",{Environment.NewLine}  ""properties"": {{ ");
      var fieldDescriptors = new List<string>();
      foreach (Field field in fields)
      {
        if (field.Name.StartsWith("__"))
        {
          continue;
        }

        fieldDescriptors.Add(
          $"{Environment.NewLine}\"{HttpUtility.JavaScriptStringEncode(field.Name)}\": {{\"type\": \"string\"}}");
      }

      fieldDescriptors.Add($"{Environment.NewLine}\"ItemUrl\": {{\"type\": \"string\"}}");

      sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      sb.Append(Environment.NewLine + "  } " + Environment.NewLine + "}");
      return sb.ToString();
    }

19 View Source File : PostToFlowPage.cs
License : MIT License
Project Creator : adoprog

protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);

      if (!Sitecore.Context.ClientPage.IsEvent)
      {
        if (!string.IsNullOrEmpty(TriggerAddressValue))
        {
          TriggerAddress.Value = TriggerAddressValue;
        }

        var formId = Sitecore.Context.Request.QueryString["id"];
        var fieldItems = Database.GetDatabase("master").Gereplacedem(formId)?.Axes.GetDescendants()
          .Where(x => x.IsDerived(new ID(FormFieldID))).ToList();

        if (fieldItems != null && fieldItems.Any())
        {
          var sb = new StringBuilder();
          sb.Append([email protected]"{{ {Environment.NewLine}  ""type"": ""object"",{Environment.NewLine}  ""properties"": {{ ");

          var fieldDescriptors = new List<string>();
          foreach (var field in fieldItems)
          {
            fieldDescriptors.Add($"{Environment.NewLine}    \"{HttpUtility.JavaScriptStringEncode(field.Name)}\": {{\"type\": \"string\"}}");
          }

          sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
          sb.Append(Environment.NewLine + "  } " + Environment.NewLine + "}");
          FlowSchema.Text = sb.ToString();
        }

        Localize();
      }
      else
      {
        TriggerAddress.Value = Sitecore.Web.WebUtil.GetFormValue("TriggerAddress");
      }
    }

19 View Source File : ItemFieldsToFlow.cs
License : MIT License
Project Creator : adoprog

private static string GetFieldsJson(Item item, string contextSite)
    {
      var sb = new StringBuilder();
      sb.Append("{");
      var fieldDescriptors = new List<string>();
      var urlOptions = new UrlOptions();
      urlOptions.AlwaysIncludeServerUrl = false;
      if (!string.IsNullOrEmpty(contextSite))
      {
        urlOptions.Site = SiteContext.GetSite(contextSite);
      }

      var url = LinkManager.GereplacedemUrl(item, urlOptions);
      url = url.Replace(" ", "%20");
      url = Settings.GetSetting("Sitecore.Flow.Actions.ServerUrl") + url;
      fieldDescriptors.Add($" \"ItemUrl\" : \"{url}\" ");

      foreach (Field field in item.Fields)
      {
        if (field.Name.StartsWith("__"))
        {
          continue;
        }

        fieldDescriptors.Add($" \"{field.Name}\" : \"{HttpUtility.JavaScriptStringEncode(field.Value)}\" ");
      }

      sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      sb.Append("}");
      return sb.ToString();
    }

19 View Source File : ClonesManager.cs
License : MIT License
Project Creator : adrenak

public static bool IsCloneProjectRunning(string projectPath)
        {

            //Determine whether it is opened in another instance by checking the UnityLockFile
            string UnityLockFilePath = new string[] { projectPath, "Temp", "UnityLockfile" }
                .Aggregate(Path.Combine);

            switch (Application.platform)
            {
                case (RuntimePlatform.WindowsEditor):
                    //Windows editor will lock "UnityLockfile" file when project is being opened.
                    //Sometime, for instance: windows editor crash, the "UnityLockfile" will not be deleted even the project
                    //isn't being opened, so a check to the "UnityLockfile" lock status may be necessary.
                    if (Preferences.AlsoCheckUnityLockFileStaPref.Value)
                        return File.Exists(UnityLockFilePath) && FileUtilities.IsFileLocked(UnityLockFilePath);
                    else
                        return File.Exists(UnityLockFilePath);
                case (RuntimePlatform.OSXEditor):
                    //Mac editor won't lock "UnityLockfile" file when project is being opened
                    return File.Exists(UnityLockFilePath);
                case (RuntimePlatform.LinuxEditor):
                    return File.Exists(UnityLockFilePath);
                default:
                    throw new System.NotImplementedException("IsCloneProjectRunning: Unsupport Platfrom: " + Application.platform);
            }
        }

19 View Source File : TreasuryContract.cs
License : MIT License
Project Creator : AElfProject

public override Empty Release(ReleaseInput input)
        {
            RequireAEDPoSContractStateSet();
            replacedert(
                Context.Sender == State.AEDPoSContract.Value,
                "Only AElf Consensus Contract can release profits from Treasury.");
            State.ProfitContract.DistributeProfits.Send(new DistributeProfitsInput
            {
                SchemeId = State.TreasuryHash.Value,
                Period = input.PeriodNumber,
                AmountsMap = {State.SymbolList.Value.Value.ToDictionary(s => s, s => 0L)}
            });
            RequireElectionContractStateSet();
            var previousTermInformation = State.AEDPoSContract.GetPreviousTermInformation.Call(new Int64Value
            {
                Value = input.PeriodNumber
            });

            var currentMinerList = State.AEDPoSContract.GetCurrentMinerList.Call(new Empty()).Pubkeys
                .Select(p => p.ToHex()).ToList();
            var maybeNewElectedMiners = new List<string>();
            maybeNewElectedMiners.AddRange(currentMinerList);
            maybeNewElectedMiners.AddRange(previousTermInformation.RealTimeMinersInformation.Keys);
            var replaceCandidates = State.ReplaceCandidateMap[input.PeriodNumber];
            if (replaceCandidates != null)
            {
                Context.LogDebug(() => $"New miners from replace candidate map: {replaceCandidates.Value.Aggregate((l, r) => $"{l}\n{r}")}");
                maybeNewElectedMiners.AddRange(replaceCandidates.Value);
                State.ReplaceCandidateMap.Remove(input.PeriodNumber);
            }
            maybeNewElectedMiners = maybeNewElectedMiners.Where(p => State.LatestMinedTerm[p] == 0 && !GetInitialMinerList().Contains(p)).ToList();
            if (maybeNewElectedMiners.Any())
            {
                Context.LogDebug(() => $"New elected miners: {maybeNewElectedMiners.Aggregate((l, r) => $"{l}\n{r}")}");
            }
            else
            {
                Context.LogDebug(() => "No new elected miner.");
            }
            UpdateStateBeforeDistribution(previousTermInformation, maybeNewElectedMiners);
            ReleaseTreasurySubProfireplacedems(input.PeriodNumber);
            UpdateStateAfterDistribution(previousTermInformation, currentMinerList);
            return new Empty();
        }

19 View Source File : UnitMakerSpawnPointSelector.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal int GetFreeParkingSpot(int airbaseID, out Coordinates parkingSpotCoordinates, Coordinates? lastSpotCoordinates = null, bool requiresOpenAirParking = false)
        {
            parkingSpotCoordinates = new Coordinates();
            if (!AirbaseParkingSpots.ContainsKey(airbaseID) || (AirbaseParkingSpots[airbaseID].Count == 0)) return -1;
            DBEntryAirbase[] airbaseDB = (from DBEntryAirbase ab in TheaterDB.GetAirbases() where ab.DCSID == airbaseID select ab).ToArray();
            if (airbaseDB.Length == 0) return -1; // No airbase with proper DCSID
            DBEntryAirbaseParkingSpot? parkingSpot = null;
            if (lastSpotCoordinates != null) //find nearest spot distance wise in attempt to cluster
                parkingSpot = AirbaseParkingSpots[airbaseID].FindAll(x => (!requiresOpenAirParking || x.ParkingType != ParkingSpotType.HardenedAirShelter))
                    .ToList()
                    .Aggregate((acc, x) => acc.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) > x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) && x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) != 0 ? x : acc);
            else
                parkingSpot = Toolbox.RandomFrom(AirbaseParkingSpots[airbaseID]);
            AirbaseParkingSpots[airbaseID].Remove(parkingSpot.Value);
            parkingSpotCoordinates = parkingSpot.Value.Coordinates;
            return parkingSpot.Value.DCSID;
        }

19 View Source File : IEnumerableExtensions.cs
License : MIT License
Project Creator : aksoftware98

public static string AllInOne(this IEnumerable<string> values)
            => values.Aggregate((e1, e2) => $"{e1}{Environment.NewLine}{e2}");

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereIn<TEnreplacedy, TValue>
          (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, TValue>> selector,
            IEnumerable<TValue> values
          )
        {
            /*
             * 实现效果:
             * var names = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='A' OR Name='B' OR Name='C'
             * 实际上,可以直接这样:
             * var query = DbContext.User.Where(m => names.Contains(m.Name));
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            IEnumerable<Expression> equals = values.Select(value => (Expression)Expression.Equal(selector.Body, Expression.Constant(value, typeof(TValue))));
            Expression body = equals.Aggregate((acreplacedulate, equal) => Expression.Or(acreplacedulate, equal));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrCollectionAnyEqual<TEnreplacedy, TValue, TMemberValue>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, IEnumerable<TValue>>> selector,
            Expression<Func<TValue, TMemberValue>> memberSelector,
            IEnumerable<TMemberValue> values
            )
        {
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression selectorParameter = selector.Parameters.Single();
            ParameterExpression memberParameter = memberSelector.Parameters.Single();
            var methodInfo = GetEnumerableMethod("Any", 2).MakeGenericMethod(typeof(TValue));
            var anyExpressions = values.Select(value =>
                    (Expression)Expression.Call(null,
                                                methodInfo,
                                                selector.Body,
                                                Expression.Lambda<Func<TValue, bool>>(Expression.Equal(memberSelector.Body,
                                                                                                       Expression.Constant(value, typeof(TMemberValue))),
                                                                                                       memberParameter
                                                                                                       )
                                                )
                );
            Expression body = anyExpressions.Aggregate((acreplacedulate, any) => Expression.Or(acreplacedulate, any));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, selectorParameter));
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrStringContains<TEnreplacedy, String>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, String>> selector,
            IEnumerable<String> values
            )
        {
            /*
             * 实现效果:
             * var tags = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='Test' AND (Tags LIKE '%A%' Or Tags LIKE  '%B%')
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            var containsExpressions = values.Select(value => (Expression)Expression.Call(selector.Body, typeof(String).GetMethod("Contains", new[] { typeof(String) }), Expression.Constant(value)));
            Expression body = containsExpressions.Aggregate((acreplacedulate, containsExpression) => Expression.Or(acreplacedulate, containsExpression));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

19 View Source File : ValueObject.cs
License : MIT License
Project Creator : AleksandreJavakhishvili

public override int GetHashCode()
        {
            return GetAtomicValues()
             .Select(x => x != null ? x.GetHashCode() : 0)
             .Aggregate((x, y) => x ^ y);
        }

19 View Source File : ScopedStyle.cs
License : GNU General Public License v3.0
Project Creator : alexandrereyes

public string CssClreplacedesMixed(string nonScopedCssClreplacedes, params string[] scopedCssClreplacedes)
        {
            var cssClreplaced = new List<string>();

            if (!string.IsNullOrWhiteSpace(nonScopedCssClreplacedes))
                cssClreplaced.Add(nonScopedCssClreplacedes.Trim());

            cssClreplaced.AddRange(
                scopedCssClreplacedes
                    .Where(w => !string.IsNullOrWhiteSpace(w))
                    .Select(c => $"{c.Trim()}{Configuration.CssSelectorToReplace}".Replace(Configuration.CssSelectorToReplace, Id.ToString()))
            );

            return cssClreplaced.Aggregate((a, b) => $"{a} {b}");
        }

19 View Source File : State.cs
License : GNU General Public License v3.0
Project Creator : alexandrereyes

internal async Task<bool> InitializeComponent(ScopedStyle component, string embeddedCssPath, ComponentBase parent)
        {
            if (component.ReuseCss && component.Parent != null)
            {
                if (_renderedStyles.ContainsKey(component.Id))
                    return false;
            }

            if (!_cssBag.Styles.TryGetValue(embeddedCssPath, out string css))
            {
                if (parent != null)
                    embeddedCssPath = $"{parent.GetType().Namespace}.{embeddedCssPath}";

                if (!_cssBag.Styles.TryGetValue(embeddedCssPath, out css))
                {
                    throw new ArgumentException($"Embedded css path {embeddedCssPath} not found. Did you set the build action of the file as EmbeddedResource on Visual Studio?");
                }
            }

            _renderedStyles.Add(component.Id, css);

            await _jsInterop.InnerHTML(
                _configuration.StyleHtmlTagName,
                _renderedStyles
                    .Select(s => s.Value.Replace(_configuration.CssSelectorToReplace, s.Key.ToString()))
                    .Aggregate((a, b) => $"{a} {b}")
            );

            return true;
        }

19 View Source File : Message.cs
License : MIT License
Project Creator : alfa-laboratory

public static string CreateMessage(IEnumerable<string> list)
        {
            try
            {
                var enumerable = list as string[] ?? list.ToArray();
                if (enumerable.Any())
                {
                    var message = string.Empty;
                    message = enumerable.Aggregate((i, j) => i + Environment.NewLine + j);
                    return message;
                }

                Log.Logger().LogWarning("The IEnumerable<string> array contains no elements");
                return null;
            }
            catch(ArgumentNullException)
            {
                Log.Logger().LogWarning("No array was preplaceded to convert to string (null)");
                return null;
            }
            
        }

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : AlFasGD

public static string AggregateIfContains(this IEnumerable<string> strings, Func<string, string, string> aggregator) => strings.Count() > 0 ? strings.Aggregate(aggregator) : "";

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

static void Main(string[] args)
        {
            Random random = new Random();
            const int N = 1024 * 1024 * 32;
            int[] a = new int[N];
            for (int i = 0; i < N; ++i)
            {
                a[i] = (random.NextDouble() < 0.2) ? 1 : 0;
            }

            int[] result = new int[1];

            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);

            const int BLOCK_DIM = 256;
            HybRunner runner = HybRunner.Cuda().SetDistrib(16 * prop.multiProcessorCount, 1, BLOCK_DIM, 1, 1, BLOCK_DIM * sizeof(int));

            dynamic wrapped = runner.Wrap(new Program());

            wrapped.ReduceAdd(N, a, result);

            cuda.DeviceSynchronize();
            Console.Out.WriteLine("sum =      {0}", result[0]);
            Console.Out.WriteLine("expected = {0}", a.Aggregate((i, j) => i + j));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

static void Main(string[] args)
        {
            Random random = new Random();
            const int N = 1024 * 1024 * 32;
            int[] a = new int[N];
            for (int i = 0; i < N; ++i)
            {
                a[i] = (random.NextDouble() < 0.2) ? 1 : 0;
            }

            int[] result = new int[1];

            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);

            const int BLOCK_DIM = 256;
            HybRunner runner = HybRunner.Cuda().SetDistrib(16 * prop.multiProcessorCount, 1, BLOCK_DIM, 1, 1, BLOCK_DIM * sizeof(double));

            dynamic wrapped = runner.Wrap(new Program());

            wrapped.ReduceAdd(N, a, result);

            cuda.DeviceSynchronize();
            Console.Out.WriteLine("sum =      {0}", result[0]);
            Console.Out.WriteLine("expected = {0}", a.Aggregate((i, j) => i + j));
        }

19 View Source File : Entity.cs
License : MIT License
Project Creator : ambleside138

public override int GetHashCode()
        {
            return GetIdenreplacedyValues()
                .Select(x => x != null ? x.GetHashCode() : 0)
                .Aggregate((x, y) => x ^ y);
        }

19 View Source File : ValueObject.cs
License : MIT License
Project Creator : ambleside138

public override int GetHashCode()
        {
            return GetAtomicValues()
                .Select(x => x != null ? x.GetHashCode() : 0)
                .Aggregate((x, y) => x ^ y);
        }

19 View Source File : SasaraConfig.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public override string ToString() =>
            $"{nameof(this.Cast)}:{this.Cast}," +
            $"{nameof(this.Gain)}:{this.Gain}," +
            $"{nameof(this.Onryo)}:{this.Onryo}," +
            $"{nameof(this.Hayasa)}:{this.Hayasa}," +
            $"{nameof(this.Takasa)}:{this.Takasa}," +
            $"{nameof(this.Seireplacedu)}:{this.Seireplacedu}," +
            $"{nameof(this.Yokuyo)}:{this.Yokuyo}," +
            this.Components
                .Select(x => $"{x.Name}.{x.Id}:{x.Value}")
                .Aggregate((x, y) => $"{x},{y}");

19 View Source File : CevioAIConfig.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public override string ToString() =>
            $"CeVIO AI" +
            $"{nameof(this.Cast)}:{this.Cast}," +
            $"{nameof(this.Gain)}:{this.Gain}," +
            $"{nameof(this.Onryo)}:{this.Onryo}," +
            $"{nameof(this.Hayasa)}:{this.Hayasa}," +
            $"{nameof(this.Takasa)}:{this.Takasa}," +
            $"{nameof(this.Seireplacedu)}:{this.Seireplacedu}," +
            $"{nameof(this.Yokuyo)}:{this.Yokuyo}," +
            this.Components
                .Select(x => $"{x.Name}.{x.Id}:{x.Value}")
                .Aggregate((x, y) => $"{x},{y}");

19 View Source File : DatabaseConnectionFactory.cs
License : MIT License
Project Creator : ansel86castro

private string BuildUpsertQuery(string[] keys, string table, bool insertKeys, object args, Dictionary<string, string> onUpdateArgs = null, Dictionary<string, string> onInsertArgs = null)
            {
                if (_connection is not SqlConnection)
                    throw new InvalidOperationException("Merge is not supported for the current connection");

                var type = args.GetType();
                return _upsertCache.GetOrAdd($"{table}:{type.FullName}", _ =>
                {
                    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToList();

                    var argValues = string.Join(", ", props.Select(x => "@" + x));
                    var condition = keys.Select(k => $"Target.[{k}] = Source.[{k}]").Aggregate((x, y) => $"{x} AND {y}");

                    var columns = (insertKeys ? props : props.Except(keys)).Select(x => $"[{x}]").ToList();

                    var update = string.Join(", ", columns.Select(c => $"{c} = Source.{c}"));
                    var sourceColumns = string.Join(", ", columns.Select(c => $"Source.{c}"));

                    var onUpdate = onUpdateArgs?.Any() ?? false ? "," + string.Join(", ", onUpdateArgs.Select(x => $"[{x.Key}] = {x.Value}")) : "";
                    var onInsertColumns = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"[{x.Key}]")) : "";
                    var onInsertValues = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"{x.Value}")) : "";

                    var columnString = string.Join(",", columns);

                    var sql = [email protected]"
                MERGE {table} AS Target USING ( VALUES ({argValues})) 
                AS Source ({string.Join(",", props.Select(x => $"[{x}]"))})
                ON {condition}
                WHEN MATCHED THEN 
                UPDATE SET {update}{onUpdate}
                WHEN NOT MATCHED BY TARGET THEN 
                INSERT ({columnString}{onInsertColumns}) VALUES ( {sourceColumns}{onInsertValues})
                OUTPUT INSERTED.*;";

                    return sql;
                });
            }

19 View Source File : KHPCPatchManager.cs
License : Apache License 2.0
Project Creator : AntonioDePau

static void InitUI(){
		UpdateResources();
		GUI_Displayed = true;
		var handle = GetConsoleWindow();
		string defaultEpicFolder = @"C:\Program Files\Epic Games\KH_1.5_2.5\Image\en\";
		string epicFolder = defaultEpicFolder;
		string[] patchFiles = new string[]{};
		Form f = new Form();
		f.Icon = Icon.ExtractreplacedociatedIcon(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
		f.Size = new System.Drawing.Size(350, 300);
		f.Text = $"KHPCPatchManager {version}";
		f.MinimumSize = new System.Drawing.Size(350, 300);
		
		status.Text = "";
		f.Controls.Add(status);
		
		Label patch = new Label();
		patch.Text = "Patch: ";
		patch.AutoSize = true;
		f.Controls.Add(patch);
		
		f.Menu = new MainMenu();
		
		MenuItem item = new MenuItem("Options");
        f.Menu.MenuItems.Add(item);
		
		MenuItem backupOption = new MenuItem();
		backupOption.Text = "Backup PKG";
		backupOption.Checked = true;
		backupOption.Click += (s,e) => backupOption.Checked = !backupOption.Checked;
        item.MenuItems.AddRange(new MenuItem[]{backupOption});
		
		item = new MenuItem("?");
        f.Menu.MenuItems.Add(item);
		
		MenuItem helpOption = new MenuItem();
		helpOption.Text = "About";
		helpOption.Click += (s,e) => {
			Form f2 = new Form();
			f2.Text = "About - " + f.Text;
			f2.Size = new System.Drawing.Size(450, 370);
			f2.MinimumSize = new System.Drawing.Size(450, 370);
			f2.Icon = Icon.ExtractreplacedociatedIcon(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
			Color c = f2.BackColor;
			string rgb = c.R.ToString() + ", " + c.G.ToString() + ", " + c.B.ToString();
			WebBrowser wb = new WebBrowser();
			wb.Dock = DockStyle.Fill;
			wb.AutoSize = true;
			wb.Size = new Size(f2.Width, f2.Height);
			wb.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom;
			wb.DoreplacedentText = "<html style='font-family:calibri;overflow:hidden;width:97%;background-color: rgb(" + rgb + @")'><div style='width:100%;text-align:center;'>
					Tool made by <b>AntonioDePau</b><br>
					Thanks to:<br>
					<ul style='text-align:left'>
						<li><a href='https://github.com/Noxalus/OpenKh/tree/feature/egs-hed-packer'>Noxalus</a></li>
						<li><a href='https://twitter.com/xeeynamo'>Xeeynamo</a> and the whole <a href='https://github.com/Xeeynamo/OpenKh'>OpenKH</a> team</li>
						<li>DemonBoy (aka: DA) for making custom HD replacedets for custom MDLX files possible</li>
						<li><a href='https://twitter.com/tieulink'>TieuLink</a> for extensive testing and help in debugging</li>
					</ul>
					Source code: <a href='https://github.com/AntonioDePau/KHPCPatchManager'>GitHub</a><br>
					Report bugs: <a href='https://github.com/AntonioDePau/KHPCPatchManager/issues'>GitHub</a><br>
					<br>
					<b>Note:</b> <i>For some issues, you may want to contact the patch's author instead of me!</i>
				</div>
				</html>";
			wb.Navigating += (s,e) => {
				e.Cancel = true;
				Process.Start(e.Url.ToString());
			};
			f2.Controls.Add(wb);
			
			f2.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
			f2.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			f2.ResumeLayout(false);
			f2.ShowDialog();
		};
        item.MenuItems.AddRange(new MenuItem[]{helpOption});
		
		selPatchButton.Text = "Select patch";
		f.Controls.Add(selPatchButton);
		
		selPatchButton.Location = new Point(
			f.ClientSize.Width / 2 - selPatchButton.Size.Width / 2, 25);
		selPatchButton.Anchor = AnchorStyles.Top;
		
		selPatchButton.Click += (s,e) => {
			using(OpenFileDialog openFileDialog = new OpenFileDialog()){
				openFileDialog.InitialDirectory = Directory.GetCurrentDirectory();
				openFileDialog.Filter = "KH pcpatch files (*.*pcpatch)|*.*pcpatch|All files (*.*)|*.*";
				openFileDialog.RestoreDirectory = true;
				openFileDialog.Multiselect = true;
				if(openFileDialog.ShowDialog() == DialogResult.OK){
					//Get the path of specified file
					//MessageBox.Show(openFileDialog.FileName);
					patchFiles = openFileDialog.FileNames;
					for(int i=0;i<patchFiles.Length;i++){
						string ext = Path.GetExtension(patchFiles[i]).Replace("pcpatch", "").Replace(".","");
						patchType.Add(ext.ToUpper());
					}
					if(patchType.Distinct().ToList().Count == 1){
						if(patchFiles.Length>1){
							patchFiles = ReorderPatches(patchFiles);
						}
						patch.Text = "Patch" + (patchFiles.Length>1?"es: " + patchFiles.Aggregate((x, y) => Path.GetFileNameWithoutExtension(x) + ", " + Path.GetFileNameWithoutExtension(y)):": " + Path.GetFileNameWithoutExtension(patchFiles[0]));
						applyPatchButton.Enabled = true;
					}else{
						MessageBox.Show(multiplePatchTypesSelected + ":\n" + patchType.Aggregate((x, y) => x + ", " + y));
						applyPatchButton.Enabled = false;
					}
				}
			}
		};
		
		applyPatchButton.Text = "Apply patch";
		f.Controls.Add(applyPatchButton);
		
		applyPatchButton.Location = new Point(
			f.ClientSize.Width / 2 - applyPatchButton.Size.Width / 2, 50);
		applyPatchButton.Anchor = AnchorStyles.Top;
		applyPatchButton.Enabled = false;
		
		applyPatchButton.Click += (s,e) => {
			if(!Directory.Exists(epicFolder) || patchType[0] == "DDD"){ 
				using(FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()){
					folderBrowserDialog.Description = "Could not find the installation path for Kingdom Hearts on this PC!\nPlease browse for the \"Epic Games\\KH_1.5_2.5\" (or \"2.8\" for DDD) folder.";
					if(folderBrowserDialog.ShowDialog() == DialogResult.OK){
						string temp = Path.Combine(folderBrowserDialog.SelectedPath, "Image\\en");
						if(Directory.Exists(temp)){
							epicFolder = temp;
							selPatchButton.Enabled = false;
							applyPatchButton.Enabled = false;
							backupOption.Enabled = false;
							ApplyPatch(patchFiles.ToList(), patchType[0], epicFolder, backupOption.Checked);
						}else{
							MessageBox.Show("Could not find \"\\Image\\en\" in the provided folder!\nPlease try again by selecting the correct folder.");
						}
					}
				}
			}else{
				selPatchButton.Enabled = false;
				applyPatchButton.Enabled = false;
				backupOption.Enabled = false;
				ApplyPatch(patchFiles.ToList(), patchType[0], epicFolder, backupOption.Checked);
			}
		};
		f.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
		f.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
		f.ResumeLayout(false);
		ShowWindow(handle, SW_HIDE);
		f.ShowDialog();
	}

19 View Source File : Widget.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public void Rereplacedessment() => Status = Count > 0 ? this.Where(w => w.IsEnabled).Aggregate((a, b) => a.Status?.Description?.Priority < b.Status?.Description?.Priority ? a : b)?.Status : Status.None;

19 View Source File : H5Utils.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

public static ulong CalculateSize(IEnumerable<ulong> dimensionSizes, DataspaceType type = DataspaceType.Simple)
        {
            switch (type)
            {
                case DataspaceType.Scalar:
                    return 1;

                case DataspaceType.Simple:

                    var totalSize = 0UL;

                    if (dimensionSizes.Any())
                        totalSize = dimensionSizes.Aggregate((x, y) => x * y);

                    return totalSize;

                case DataspaceType.Null:
                    return 0;

                default:
                    throw new Exception($"The dataspace type '{type}' is not supported.");
            }
        }

19 View Source File : Pattern.cs
License : MIT License
Project Creator : Aptacode

public override int GetHashCode()
        {
            return HashedElements
                .Select(item => item.GetHashCode())
                .Aggregate((total, nextCode) => total ^ nextCode);
        }

19 View Source File : DesignIirFilter.cs
License : MIT License
Project Creator : ar1st0crat

public static TransferFunction SosToTf(TransferFunction[] sos)
        {
            return sos.Aggregate((tf, s) => tf * s);
        }

19 View Source File : MergeStrategyStub.cs
License : Apache License 2.0
Project Creator : Arasz

public GitignoreFile Merge(IReadOnlyCollection<GitignoreFile> gitignoreFiles)
        {
            var mergedContent = gitignoreFiles
               .Select(file => file.Content)
               .Aggregate((content, acreplaced) => acreplaced + content);

            return new GitignoreFile("MERGED", mergedContent);
        }

19 View Source File : TemplateProject.cs
License : MIT License
Project Creator : arcus-azure

protected string RemovesUserErrorsFromContents(string content)
        {
            return content.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
                          .Where(line => !line.Contains("#error"))
                          .Aggregate((line1, line2) => line1 + Environment.NewLine + line2);
        }

19 View Source File : WebApiProjectOptions.cs
License : MIT License
Project Creator : arcus-azure

private static string RemoveCustomUserErrors(string content)
        {
            return content.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
                          .Where(line => !line.Contains("#error"))
                          .Aggregate((line1, line2) => line1 + Environment.NewLine + line2);
        }

19 View Source File : ValueObject.cs
License : MIT License
Project Creator : ARKlab

public override int GetHashCode()
        {
            return GetAtomicValues()
                 .Select(x => x?.GetHashCode() ?? 0)
                 .Aggregate((x, y) => x ^ y);
        }

See More Examples