Exemplo n.º 1
0
        public AlmostEverywhereProtocol(AsyncParty e, ReadOnlyCollection<int> processorIds, SafeRandom randGen, StateKey stateKey)
            : base(e, processorIds, stateKey)
        {
            if (randGen == null)
                randUtils = new RandomUtils();
            else
                randUtils = new RandomUtils(randGen);

            var cStr = ConfigurationManager.AppSettings["SampleListSizeFactor"];
            C = cStr == null ? 1 : float.Parse(cStr);
        }
Exemplo n.º 2
0
        protected override void CompleteRangeAttack(IList <object> data)
        {
            MapObject   target  = (MapObject)data[0];
            int         damage  = (int)data[1];
            DefenceType defence = (DefenceType)data[2];

            if (target == null || !target.IsAttackTarget(this) || target.CurrentMap != CurrentMap || target.Node == null)
            {
                return;
            }
            //减速
            if (target.Attacked(this, damage, defence) <= 0)
            {
                return;
            }
            if (RandomUtils.Next(Settings.PoisonResistWeight) >= target.PoisonResist && RandomUtils.Next(3) == 1)
            {
                target.ApplyPoison(new Poison {
                    Owner = this, Duration = RandomUtils.Next(3, 8), PType = PoisonType.Slow, Value = damage, TickSpeed = 2000
                }, this);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 刷新日常任务,当天的记录不清空
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="userTask"></param>
        /// <returns></returns>
        public static List <UserTask> RefreshDailyTask(string userID, UserTask userTask)
        {
            List <UserTask> userTaskList = new GameDataCacheSet <UserTask>().FindAll(userID, m => !m.TaskState.Equals(TaskState.Disable) && m.TaskType.Equals(TaskType.Daily));

            foreach (UserTask userTaskTemp in userTaskList)
            {
                //关掉任务
                userTaskTemp.TaskState = TaskState.Disable;
                //userTaskTemp.Update();
            }

            TaskStar taskStar = TaskStar.Star1;

            if (userTask != null)
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Monday && userTask.CreateDate.Date < DateTime.Now.Date)
                {
                    taskStar = TaskStar.Star1;
                }
                else
                {
                    taskStar = GetTaskStar(userTask.TaskStar, userTask.TakeDate);
                }
            }

            DailyTaskInfo[] dtaskList = RandomUtils.GetRandomArray(new ConfigCacheSet <DailyTaskInfo>().FindAll().ToArray(), DailyMaxCount);
            foreach (DailyTaskInfo item in dtaskList)
            {
                UserTask tempTask = new GameDataCacheSet <UserTask>().FindKey(userID, item.TaskID);
                if (tempTask == null)
                {
                    tempTask = new UserTask
                    {
                        UserID        = userID,
                        TaskID        = item.TaskID,
                        TaskType      = item.TaskType,
                        TaskStar      = taskStar,
                        TaskState     = TaskState.AllowTake,
                        TaskTargetNum = "0",
                        CompleteNum   = 0,
                        CreateDate    = DateTime.Now
                    };
                    new GameDataCacheSet <UserTask>().Add(tempTask, GameEnvironment.CacheUserPeriod);
                }
                else
                {
                    tempTask.TaskStar      = taskStar;
                    tempTask.TaskState     = TaskState.AllowTake;
                    tempTask.TaskTargetNum = "0";
                    if (!tempTask.CreateDate.Date.Equals(DateTime.Now.Date))
                    {
                        tempTask.CompleteNum = 0;
                    }
                    tempTask.CreateDate = DateTime.Now;
                }
            }

            return(new GameDataCacheSet <UserTask>().FindAll(userID,
                                                             m => m.TaskType.Equals(TaskType.Daily) &&
                                                             (m.TaskState.Equals(TaskState.Taked) || m.TaskState.Equals(TaskState.AllowTake) || m.TaskState.Equals(TaskState.Completed)) &&
                                                             m.CreateDate.Date.Equals(DateTime.Now.Date)
                                                             ));
        }
Exemplo n.º 4
0
        public async Task <InvoiceEntity> CreateInvoiceAsync(string storeId, InvoiceEntity invoice, string[] additionalSearchTerms = null)
        {
            var textSearch = new HashSet <string>();

            invoice          = Clone(invoice);
            invoice.Networks = _btcPayNetworkProvider;
            invoice.Id       = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16));
#pragma warning disable CS0618
            invoice.Payments = new List <PaymentEntity>();
#pragma warning restore CS0618
            invoice.StoreId = storeId;
            using (var context = _applicationDbContextFactory.CreateContext())
            {
                var invoiceData = new Data.InvoiceData()
                {
                    StoreDataId = storeId,
                    Id          = invoice.Id,
                    Created     = invoice.InvoiceTime,
                    Blob        = ToBytes(invoice, null),
                    OrderId     = invoice.Metadata.OrderId,
#pragma warning disable CS0618 // Type or member is obsolete
                    Status = invoice.StatusString,
#pragma warning restore CS0618 // Type or member is obsolete
                    ItemCode      = invoice.Metadata.ItemCode,
                    CustomerEmail = invoice.RefundMail,
                    Archived      = false
                };
                await context.Invoices.AddAsync(invoiceData);


                foreach (var paymentMethod in invoice.GetPaymentMethods())
                {
                    if (paymentMethod.Network == null)
                    {
                        throw new InvalidOperationException("CryptoCode unsupported");
                    }
                    var details = paymentMethod.GetPaymentMethodDetails();
                    if (!details.Activated)
                    {
                        continue;
                    }
                    var    paymentDestination = details.GetPaymentDestination();
                    string address            = GetDestination(paymentMethod);
                    await context.AddressInvoices.AddAsync(new AddressInvoiceData()
                    {
                        InvoiceDataId = invoice.Id,
                        CreatedTime   = DateTimeOffset.UtcNow,
                    }.Set(address, paymentMethod.GetId()));

                    await context.HistoricalAddressInvoices.AddAsync(new HistoricalAddressInvoiceData()
                    {
                        InvoiceDataId = invoice.Id,
                        Assigned      = DateTimeOffset.UtcNow
                    }.SetAddress(paymentDestination, paymentMethod.GetId().ToString()));

                    textSearch.Add(paymentDestination);
                    textSearch.Add(paymentMethod.Calculate().TotalDue.ToString());
                }
                await context.PendingInvoices.AddAsync(new PendingInvoiceData()
                {
                    Id = invoice.Id
                });

                textSearch.Add(invoice.Id);
                textSearch.Add(invoice.InvoiceTime.ToString(CultureInfo.InvariantCulture));
                if (!invoice.IsUnsetTopUp())
                {
                    textSearch.Add(invoice.Price.ToString(CultureInfo.InvariantCulture));
                }
                textSearch.Add(invoice.Metadata.OrderId);
                textSearch.Add(invoice.StoreId);
                textSearch.Add(invoice.Metadata.BuyerEmail);

                if (additionalSearchTerms != null)
                {
                    textSearch.AddRange(additionalSearchTerms);
                }
                AddToTextSearch(context, invoiceData, textSearch.ToArray());

                await context.SaveChangesAsync().ConfigureAwait(false);
            }


            return(invoice);
        }
Exemplo n.º 5
0
 public override int Next(int maxValue)
 {
     return((int)(RandomUtils.GetUInt32() % maxValue));
 }
Exemplo n.º 6
0
        public static async Task <CoreNode> CreateAsync(CoreNodeParams coreNodeParams, CancellationToken cancel)
        {
            Guard.NotNull(nameof(coreNodeParams), coreNodeParams);
            using (BenchmarkLogger.Measure())
            {
                var coreNode = new CoreNode();
                coreNode.HostedServices = coreNodeParams.HostedServices;
                coreNode.DataDir        = coreNodeParams.DataDir;
                coreNode.Network        = coreNodeParams.Network;
                coreNode.MempoolService = coreNodeParams.MempoolService;

                var configPath = Path.Combine(coreNode.DataDir, "bitcoin.conf");
                coreNode.Config = new CoreConfig();
                if (File.Exists(configPath))
                {
                    var configString = await File.ReadAllTextAsync(configPath).ConfigureAwait(false);

                    coreNode.Config.AddOrUpdate(configString);                     // Bitcoin Core considers the last entry to be valid.
                }
                cancel.ThrowIfCancellationRequested();

                var configTranslator = new CoreConfigTranslator(coreNode.Config, coreNode.Network);

                string    rpcUser           = configTranslator.TryGetRpcUser();
                string    rpcPassword       = configTranslator.TryGetRpcPassword();
                string    rpcCookieFilePath = configTranslator.TryGetRpcCookieFile();
                string    rpcHost           = configTranslator.TryGetRpcBind();
                int?      rpcPort           = configTranslator.TryGetRpcPort();
                WhiteBind whiteBind         = configTranslator.TryGetWhiteBind();

                string authString;
                bool   cookieAuth = rpcCookieFilePath is { };
                if (cookieAuth)
                {
                    authString = $"cookiefile={rpcCookieFilePath}";
                }
                else
                {
                    rpcUser ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21));
                    rpcPassword ??= Encoders.Hex.EncodeData(RandomUtils.GetBytes(21));
                    authString = $"{rpcUser}:{rpcPassword}";
                }

                coreNode.P2pEndPoint = whiteBind?.EndPoint ?? coreNodeParams.P2pEndPointStrategy.EndPoint;
                rpcHost ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetHostOrDefault();
                rpcPort ??= coreNodeParams.RpcEndPointStrategy.EndPoint.GetPortOrDefault();
                EndPointParser.TryParse($"{rpcHost}:{rpcPort}", coreNode.Network.RPCPort, out EndPoint rpce);
                coreNode.RpcEndPoint = rpce;

                var rpcClient = new RPCClient($"{authString}", coreNode.RpcEndPoint.ToString(coreNode.Network.DefaultPort), coreNode.Network);
                coreNode.RpcClient = new RpcClientBase(rpcClient);


                if (coreNodeParams.TryRestart)
                {
                    await coreNode.TryStopAsync(false).ConfigureAwait(false);
                }
                cancel.ThrowIfCancellationRequested();

                if (coreNodeParams.TryDeleteDataDir)
                {
                    await IoHelpers.DeleteRecursivelyWithMagicDustAsync(coreNode.DataDir).ConfigureAwait(false);
                }
                cancel.ThrowIfCancellationRequested();

                IoHelpers.EnsureDirectoryExists(coreNode.DataDir);

                var configPrefix             = NetworkTranslator.GetConfigPrefix(coreNode.Network);
                var whiteBindPermissionsPart = !string.IsNullOrWhiteSpace(whiteBind?.Permissions) ? $"{whiteBind?.Permissions}@" : "";
                var desiredConfigLines       = new List <string>()
                {
                    $"{configPrefix}.server			= 1",
                    $"{configPrefix}.listen			= 1",
                    $"{configPrefix}.whitebind		= {whiteBindPermissionsPart}{coreNode.P2pEndPoint.ToString(coreNode.Network.DefaultPort)}",
                    $"{configPrefix}.rpcbind		= {coreNode.RpcEndPoint.GetHostOrDefault()}",
                    $"{configPrefix}.rpcallowip		= {IPAddress.Loopback}",
                    $"{configPrefix}.rpcport		= {coreNode.RpcEndPoint.GetPortOrDefault()}"
                };

                if (!cookieAuth)
                {
                    desiredConfigLines.Add($"{configPrefix}.rpcuser		= {coreNode.RpcClient.CredentialString.UserPassword.UserName}");
                    desiredConfigLines.Add($"{configPrefix}.rpcpassword	= {coreNode.RpcClient.CredentialString.UserPassword.Password}");
                }

                if (coreNodeParams.TxIndex is { })
Exemplo n.º 7
0
 /// <summary>
 /// 重新生成Id
 /// </summary>
 public static void ReGenerateId(this Session session)
 {
     session.Id = RandomUtils.SystemRandomBytes(20).ToHex();
 }
Exemplo n.º 8
0
        /// <summary>
        /// 奖励配置
        /// </summary>
        /// <param name="user"></param>
        /// <param name="status">状态值为1时,下发图片</param>
        public static string GetUserTake(List <PrizeInfo> prizeInfoList, string userID, int status = 0)
        {
            string           HeadID    = string.Empty;
            int              quality   = 0;
            List <PrizeInfo> prizeList = new List <PrizeInfo>();
            var              prize     = prizeInfoList[0];
            string           content   = string.Empty;

            switch (prize.Reward)
            {
            //随机
            case 1:
                if (prizeInfoList.Count > 0)
                {
                    int randomNum = RandomUtils.GetRandom(0, prizeInfoList.Count);
                    prizeList.Add(prizeInfoList[randomNum]);
                }

                break;

            //概率
            case 2:
                int   count   = prizeInfoList.Count;
                int[] precent = new int[count];
                for (int i = 0; i < count; i++)
                {
                    var prize2 = prizeInfoList[i];
                    precent[i] = (prize2.Probability * 1000).ToInt();
                }
                int index = RandomUtils.GetHitIndexByTH(precent);
                prizeList.Add(prizeInfoList[index]);
                break;

            //全部
            case 3:
                prizeList.AddRange(prizeInfoList);
                break;
            }
            prizeList.ForEach(prizeInfo =>
            {
                var cacheSetUser = new PersonalCacheStruct <GameUser>();
                var user         = cacheSetUser.FindKey(userID);

                if (user != null)
                {
                    switch (prizeInfo.Type)
                    {
                    case RewardType.GameGoin:
                        //content += string.Format(LanguageManager.GetLang().St_GameCoin, prizeInfo.Num) + ",";
                        //user.GameCoin = MathUtils.Addition(user.GameCoin, prizeInfo.Num);
                        HeadID = prizeInfo.HeadID;
                        // 1: 乘玩家等级
                        if (prizeInfo.IsMultiplyUserLv == 1)
                        {
                            int coinNumber = 0;
                            // 获取当前玩家等级
                            if (user.UserLv >= 1 && user.UserLv <= 100)
                            {
                                coinNumber = prizeInfo.Num * user.UserLv;
                            }

                            else if (user.UserLv < 1)
                            {
                                coinNumber = prizeInfo.Num * 1;
                            }
                            else
                            {
                                coinNumber = prizeInfo.Num * 100;
                            }
                            content      += string.Format(LanguageManager.GetLang().St_GameCoin, coinNumber) + ",";
                            user.GameCoin = MathUtils.Addition(user.GameCoin, coinNumber);
                        }
                        else
                        {
                            content      += string.Format(LanguageManager.GetLang().St_GameCoin, prizeInfo.Num) + ",";
                            user.GameCoin = MathUtils.Addition(user.GameCoin, prizeInfo.Num);
                        }
                        break;

                    case RewardType.Gold:
                        HeadID        = prizeInfo.HeadID;
                        content      += string.Format(LanguageManager.GetLang().St_GiftGoldNum, prizeInfo.Num) + ",";
                        user.GiftGold = MathUtils.Addition(user.GiftGold, prizeInfo.Num);
                        break;

                    case RewardType.EnergyNum:
                        content       += string.Format(LanguageManager.GetLang().St_EnergyNum, prizeInfo.Num) + ",";
                        user.EnergyNum = MathUtils.Addition(user.EnergyNum, prizeInfo.Num).ToShort();
                        break;

                    case RewardType.ExpNum:
                        content    += string.Format(LanguageManager.GetLang().St_ExpNum, prizeInfo.Num) + ",";
                        user.ExpNum = MathUtils.Addition(user.ExpNum, prizeInfo.Num);
                        break;

                    case RewardType.Experience:
                        content += string.Format(LanguageManager.GetLang().St_Experience, prizeInfo.Num) + ",";
                        GeneralEscalateHelper.AddUserLv(user, prizeInfo.Num);
                        break;

                    case RewardType.CrystalId:
                        var crystalInfo = new ShareCacheStruct <CrystalInfo>().FindKey(prizeInfo.ItemID);
                        if (crystalInfo != null)
                        {
                            //content += string.Format(LanguageManager.GetLang().St_Crystal, crystalInfo.CrystalName) + ",";
                            content += crystalInfo.CrystalName + ",";
                            CrystalHelper.AppendCrystal(user.UserID, crystalInfo.CrystalID, prizeInfo.UserLv);
                        }
                        break;

                    case RewardType.Item:
                        var itemInfo = new ShareCacheStruct <ItemBaseInfo>().FindKey(prizeInfo.ItemID);
                        if (itemInfo != null)
                        {
                            //content += string.Format(LanguageManager.GetLang().St_Item, itemInfo.ItemName,  prizeInfo.Num) + ",";
                            //UserItemHelper.AddUserItem(user.UserID, prizeInfo.ItemID, prizeInfo.Num, prizeInfo.UserLv);
                            if (status == 1)
                            {
                                HeadID   = prizeInfo.HeadID;
                                content += string.Format(LanguageManager.GetLang().St_ItemReward, itemInfo.ItemName, prizeInfo.Num) + ",";
                                UserItemHelper.AddUserItem(user.UserID, prizeInfo.ItemID, prizeInfo.Num, prizeInfo.UserLv);
                            }
                            else
                            {
                                content += string.Format(LanguageManager.GetLang().St_Item, itemInfo.ItemName, prizeInfo.UserLv, prizeInfo.Num) + ",";
                                UserItemHelper.AddUserItem(user.UserID, prizeInfo.ItemID, prizeInfo.Num, prizeInfo.UserLv);
                            }
                        }
                        break;

                    case RewardType.MonsterCard:
                        //  获取 JSON 中的怪物记录
                        var monsterCard = prizeInfoList.Find(s => s.Type == RewardType.MonsterCard);

                        var userPlotInfo = new PersonalCacheStruct <UserPlotPackage>().FindKey(user.UserID);
                        if (userPlotInfo != null)
                        {
                            List <PlotNPCInfo> plotNpcInfoList = new List <PlotNPCInfo>();
                            var userPlotPackageList            = userPlotInfo.PlotPackage.FindAll(x => x.PlotStatus == PlotStatus.Completed);
                            // PlotID
                            if (userPlotPackageList.Count > 0)
                            {
                                userPlotPackageList.ForEach(userPlot =>
                                {
                                    var plotNPCInfo = new ShareCacheStruct <PlotNPCInfo>().Find(x => x.PlotID == userPlot.PlotID);
                                    if (plotNPCInfo != null)
                                    {
                                        plotNpcInfoList.Add(plotNPCInfo);
                                    }
                                });
                                if (plotNpcInfoList.Count > 0)
                                {
                                    int index     = RandomUtils.GetRandom(0, plotNpcInfoList.Count);
                                    int plotNpcID = plotNpcInfoList[index].PlotNpcID;

                                    var plotEmbattleInfo = new ShareCacheStruct <PlotEmbattleInfo>().Find(x => x.PlotNpcID == plotNpcID);

                                    if (plotEmbattleInfo != null)
                                    {
                                        var monsterInfo = new ShareCacheStruct <MonsterInfo>().FindKey(plotEmbattleInfo.MonsterID);
                                        if (monsterInfo != null)
                                        {
                                            var itemMonster = new ShareCacheStruct <ItemBaseInfo>().FindKey(monsterInfo.ItemID);
                                            HeadID          = itemMonster.HeadID;

                                            content += string.Format(LanguageManager.GetLang().St_MonsterCard, itemMonster.ItemName,
                                                                     prizeInfo.Num) + ",";
                                            UserItemHelper.AddUserItem(user.UserID, monsterInfo.ItemID, prizeInfo.Num, prizeInfo.UserLv);
                                        }
                                    }
                                }
                            }
                            #region 注释
                            //else
                            //{
                            //    // 副本没有通关默认奖励为第一种金币奖励
                            //    HeadID = prize.HeadID;
                            //    int coinNumber = prize.Num;  // 第一条记录中金币数
                            //    // 获取当前玩家等级
                            //    if (user.UserLv >= 1 && user.UserLv <= 100)
                            //    {
                            //        coinNumber = coinNumber * user.UserLv;
                            //    }

                            //    else if (user.UserLv < 1)
                            //    {
                            //        coinNumber = coinNumber * 1;
                            //    }
                            //    else
                            //    {
                            //        coinNumber = coinNumber * 100;
                            //    }
                            //    content += string.Format(LanguageManager.GetLang().St_GameCoin, coinNumber) + ",";
                            //    user.GameCoin = MathUtils.Addition(user.GameCoin, coinNumber);
                            //}
                            #endregion
                        }

                        break;

                    case RewardType.GeneralSoul:
                        var generalInfoList = new ShareCacheStruct <GeneralInfo>().FindAll(x => x.GeneralQuality == prizeInfo.GeneralQuality);
                        if (generalInfoList != null)
                        {
                            if (generalInfoList.Count > 0)
                            {
                                int index = RandomUtils.GetRandom(0, generalInfoList.Count);
                                GeneralInfo generalInfo = generalInfoList[index];
                                HeadID   = generalInfo.HeadID;
                                quality  = generalInfo.GeneralQuality.ToInt();
                                content += string.Format(LanguageManager.GetLang().St_GeneralSoul,
                                                         generalInfo.GeneralName, prizeInfo.Num) + ",";
                                UserItemHelper.AddGeneralSoul(user.UserID, generalInfo.SoulID, prizeInfo.Num);
                            }
                        }
                        break;

                    case RewardType.Ability:
                        // 查找绿色技能列表
                        var abilityInfoList = new ShareCacheStruct <AbilityInfo>().FindAll(x => x.AbilityQuality == prizeInfo.AbilityQuality);
                        if (abilityInfoList != null)
                        {
                            if (abilityInfoList.Count > 0)
                            {
                                int index = RandomUtils.GetRandom(0, abilityInfoList.Count);
                                AbilityInfo abilityInfo = abilityInfoList[index];
                                HeadID   = abilityInfo.HeadID;
                                quality  = abilityInfo.AbilityQuality;
                                content += string.Format(LanguageManager.GetLang().St_Ability, abilityInfo.AbilityName, prizeInfo.Num) + ",";
                                UserAbilityHelper.AddUserAbility(abilityInfo.AbilityID, Convert.ToInt32(user.UserID), 0, 0);
                            }
                        }
                        break;
                    }
                }
                // 状态值为1时下发图片
                if (status == 1)
                {
                    #region  如果奖励为空,则默认奖励金币

                    string[] rewardInfo = content.TrimEnd(',').Split('*');
                    if (String.IsNullOrEmpty(rewardInfo[0]))
                    {
                        // 默认奖励为第一种金币奖励
                        HeadID         = prize.HeadID;
                        int coinNumber = prize.Num;  // 第一条记录中金币数
                        // 获取当前玩家等级
                        if (user.UserLv >= 1 && user.UserLv <= 100)
                        {
                            coinNumber = coinNumber * user.UserLv;
                        }

                        else if (user.UserLv < 1)
                        {
                            coinNumber = coinNumber * 1;
                        }
                        else
                        {
                            coinNumber = coinNumber * 100;
                        }
                        content      += string.Format(LanguageManager.GetLang().St_GameCoin, coinNumber) + ",";
                        user.GameCoin = MathUtils.Addition(user.GameCoin, coinNumber);
                    }

                    #endregion
                    content = content.TrimEnd(',') + "*" + HeadID + "*" + quality + ",";
                }
            });
            content = content.TrimEnd(',');

            return(content);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Generates random key. Used internally and can be used to generate key for manual Encrypt() calls.
 /// </summary>
 /// <returns>Key suitable for manual Encrypt() calls.</returns>
 public static byte GenerateKey()
 {
     return(RandomUtils.GenerateByteKey());
 }
Exemplo n.º 10
0
 public void BeforeEachTest()
 {
     this.randomUtils = new RandomUtils();
 }
Exemplo n.º 11
0
        GetImportanceMetricsMatrix(
            IHostEnvironment env,
            IPredictionTransformer <IPredictor> model,
            IDataView data,
            Func <IDataView, TMetric> evaluationFunc,
            Func <TMetric, TMetric, TMetric> deltaFunc,
            string features,
            int permutationCount,
            bool useFeatureWeightFilter = false,
            int?topExamples             = null)
        {
            Contracts.CheckValue(env, nameof(env));
            var host = env.Register(nameof(PermutationFeatureImportance <TMetric, TResult>));

            host.CheckValue(model, nameof(model));
            host.CheckValue(data, nameof(data));
            host.CheckNonEmpty(features, nameof(features));

            topExamples = topExamples ?? Utils.ArrayMaxSize;
            host.Check(topExamples > 0, "Provide how many examples to use (positive number) or set to null to use whole dataset.");

            VBuffer <ReadOnlyMemory <char> > slotNames = default;
            var metricsDelta = new List <TResult>();

            using (var ch = host.Start("GetImportanceMetrics"))
            {
                ch.Trace("Scoring and evaluating baseline.");
                var baselineMetrics = evaluationFunc(model.Transform(data));

                // Get slot names.
                var featuresColumn = data.Schema[features];
                int numSlots       = featuresColumn.Type.VectorSize;
                data.Schema.TryGetColumnIndex(features, out int featuresColumnIndex);

                ch.Info("Number of slots: " + numSlots);
                if (data.Schema[featuresColumnIndex].HasSlotNames(numSlots))
                {
                    data.Schema[featuresColumnIndex].Metadata.GetValue(MetadataUtils.Kinds.SlotNames, ref slotNames);
                }

                if (slotNames.Length != numSlots)
                {
                    slotNames = VBufferUtils.CreateEmpty <ReadOnlyMemory <char> >(numSlots);
                }

                VBuffer <float> weights = default;
                var             workingFeatureIndices = Enumerable.Range(0, numSlots).ToList();
                int             zeroWeightsCount      = 0;

                // By default set to the number of all features available.
                var evaluatedFeaturesCount = numSlots;
                if (useFeatureWeightFilter)
                {
                    var predictorWithWeights = model.Model as IPredictorWithFeatureWeights <Single>;
                    if (predictorWithWeights != null)
                    {
                        predictorWithWeights.GetFeatureWeights(ref weights);

                        const int     maxReportedZeroFeatures = 10;
                        StringBuilder msgFilteredOutFeatures  = new StringBuilder("The following features have zero weight and will not be evaluated: \n \t");
                        var           prefix = "";
                        foreach (var k in weights.Items(all: true))
                        {
                            if (k.Value == 0)
                            {
                                zeroWeightsCount++;

                                // Print info about first few features we're not going to evaluate.
                                if (zeroWeightsCount <= maxReportedZeroFeatures)
                                {
                                    msgFilteredOutFeatures.Append(prefix);
                                    msgFilteredOutFeatures.Append(GetSlotName(slotNames, k.Key));
                                    prefix = ", ";
                                }
                            }
                            else
                            {
                                workingFeatureIndices.Add(k.Key);
                            }
                        }

                        // Old FastTree models has less weights than slots.
                        if (weights.Length < numSlots)
                        {
                            ch.Warning(
                                "Predictor had fewer features than slots. All unknown features will get default 0 weight.");
                            zeroWeightsCount += numSlots - weights.Length;
                            var indexes = weights.GetIndices().ToArray();
                            var values  = weights.GetValues().ToArray();
                            var count   = values.Length;
                            weights = new VBuffer <float>(numSlots, count, values, indexes);
                        }

                        evaluatedFeaturesCount = workingFeatureIndices.Count;
                        ch.Info("Number of zero weights: {0} out of {1}.", zeroWeightsCount, weights.Length);

                        // Print what features have 0 weight
                        if (zeroWeightsCount > 0)
                        {
                            if (zeroWeightsCount > maxReportedZeroFeatures)
                            {
                                msgFilteredOutFeatures.Append(string.Format("... (printing out  {0} features here).\n Use 'Index' column in the report for info on what features are not evaluated.", maxReportedZeroFeatures));
                            }
                            ch.Info(msgFilteredOutFeatures.ToString());
                        }
                    }
                }

                if (workingFeatureIndices.Count == 0 && zeroWeightsCount == 0)
                {
                    // Use all features otherwise.
                    workingFeatureIndices.AddRange(Enumerable.Range(0, numSlots));
                }

                if (zeroWeightsCount == numSlots)
                {
                    ch.Warning("All features have 0 weight thus can not do thorough evaluation");
                    return(metricsDelta.ToImmutableArray());
                }

                // Note: this will not work on the huge dataset.
                var          maxSize = topExamples;
                List <float> initialfeatureValuesList = new List <float>();

                // Cursor through the data to cache slot 0 values for the upcoming permutation.
                var valuesRowCount = 0;
                // REVIEW: Seems like if the labels are NaN, so that all metrics are NaN, this command will be useless.
                // In which case probably erroring out is probably the most useful thing.
                using (var cursor = data.GetRowCursor(col => col == featuresColumnIndex))
                {
                    var featuresGetter = cursor.GetGetter <VBuffer <float> >(featuresColumnIndex);
                    var featuresBuffer = default(VBuffer <float>);

                    while (initialfeatureValuesList.Count < maxSize && cursor.MoveNext())
                    {
                        featuresGetter(ref featuresBuffer);
                        initialfeatureValuesList.Add(featuresBuffer.GetItemOrDefault(workingFeatureIndices[0]));
                    }

                    valuesRowCount = initialfeatureValuesList.Count;
                }

                if (valuesRowCount > 0)
                {
                    ch.Info("Detected {0} examples for evaluation.", valuesRowCount);
                }
                else
                {
                    ch.Warning("Detected no examples for evaluation.");
                    return(metricsDelta.ToImmutableArray());
                }

                float[] featureValuesBuffer = initialfeatureValuesList.ToArray();
                float[] nextValues          = new float[valuesRowCount];

                // Now iterate through all the working slots, do permutation and calc the delta of metrics.
                int processedCnt     = 0;
                int nextFeatureIndex = 0;
                var shuffleRand      = RandomUtils.Create(host.Rand.Next());
                using (var pch = host.StartProgressChannel("SDCA preprocessing with lookup"))
                {
                    pch.SetHeader(new ProgressHeader("processed slots"), e => e.SetProgress(0, processedCnt));
                    foreach (var workingIndx in workingFeatureIndices)
                    {
                        // Index for the feature we will permute next.  Needed to build in advance a buffer for the permutation.
                        if (processedCnt < workingFeatureIndices.Count - 1)
                        {
                            nextFeatureIndex = workingFeatureIndices[processedCnt + 1];
                        }

                        // Used for pre-caching the next feature
                        int nextValuesIndex = 0;

                        SchemaDefinition input = SchemaDefinition.Create(typeof(FeaturesBuffer));
                        Contracts.Assert(input.Count == 1);
                        input[0].ColumnName = features;

                        SchemaDefinition output = SchemaDefinition.Create(typeof(FeaturesBuffer));
                        Contracts.Assert(output.Count == 1);
                        output[0].ColumnName = features;
                        output[0].ColumnType = featuresColumn.Type;

                        // Perform multiple permutations for one feature to build a confidence interval
                        var metricsDeltaForFeature = new TResult();
                        for (int permutationIteration = 0; permutationIteration < permutationCount; permutationIteration++)
                        {
                            Utils.Shuffle <float>(shuffleRand, featureValuesBuffer);

                            Action <FeaturesBuffer, FeaturesBuffer, PermuterState> permuter =
                                (src, dst, state) =>
                            {
                                src.Features.CopyTo(ref dst.Features);
                                VBufferUtils.ApplyAt(ref dst.Features, workingIndx,
                                                     (int ii, ref float d) =>
                                                     d = featureValuesBuffer[state.SampleIndex++]);

                                // Is it time to pre-cache the next feature?
                                if (permutationIteration == permutationCount - 1 &&
                                    processedCnt < workingFeatureIndices.Count - 1)
                                {
                                    // Fill out the featureValueBuffer for the next feature while updating the current feature
                                    // This is the reason I need PermuterState in LambdaTransform.CreateMap.
                                    nextValues[nextValuesIndex] = src.Features.GetItemOrDefault(nextFeatureIndex);
                                    if (nextValuesIndex < valuesRowCount - 1)
                                    {
                                        nextValuesIndex++;
                                    }
                                }
                            };

                            IDataView viewPermuted = LambdaTransform.CreateMap(
                                host, data, permuter, null, input, output);
                            if (valuesRowCount == topExamples)
                            {
                                viewPermuted = SkipTakeFilter.Create(host, new SkipTakeFilter.TakeArguments()
                                {
                                    Count = valuesRowCount
                                }, viewPermuted);
                            }

                            var metrics = evaluationFunc(model.Transform(viewPermuted));

                            var delta = deltaFunc(metrics, baselineMetrics);
                            metricsDeltaForFeature.Add(delta);
                        }

                        // Add the metrics delta to the list
                        metricsDelta.Add(metricsDeltaForFeature);

                        // Swap values for next iteration of permutation.
                        if (processedCnt < workingFeatureIndices.Count - 1)
                        {
                            Array.Clear(featureValuesBuffer, 0, featureValuesBuffer.Length);
                            nextValues.CopyTo(featureValuesBuffer, 0);
                            Array.Clear(nextValues, 0, nextValues.Length);
                        }
                        processedCnt++;
                    }
                    pch.Checkpoint(processedCnt, processedCnt);
                }
            }

            return(metricsDelta.ToImmutableArray());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Animates the object. Intended to be called from PortalSpawnMessages.
        /// </summary>
        public static void AnimateObject(GameObject entity, PortalSpawnInfo settings)
        {
            Transform spriteObject = entity.transform.Find("Sprite");

            if (spriteObject == null)
            {
                spriteObject = entity.transform.Find("sprite");
            }
            if (spriteObject == null)
            {
                Logger.LogError($"No Sprite object found on {entity}! Cannot animate with {nameof(SpawnByPortal)}.");
            }
            float fallingTime = GetFallingTime(settings.PortalHeight);

            // Animate entity falling.
            LeanTween.moveLocalY(spriteObject.gameObject, 0, fallingTime).setFrom(settings.PortalHeight).setEaseInQuad();

            // Animate entity rotating during fall.
            if (settings.EntityRotate)
            {
                spriteObject.LeanRotateZ(UnityEngine.Random.Range(0, 720), fallingTime).setFrom(RandomUtils.RandomRotation2D().eulerAngles);
            }
        }
Exemplo n.º 13
0
 public RmlEnvironment(RmlEnvironment source, int?seed = null, bool verbose = false, int conc = 0)
     : this(source, RandomUtils.Create(seed), verbose, conc)
 {
 }
Exemplo n.º 14
0
 public RmlEnvironment(Bridge.CheckCancelled checkDelegate, int?seed = null, bool verbose = false, int conc = 0)
     : this(RandomUtils.Create(seed), verbose, conc)
 {
     CheckCancelled = checkDelegate;
 }
Exemplo n.º 15
0
 public Supernode(int id, RandomUtils randUtils)
 {
     Id = id;
     NodeIds = new List<int>();
     this.randUtils = randUtils;
 }
Exemplo n.º 16
0
        protected override void Attack()
        {
            if (!Target.IsAttackTarget(this))
            {
                Target = null;
                return;
            }
            Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
            int damage   = GetAttackPower(MinDC, MaxDC);
            int distance = Functions.MaxDistance(CurrentLocation, Target.CurrentLocation);
            int delay    = distance * 50 + 500; //50 MS per Step
            int rd       = RandomUtils.Next(100);

            //攻击力
            if (HP < MaxHP / 2)
            {
                damage = damage * 3 / 2;
            }

            if (HP < MaxHP / 3)
            {
                //攻击距离
                if (distance < 3)
                {
                    if (rd < 30)
                    {
                        attType = 0;
                    }
                    else if (rd < 50)
                    {
                        attType = 1;
                    }
                    else if (rd < 70)
                    {
                        attType = 2;
                    }
                    else if (rd < 80)
                    {
                        attType = 3;
                    }
                    else if (rd < 95)
                    {
                        attType = 4;
                    }
                    else
                    {
                        attType = 5;
                    }
                }
                else
                {
                    if (rd < 50)
                    {
                        attType = 3;
                    }
                    else if (rd < 80)
                    {
                        attType = 4;
                    }
                    else
                    {
                        attType = 5;
                    }
                }
            }
            else
            {
                //攻击距离
                if (distance < 3)
                {
                    if (rd < 10)
                    {
                        attType = 0;
                    }
                    else if (rd < 20)
                    {
                        attType = 1;
                    }
                    else if (rd < 40)
                    {
                        attType = 2;
                    }
                    else if (rd < 60)
                    {
                        attType = 3;
                    }
                    else if (rd < 85)
                    {
                        attType = 4;
                    }
                    else
                    {
                        attType = 5;
                    }
                }
                else
                {
                    if (rd < 30)
                    {
                        attType = 3;
                    }
                    else if (rd < 60)
                    {
                        attType = 4;
                    }
                    else
                    {
                        attType = 5;
                    }
                }
            }
            DelayedAction    action  = null;
            List <MapObject> targets = null;

            switch (attType)
            {
            case 0:
                Broadcast(new S.ObjectAttack {
                    ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 0
                });
                action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage, DefenceType.ACAgility);
                ActionList.Add(action);
                break;

            case 1:
                Broadcast(new S.ObjectAttack {
                    ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 1
                });
                action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage, DefenceType.AC);
                ActionList.Add(action);
                break;

            case 2:
                Broadcast(new S.ObjectAttack {
                    ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 2
                });
                action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage, DefenceType.AC);
                ActionList.Add(action);
                action = new DelayedAction(DelayedType.Damage, Envir.Time + delay + 300, Target, damage, DefenceType.AC);
                ActionList.Add(action);
                break;

            case 3:
                //这个是方向攻击
                Broadcast(new S.ObjectRangeAttack {
                    ObjectID = ObjectID, Direction = Direction, TargetID = Target.ObjectID, Location = CurrentLocation, Type = 0
                });
                targets = FindAllTargets(4, CurrentLocation, false);
                foreach (MapObject ob in targets)
                {
                    action = new DelayedAction(DelayedType.RangeDamage, Envir.Time + delay, ob, damage, DefenceType.MACAgility);
                    ActionList.Add(action);
                }
                break;

            case 4:
                Broadcast(new S.ObjectRangeAttack {
                    ObjectID = ObjectID, Direction = Direction, TargetID = Target.ObjectID, Location = CurrentLocation, Type = 1
                });
                targets = FindAllTargets(4, CurrentLocation, false);
                foreach (MapObject ob in targets)
                {
                    action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, ob, damage, DefenceType.MACAgility);
                    ActionList.Add(action);
                    //冰冻

                    if (RandomUtils.Next(Settings.PoisonResistWeight) >= Target.PoisonResist)
                    {
                        ob.ApplyPoison(new Poison
                        {
                            Owner     = this,
                            Duration  = RandomUtils.Next(4, 7),
                            PType     = PoisonType.Frozen,
                            Value     = damage,
                            TickSpeed = 1000
                        }, this);
                    }
                }
                break;

            case 5:
                Broadcast(new S.ObjectRangeAttack {
                    ObjectID = ObjectID, Direction = Direction, TargetID = Target.ObjectID, Location = CurrentLocation, Type = 2
                });
                targets = FindAllTargets(4, CurrentLocation, false);
                foreach (MapObject ob in targets)
                {
                    action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, ob, damage, DefenceType.MACAgility);
                    ActionList.Add(action);
                    action = new DelayedAction(DelayedType.Damage, Envir.Time + delay + 300, ob, damage, DefenceType.MAC);
                    ActionList.Add(action);
                }
                break;
            }

            ShockTime  = 0;
            ActionTime = Envir.Time + 500;
            AttackTime = Envir.Time + (AttackSpeed);
        }
Exemplo n.º 17
0
        public InvoiceResponse EntityToDTO()
        {
            ServerUrl = ServerUrl ?? "";
            InvoiceResponse dto = new InvoiceResponse
            {
                Id             = Id,
                StoreId        = StoreId,
                OrderId        = OrderId,
                PosData        = PosData,
                CurrentTime    = DateTimeOffset.UtcNow,
                InvoiceTime    = InvoiceTime,
                ExpirationTime = ExpirationTime,
#pragma warning disable CS0618 // Type or member is obsolete
                Status          = StatusString,
                ExceptionStatus = ExceptionStatus == InvoiceExceptionStatus.None ? new JValue(false) : new JValue(ExceptionStatusString),
#pragma warning restore CS0618 // Type or member is obsolete
                Currency = ProductInformation.Currency,
                Flags    = new Flags()
                {
                    Refundable = Refundable
                },
                PaymentSubtotals = new Dictionary <string, decimal>(),
                PaymentTotals    = new Dictionary <string, decimal>(),
                SupportedTransactionCurrencies = new Dictionary <string, InvoiceSupportedTransactionCurrency>(),
                Addresses     = new Dictionary <string, string>(),
                PaymentCodes  = new Dictionary <string, InvoicePaymentUrls>(),
                ExchangeRates = new Dictionary <string, Dictionary <string, decimal> >()
            };

            dto.Url        = ServerUrl.WithTrailingSlash() + $"invoice?id=" + Id;
            dto.CryptoInfo = new List <NBitpayClient.InvoiceCryptoInfo>();
            dto.MinerFees  = new Dictionary <string, MinerFeeInfo>();
            foreach (var info in this.GetPaymentMethods())
            {
                var accounting    = info.Calculate();
                var cryptoInfo    = new NBitpayClient.InvoiceCryptoInfo();
                var subtotalPrice = accounting.TotalDue - accounting.NetworkFee;
                var cryptoCode    = info.GetId().CryptoCode;
                var details       = info.GetPaymentMethodDetails();
                var address       = details?.GetPaymentDestination();
                var exrates       = new Dictionary <string, decimal>
                {
                    { ProductInformation.Currency, cryptoInfo.Rate }
                };

                cryptoInfo.CryptoCode  = cryptoCode;
                cryptoInfo.PaymentType = info.GetId().PaymentType.ToString();
                cryptoInfo.Rate        = info.Rate;
                cryptoInfo.Price       = subtotalPrice.ToString();

                cryptoInfo.Due        = accounting.Due.ToString();
                cryptoInfo.Paid       = accounting.Paid.ToString();
                cryptoInfo.TotalDue   = accounting.TotalDue.ToString();
                cryptoInfo.NetworkFee = accounting.NetworkFee.ToString();
                cryptoInfo.TxCount    = accounting.TxCount;
                cryptoInfo.CryptoPaid = accounting.CryptoPaid.ToString();

                cryptoInfo.Address = address;

                cryptoInfo.ExRates = exrates;
                var paymentId = info.GetId();
                cryptoInfo.Url = ServerUrl.WithTrailingSlash() + $"i/{paymentId}/{Id}";

                cryptoInfo.Payments = GetPayments(info.Network).Select(entity =>
                {
                    var data = entity.GetCryptoPaymentData();
                    return(new InvoicePaymentInfo()
                    {
                        Id = data.GetPaymentId(),
                        Fee = entity.NetworkFee,
                        Value = data.GetValue(),
                        Completed = data.PaymentCompleted(entity),
                        Confirmed = data.PaymentConfirmed(entity, SpeedPolicy),
                        Destination = data.GetDestination(),
                        PaymentType = data.GetPaymentType().ToString(),
                        ReceivedDate = entity.ReceivedTime.DateTime
                    });
                }).ToList();


                if (paymentId.PaymentType == PaymentTypes.LightningLike)
                {
                    cryptoInfo.PaymentUrls = new InvoicePaymentUrls()
                    {
                        BOLT11 = $"lightning:{cryptoInfo.Address}"
                    };
                }
                else if (paymentId.PaymentType == PaymentTypes.BTCLike)
                {
                    var minerInfo = new MinerFeeInfo();
                    minerInfo.TotalFee        = accounting.NetworkFee.Satoshi;
                    minerInfo.SatoshiPerBytes = ((BitcoinLikeOnChainPaymentMethod)details).FeeRate
                                                .GetFee(1).Satoshi;
                    dto.MinerFees.TryAdd(cryptoInfo.CryptoCode, minerInfo);
                    var bip21 = ((BTCPayNetwork)info.Network).GenerateBIP21(cryptoInfo.Address, cryptoInfo.Due);

                    if ((details as BitcoinLikeOnChainPaymentMethod)?.PayjoinEnabled is true)
                    {
                        bip21 += $"&{PayjoinClient.BIP21EndpointKey}={ServerUrl.WithTrailingSlash()}{cryptoCode}/{PayjoinClient.BIP21EndpointKey}";
                    }
                    cryptoInfo.PaymentUrls = new NBitpayClient.InvoicePaymentUrls()
                    {
                        BIP21 = bip21,
                    };

#pragma warning disable 618
                    if (info.CryptoCode == "BTC")
                    {
                        dto.BTCPrice       = cryptoInfo.Price;
                        dto.Rate           = cryptoInfo.Rate;
                        dto.ExRates        = cryptoInfo.ExRates;
                        dto.BitcoinAddress = cryptoInfo.Address;
                        dto.BTCPaid        = cryptoInfo.Paid;
                        dto.BTCDue         = cryptoInfo.Due;
                        dto.PaymentUrls    = cryptoInfo.PaymentUrls;
                    }
#pragma warning restore 618
                }

                dto.CryptoInfo.Add(cryptoInfo);
                dto.PaymentCodes.Add(paymentId.ToString(), cryptoInfo.PaymentUrls);
                dto.PaymentSubtotals.Add(paymentId.ToString(), subtotalPrice.Satoshi);
                dto.PaymentTotals.Add(paymentId.ToString(), accounting.TotalDue.Satoshi);
                dto.SupportedTransactionCurrencies.TryAdd(cryptoCode, new InvoiceSupportedTransactionCurrency()
                {
                    Enabled = true
                });
                dto.Addresses.Add(paymentId.ToString(), address);
                dto.ExchangeRates.TryAdd(cryptoCode, exrates);
            }

            //dto.AmountPaid dto.MinerFees & dto.TransactionCurrency are not supported by btcpayserver as we have multi currency payment support per invoice

            Populate(ProductInformation, dto);
            dto.Buyer = new JObject();
            dto.Buyer.Add(new JProperty("name", BuyerInformation.BuyerName));
            dto.Buyer.Add(new JProperty("address1", BuyerInformation.BuyerAddress1));
            dto.Buyer.Add(new JProperty("address2", BuyerInformation.BuyerAddress2));
            dto.Buyer.Add(new JProperty("locality", BuyerInformation.BuyerCity));
            dto.Buyer.Add(new JProperty("region", BuyerInformation.BuyerState));
            dto.Buyer.Add(new JProperty("postalCode", BuyerInformation.BuyerZip));
            dto.Buyer.Add(new JProperty("country", BuyerInformation.BuyerCountry));
            dto.Buyer.Add(new JProperty("phone", BuyerInformation.BuyerPhone));
            dto.Buyer.Add(new JProperty("email", string.IsNullOrWhiteSpace(BuyerInformation.BuyerEmail) ? RefundMail : BuyerInformation.BuyerEmail));

            dto.Token = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); //No idea what it is useful for
            dto.Guid  = Guid.NewGuid().ToString();
            return(dto);
        }
        public async Task ReorgedBlocksAreDeletedFromRepositoryIfReorgDetectedAsync()
        {
            this.chainIndexer = CreateChain(1000);
            this.repositoryTipHashAndHeight = new HashHeightPair(this.chainIndexer.Genesis.HashBlock, 0);

            var blockStoreFlushCondition = new Mock <IBlockStoreQueueFlushCondition>();

            blockStoreFlushCondition.Setup(s => s.ShouldFlush).Returns(false);

            this.blockStoreQueue = new BlockStoreQueue(this.chainIndexer, this.chainState, blockStoreFlushCondition.Object, new StoreSettings(this.nodeSettings), this.nodeSettings,
                                                       this.blockRepositoryMock.Object, new LoggerFactory(), new Mock <INodeStats>().Object);

            this.blockStoreQueue.Initialize();
            this.chainState.ConsensusTip = this.chainIndexer.Tip;

            // Sending 500 blocks to the queue.
            for (int i = 1; i < 500; i++)
            {
                Block block = this.network.Consensus.ConsensusFactory.CreateBlock();
                block.GetSerializedSize();

                this.blockStoreQueue.AddToPending(new ChainedHeaderBlock(block, this.chainIndexer.GetHeader(i)));
            }

            // Create alternative chain with fork point at 450.
            ChainedHeader prevBlock         = this.chainIndexer.GetHeader(450);
            var           alternativeBlocks = new List <ChainedHeader>();

            for (int i = 0; i < 100; i++)
            {
                BlockHeader header = this.network.Consensus.ConsensusFactory.CreateBlockHeader();
                header.Nonce         = RandomUtils.GetUInt32();
                header.HashPrevBlock = prevBlock.HashBlock;
                header.Bits          = Target.Difficulty1;

                var chainedHeader = new ChainedHeader(header, header.GetHash(), prevBlock);
                alternativeBlocks.Add(chainedHeader);
                prevBlock = chainedHeader;
            }

            ChainedHeader savedHeader = this.chainIndexer.Tip;

            this.chainIndexer.SetTip(alternativeBlocks.Last());
            this.chainState.ConsensusTip = this.chainIndexer.Tip;

            // Present alternative chain and trigger save.
            foreach (ChainedHeader header in alternativeBlocks)
            {
                Block block = this.network.Consensus.ConsensusFactory.CreateBlock();
                block.GetSerializedSize();

                if (header == alternativeBlocks.Last())
                {
                    blockStoreFlushCondition.Setup(s => s.ShouldFlush).Returns(true);
                }

                this.blockStoreQueue.AddToPending(new ChainedHeaderBlock(block, header));
            }

            await this.WaitUntilQueueIsEmptyAsync().ConfigureAwait(false);

            blockStoreFlushCondition.Setup(s => s.ShouldFlush).Returns(false);

            // Make sure only longest chain is saved.
            Assert.Equal(this.chainIndexer.Tip.Height, this.repositoryTotalBlocksSaved);

            // Present a new longer chain that will reorg the repository.
            this.chainIndexer.SetTip(savedHeader);
            this.chainState.ConsensusTip = this.chainIndexer.Tip;

            for (int i = 451; i <= this.chainIndexer.Height; i++)
            {
                Block block = this.network.Consensus.ConsensusFactory.CreateBlock();
                block.GetSerializedSize();

                if (i == this.chainIndexer.Height)
                {
                    blockStoreFlushCondition.Setup(s => s.ShouldFlush).Returns(true);
                }

                this.blockStoreQueue.AddToPending(new ChainedHeaderBlock(block, this.chainIndexer.GetHeader(i)));
            }

            await this.WaitUntilQueueIsEmptyAsync().ConfigureAwait(false);

            // Make sure chain is saved.
            Assert.Equal(this.chainIndexer.Tip.Height + alternativeBlocks.Count, this.repositoryTotalBlocksSaved);
            Assert.Equal(alternativeBlocks.Count, this.repositoryTotalBlocksDeleted);

            // Dispose block store.
            this.nodeLifetime.StopApplication();
            this.blockStoreQueue.Dispose();
        }
Exemplo n.º 19
0
        /// <summary>
        /// 获得物品
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="prize"></param>
        /// <returns></returns>
        public bool DoPrize(GameUser userInfo, List <PrizeInfo> prizeList)
        {
            try
            {
                bool        isDeduct = false;
                CrystalInfo crystal  = new CrystalInfo();
                content = LanguageManager.GetLang().St_SummerThreeGameCoinNotice.Substring(0, 5);
                foreach (PrizeInfo prize in prizeList)
                {
                    int num = prize.Num;
                    switch (prize.Type)
                    {
                    case RewardType.GameGoin:
                        userInfo.GameCoin = MathUtils.Addition(userInfo.GameCoin, num);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeGameCoinNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_GameCoin, num) + ",";
                        }
                        break;

                    case RewardType.Obtion:
                        userInfo.ObtainNum = MathUtils.Addition(userInfo.ObtainNum, num);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeObtionNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_ObtionNum, num) + ",";
                        }
                        break;

                    case RewardType.ExpNum:
                        userInfo.ExpNum = MathUtils.Addition(userInfo.ExpNum, num);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeExpNumNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_ExpNum, num) + ",";
                        }
                        break;

                    case RewardType.EnergyNum:
                        userInfo.EnergyNum = MathUtils.Addition(userInfo.EnergyNum, (short)num, short.MaxValue);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeEnergyNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_EnergyNum, num) + ",";
                        }
                        break;

                    case RewardType.Experience:
                        UserHelper.UserGeneralExp(userInfo.UserID, num);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeExperienceNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_Experience, num) + ",";
                        }
                        break;

                    case RewardType.Gold:
                        userInfo.ItemGold = MathUtils.Addition(userInfo.ItemGold, num);
                        if (content.Length == 0)
                        {
                            content = string.Format(LanguageManager.GetLang().St_SummerThreeGoldNotice, num);
                        }
                        else
                        {
                            content += string.Format(LanguageManager.GetLang().St_GiftGoldNum, num) + ",";
                        }
                        break;

                    case RewardType.Item:
                        if (UserHelper.IsBeiBaoFull(userInfo))
                        {
                            content = LanguageManager.GetLang().St1107_GridNumFull;
                            return(false);
                        }
                        UserItemHelper.AddUserItem(userInfo.UserID, prize.ItemID, num);
                        ItemBaseInfo itemInfo = new ShareCacheStruct <ItemBaseInfo>().FindKey(prize.ItemID);
                        if (itemInfo != null)
                        {
                            if (content.Length == 0)
                            {
                                content = string.Format(LanguageManager.GetLang().St_SummerThreeItemNotice, num);
                            }
                            else
                            {
                                content += string.Format("{0}*{1}", itemInfo.ItemName, num) + ",";
                            }
                        }
                        break;

                    case RewardType.CrystalType:
                        if (!UserCrystalInfo.CheckFull(userInfo.UserID, 0))
                        {
                            content = LanguageManager.GetLang().St1307_FateBackpackFull;
                            return(false);
                        }
                        List <CrystalInfo> crystalArray2 = new ShareCacheStruct <CrystalInfo>().FindAll(m => m.CrystalQuality == prize.CrystalType);
                        if (crystalArray2.Count > 0)
                        {
                            int randomNum = RandomUtils.GetRandom(0, crystalArray2.Count);
                            int crystalID = crystalArray2[randomNum].CrystalID;
                            UserHelper.CrystalAppend(userInfo.UserID, crystalID, 2);
                            CrystalHelper.SendChat(crystalArray2[randomNum].CrystalID, userInfo);
                            crystal = new ShareCacheStruct <CrystalInfo>().FindKey(crystalID);
                            if (crystal != null)
                            {
                                content += string.Format(LanguageManager.GetLang().St_Crystal, CrystalHelper.GetQualityName(crystal.CrystalQuality), crystal.CrystalName) + ",";
                            }
                        }
                        else
                        {
                            TraceLog.WriteError("配置出错");
                            return(false);
                        }
                        break;

                    case RewardType.CrystalId:
                        if (!UserCrystalInfo.CheckFull(userInfo.UserID, 0))
                        {
                            content = LanguageManager.GetLang().St1307_FateBackpackFull;
                            return(false);
                        }
                        UserHelper.CrystalAppend(userInfo.UserID, prize.ItemID, 2);
                        CrystalHelper.SendChat(prize.ItemID, userInfo);
                        crystal = new ShareCacheStruct <CrystalInfo>().FindKey(prize.ItemID);
                        if (crystal != null)
                        {
                            content += string.Format(LanguageManager.GetLang().St_Crystal, CrystalHelper.GetQualityName(crystal.CrystalQuality), crystal.CrystalName) + ",";
                        }
                        break;

                    case RewardType.Spare:
                        int currNum = userInfo.SparePartList.FindAll(m => string.IsNullOrEmpty(m.UserItemID)).Count;
                        if (currNum >= userInfo.UserExtend.SparePartGridNum)
                        {
                            content = LanguageManager.GetLang().St1213_GridNumFull;
                            return(false);
                        }
                        UserSparePart sparePart = UserSparePart.GetRandom(prize.ItemID);
                        SparePartInfo partInfo  = new ShareCacheStruct <SparePartInfo>().FindKey(prize.ItemID);
                        if (partInfo != null && sparePart != null && UserHelper.AddSparePart(userInfo, sparePart))
                        {
                            SendChat(prize, userInfo.NickName, partInfo.Name);
                        }
                        content = string.Empty;
                        break;

                    default:
                        break;
                    }
                    if (prize.Reward == 3 && !string.IsNullOrEmpty(prize.Desc))
                    {
                        content = prize.Desc;
                    }
                    //原因:开启礼包消耗的物品
                    if (prize.DemandItem > 0 && !isDeduct)
                    {
                        UserItemHelper.UseUserItem(userInfo.UserID, prize.DemandItem, prize.DemandNum);
                        isDeduct = true;
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                content = "使用礼包出错!";
                TraceLog.WriteError("使用礼包出错!", ex);
            }
            return(false);
        }
Exemplo n.º 20
0
 protected override void InitializeStateCore()
 {
     _parent    = (PValueTransform)ParentTransform;
     _randomGen = RandomUtils.Create(_parent._seed);
 }
Exemplo n.º 21
0
        public InvoiceResponse EntityToDTO(BTCPayNetworkProvider networkProvider)
        {
            ServerUrl = ServerUrl ?? "";
            InvoiceResponse dto = new InvoiceResponse
            {
                Id             = Id,
                OrderId        = OrderId,
                PosData        = PosData,
                CurrentTime    = DateTimeOffset.UtcNow,
                InvoiceTime    = InvoiceTime,
                ExpirationTime = ExpirationTime,
                Status         = Status,
                Currency       = ProductInformation.Currency,
                Flags          = new Flags()
                {
                    Refundable = Refundable
                }
            };

            dto.CryptoInfo = new List <InvoiceCryptoInfo>();
            foreach (var info in this.GetCryptoData().Values)
            {
                var accounting = info.Calculate();
                var cryptoInfo = new InvoiceCryptoInfo();
                cryptoInfo.CryptoCode = info.CryptoCode;
                cryptoInfo.Rate       = info.Rate;
                cryptoInfo.Price      = Money.Coins(ProductInformation.Price / cryptoInfo.Rate).ToString();

                cryptoInfo.Due        = accounting.Due.ToString();
                cryptoInfo.Paid       = accounting.Paid.ToString();
                cryptoInfo.TotalDue   = accounting.TotalDue.ToString();
                cryptoInfo.NetworkFee = accounting.NetworkFee.ToString();
                cryptoInfo.TxCount    = accounting.TxCount;
                cryptoInfo.CryptoPaid = accounting.CryptoPaid;

                cryptoInfo.Address = info.DepositAddress;
                cryptoInfo.ExRates = new Dictionary <string, double>
                {
                    { ProductInformation.Currency, (double)cryptoInfo.Rate }
                };

                var scheme       = networkProvider.GetNetwork(info.CryptoCode)?.UriScheme ?? "BTC";
                var cryptoSuffix = cryptoInfo.CryptoCode == "BTC" ? "" : "/" + cryptoInfo.CryptoCode;
                cryptoInfo.Url = ServerUrl.WithTrailingSlash() + $"invoice{cryptoSuffix}?id=" + Id;


                cryptoInfo.PaymentUrls = new InvoicePaymentUrls()
                {
                    BIP72  = $"{scheme}:{cryptoInfo.Address}?amount={cryptoInfo.Due}&r={ServerUrl.WithTrailingSlash() + ($"i/{Id}{cryptoSuffix}")}",
                    BIP72b = $"{scheme}:?r={ServerUrl.WithTrailingSlash() + ($"i/{Id}{cryptoSuffix}")}",
                    BIP73  = ServerUrl.WithTrailingSlash() + ($"i/{Id}{cryptoSuffix}"),
                    BIP21  = $"{scheme}:{cryptoInfo.Address}?amount={cryptoInfo.Due}",
                };
#pragma warning disable CS0618
                if (info.CryptoCode == "BTC")
                {
                    dto.Url            = cryptoInfo.Url;
                    dto.BTCPrice       = cryptoInfo.Price;
                    dto.Rate           = cryptoInfo.Rate;
                    dto.ExRates        = cryptoInfo.ExRates;
                    dto.BitcoinAddress = cryptoInfo.Address;
                    dto.BTCPaid        = cryptoInfo.Paid;
                    dto.BTCDue         = cryptoInfo.Due;
                    dto.PaymentUrls    = cryptoInfo.PaymentUrls;
                }
#pragma warning restore CS0618

                dto.CryptoInfo.Add(cryptoInfo);
            }

            Populate(ProductInformation, dto);
            Populate(BuyerInformation, dto);

            dto.Token = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); //No idea what it is useful for
            dto.Guid  = Guid.NewGuid().ToString();

            dto.ExceptionStatus = ExceptionStatus == null ? new JValue(false) : new JValue(ExceptionStatus);
            return(dto);
        }
Exemplo n.º 22
0
 public override int Next()
 {
     return(RandomUtils.GetInt32());
 }
Exemplo n.º 23
0
 /// <summary>
 /// Generates random key. Used internally and can be used to generate key for manual Encrypt() calls.
 /// </summary>
 /// <returns>Key suitable for manual Encrypt() calls.</returns>
 public static ushort GenerateKey()
 {
     return(RandomUtils.GenerateUShortKey());
 }
Exemplo n.º 24
0
 public override void NextBytes(byte[] buffer)
 {
     RandomUtils.GetBytes(buffer);
 }
Exemplo n.º 25
0
        protected override void Attack()
        {
            if (!Target.IsAttackTarget(this))
            {
                Target = null;
                return;
            }
            Direction = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation);
            int damage   = GetAttackPower(MinDC, MaxDC);
            int distance = Functions.MaxDistance(CurrentLocation, Target.CurrentLocation);
            int delay    = distance * 50 + 750; //50 MS per Step
            int rd       = RandomUtils.Next(100);

            if (distance > 2)
            {
                if (rd < 70)
                {
                    attType = 1;
                }
                else
                {
                    attType = 2;
                }
            }
            else
            {
                attType = 0;
            }


            if (attType == 0)
            {
                Broadcast(new S.ObjectAttack {
                    ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation, Type = 0
                });
                DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage, DefenceType.ACAgility);
                ActionList.Add(action);
            }
            if (attType == 1)
            {
                Broadcast(new S.ObjectRangeAttack {
                    ObjectID = ObjectID, Direction = Direction, TargetID = Target.ObjectID, Location = CurrentLocation, Type = 0
                });
                DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage, DefenceType.MACAgility);
                ActionList.Add(action);
            }
            //带流血效果
            if (attType == 2)
            {
                Broadcast(new S.ObjectRangeAttack {
                    ObjectID = ObjectID, Direction = Direction, TargetID = Target.ObjectID, Location = CurrentLocation, Type = 1
                });
                DelayedAction action = new DelayedAction(DelayedType.Damage, Envir.Time + delay, Target, damage * 2, DefenceType.MAC);
                ActionList.Add(action);
                if (RandomUtils.Next(Settings.PoisonResistWeight) >= Target.PoisonResist && RandomUtils.Next(2) == 1)
                {
                    if (RandomUtils.Next(2) == 0)
                    {
                        Target.ApplyPoison(new Poison {
                            Owner = this, Duration = 2, PType = PoisonType.Bleeding, Value = damage / 2, TickSpeed = 2000
                        }, this);
                    }
                }
            }
            ShockTime  = 0;
            ActionTime = Envir.Time + 500;
            AttackTime = Envir.Time + (AttackSpeed);
        }
Exemplo n.º 26
0
 public static OutPoint GetRandomOutPoint()
 {
     return(new OutPoint(RandomUtils.GetUInt256(), 0));
 }
Exemplo n.º 27
0
 private void Shuffle()
 {
     _shuffledList = RandomUtils.ShuffleList <T>(_list);
 }
Exemplo n.º 28
0
        protected override void ProcessTarget()
        {
            if (Target == null)
            {
                return;
            }

            if (InAttackRange() && CanAttack)
            {
                Attack();
                if (Target == null || Target.Dead)
                {
                    FindTarget();
                }

                return;
            }

            if (Envir.Time < ShockTime)
            {
                Target = null;
                return;
            }

            if (!CanMove || Target == null)
            {
                return;
            }
            int distance = Functions.MaxDistance(CurrentLocation, Target.CurrentLocation);

            if (distance > 6)
            {
                MoveTo(Target.CurrentLocation);
                return;
            }


            //40几率跑路
            if (RandomUtils.Next(100) < 60)
            {
                return;
            }
            MirDirection dir = Functions.DirectionFromPoint(Target.CurrentLocation, CurrentLocation);

            if (Walk(dir))
            {
                return;
            }

            switch (RandomUtils.Next(2)) //No favour
            {
            case 0:
                for (int i = 0; i < 7; i++)
                {
                    dir = Functions.NextDir(dir);

                    if (Walk(dir))
                    {
                        return;
                    }
                }
                break;

            default:
                for (int i = 0; i < 7; i++)
                {
                    dir = Functions.PreviousDir(dir);

                    if (Walk(dir))
                    {
                        return;
                    }
                }
                break;
            }
        }
Exemplo n.º 29
0
 public GenericRecommenderIRStatsEvaluator(IRelevantItemsDataSplitter dataSplitter)
 {
     //Preconditions.checkNotNull(dataSplitter);
     random            = RandomUtils.getRandom();
     this.dataSplitter = dataSplitter;
 }
Exemplo n.º 30
0
        private static Random GetRandomNumberGenerator()
        {
            var seed = RandomUtils.GetSeed();

            return(new Random(seed));
        }
Exemplo n.º 31
0
 public int GetRandomGold()
 {
     return(RandomUtils.IsHit(this.GoldProbability) ? this.Gold : 0);
 }
Exemplo n.º 32
0
        public SignaturesRequest CreateSignatureRequest(Script cashoutDestination, FeeRate feeRate)
        {
            if (cashoutDestination == null)
            {
                throw new ArgumentNullException(nameof(cashoutDestination));
            }
            if (feeRate == null)
            {
                throw new ArgumentNullException(nameof(feeRate));
            }
            AssertState(PromiseClientStates.WaitingSignatureRequest);

            Transaction cashout = new Transaction();

            cashout.AddInput(new TxIn(InternalState.EscrowedCoin.Outpoint));
            cashout.Inputs[0].ScriptSig = new Script(
                Op.GetPushOp(TrustedBroadcastRequest.PlaceholderSignature),
                Op.GetPushOp(TrustedBroadcastRequest.PlaceholderSignature),
                Op.GetPushOp(InternalState.EscrowedCoin.Redeem.ToBytes())
                );
            cashout.Inputs[0].Witnessify();
            cashout.AddOutput(new TxOut(InternalState.EscrowedCoin.Amount, cashoutDestination));
            var virtualSize = cashout.HasWitness ? cashout.GetVirtualSize(_Network.Consensus.Options.WitnessScaleFactor) : cashout.GetSerializedSize();

            cashout.Outputs[0].Value -= feeRate.GetFee(virtualSize);


            List <HashBase> hashes = new List <HashBase>();

            for (int i = 0; i < Parameters.RealTransactionCount; i++)
            {
                RealHash h = new RealHash(cashout, InternalState.EscrowedCoin);
                h.FeeVariation = Money.Satoshis(i);
                hashes.Add(h);
            }

            for (int i = 0; i < Parameters.FakeTransactionCount; i++)
            {
                FakeHash h = new FakeHash(Parameters);
                h.Salt = new uint256(RandomUtils.GetBytes(32));
                hashes.Add(h);
            }

            _Hashes = hashes.ToArray();
            NBitcoin.Utils.Shuffle(_Hashes, RandomUtils.GetInt32());
            for (int i = 0; i < _Hashes.Length; i++)
            {
                _Hashes[i].Index = i;
            }
            var     fakeIndices = _Hashes.OfType <FakeHash>().Select(h => h.Index).ToArray();
            uint256 indexSalt   = null;
            var     request     = new SignaturesRequest
            {
                Hashes          = _Hashes.Select(h => h.GetHash(_Network)).ToArray(),
                FakeIndexesHash = PromiseUtils.HashIndexes(ref indexSalt, fakeIndices),
            };

            InternalState.IndexSalt   = indexSalt;
            InternalState.Cashout     = cashout.Clone(_Network.Consensus.ConsensusFactory);
            InternalState.Status      = PromiseClientStates.WaitingCommitments;
            InternalState.FakeIndexes = fakeIndices;
            return(request);
        }
Exemplo n.º 33
0
 public override string Choice(List<string> allWords)
 {
     RandomUtils rand = new RandomUtils();
     return rand.RandomizeWord(allWords);
 }