Ejemplo n.º 1
0
        public ActionResult AsynTest()
        {
            List<SystemStatusInfo> infoList = new List<SystemStatusInfo>();
            SystemStatusInfo item4 = new SystemStatusInfo();
            item4.SystemStatus = HiLand.Utility.Enums.SystemStatuses.Tip;
            item4.Message = "数据准备中,其完成后会自动下载,请等待。。。";
            infoList.Add(item4);
            this.TempData.Add("OperationResultData", infoList);

            Funcs<ActionResult> commonHandle = new Funcs<ActionResult>(Foo);
            this.TempData["AsynMethod"]= commonHandle;

            commonHandle.BeginInvoke(null,null);
            return RedirectToAction("OperationResults", "System", new { });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 获取还款日程信息
        /// </summary>
        /// <param name="paymentNumber">指定要计算的还款档期序号</param>
        /// <param name="rate">利率</param>
        /// <param name="paymentCount">还款总期数</param>
        /// <param name="totalAmount">贷款总费用</param>
        /// <param name="dueDate">还款在每期的开始还是结尾时间,缺省为每期的结尾时间(大部分商业都是用结尾时间)</param>
        /// <param name="getPaymentFunc">生成每期贷款的方法</param>
        /// <returns>每期还款的额度</returns>
        /// <remarks>参数rate和参数paymentCount是呼应的。即如果paymentCount按照月计数,那么rate就必须指定为月利率;
        ///    如果paymentCount按照年计数,那么rate就必须指定为年利率。</remarks>
        public static List<Payment> GetPaymentSchedule(double rate, double totalAmount, int paymentCount, PaymentTermTypes paymentCircle, DateTime loanStartDate, DueDate dueDate, Funcs<double, double, int, int, DueDate, Payment> getPaymentFunc)
        {
            //贷款还款日期的时间精度仅仅控制到日,不对时分秒控制
            loanStartDate = loanStartDate.Date;

            List<Payment> paymentSchedule = new List<Payment>();
            double totalNeedPayPrinclepal = 0;
            DateTime lastPaymentDate = DateTime.MinValue;
            for (int i = 0; i < paymentCount; i++)
            {
                int paymentNumber = i + 1;
                Payment payment = getPaymentFunc(rate, totalAmount, paymentCount, paymentNumber, dueDate);
                totalNeedPayPrinclepal += payment.Principal;
                payment.TotalPrincipal = totalNeedPayPrinclepal;
                payment.PrincipalBalance = totalAmount - totalNeedPayPrinclepal;
                if (lastPaymentDate == DateTime.MinValue)
                {
                    if (dueDate == DueDate.BegOfPeriod)
                    {
                        lastPaymentDate = loanStartDate;
                    }
                    else
                    {
                        lastPaymentDate = LoanHelper.GetNextPaymentDate(loanStartDate, paymentCircle);
                    }
                }
                else
                {
                    lastPaymentDate = LoanHelper.GetNextPaymentDate(lastPaymentDate, paymentCircle);
                }

                payment.PaymentDate = lastPaymentDate;

                paymentSchedule.Add(payment);
            }

            return paymentSchedule;
        }
Ejemplo n.º 3
0
 public GameTask(int interval, Action action)
 {
     LastWorkTime = Funcs.GetRoundedUtc();
     WorkInterval = interval;
     Task         = action;
 }
Ejemplo n.º 4
0
        private static void InitializeServerData()
        {
            for (short i = 1; i < MaxClients + 1; i++)
            {
                Clients.Add(i, new Client(i));
            }

            handlers = new Dictionary <int, PacketHandler>
            {
                { (int)Packets.ClientPackets.WelcomeReceived, Packets.ServerHandle.Receive.WelcomeConfirmation },
                { (int)Packets.ClientPackets.UnitMovement, Packets.ServerHandle.Receive.PlayerUnitMovement },
                { (int)Packets.ClientPackets.ChatMessage, Packets.ServerHandle.Receive.ChatMessage }
            };

            clientCommands = new CommandHandler("/");
            clientCommands.register(new Command("help", "", "Display all available commands", (player, args) =>
            {
                string final = String.Empty;
                foreach (var cmd in clientCommands.commands)
                {
                    final = final + $"[color={Funcs.ColorToHex(Pals.command)}]{cmd.Value.name}[/color] [color={Funcs.ColorToHex(Pals.unimportant)}]{cmd.Value.textparam}[/color] - {cmd.Value.desc}\n";
                }
                NetworkManager.SendMessage(NetworkManager.loc.SERVER, final.Substring(0, final.Length - 1), player); // remove trailing \n
            }));

            clientCommands.register(new AdminCommand("spawn", "[amount] [typeid]", "Spawns an amount of units at the player's position",
                                                     (player, args) =>
            {
                int amt;
                UnitType type;

                try
                {
                    amt  = int.Parse((string)args[0]);
                    type = Enums.UnitTypes[int.Parse((string)args[1])];
                }
                catch (Exception e)
                {
                    NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"[color=#e64b40]Error parsing command arguments:[/color] {e.Message}", player);
                    return;
                }

                if (player.Unit?.Body != null)
                {
                    var pos = player.Unit.Body.GlobalPosition;
                    var rnd = new Random();
                    pos.x  += rnd.Next(-20000, 20000) / 300f;
                    pos.y  += rnd.Next(-20000, 20000) / 300f;

                    for (int i = 0; i < amt; i++)
                    {
                        NetworkManager.CreateUnit(NetworkManager.loc.SERVER, 0, type, pos, 0);
                    }
                    NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"Spawned {amt} {type.Name}s", player);
                    return;
                }
                NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"You need to be alive to use this command.", player);
            }));

            clientCommands.register(new AdminCommand("ownership", "[unitid]", "Take the ownership of the specified unit",
                                                     (player, args) =>
            {
                Unit unit;
                try
                {
                    unit = NetworkManager.UnitsGroup[int.Parse((string)args[0])];
                }
                catch (Exception e)
                {
                    NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"[color=#e64b40]Error parsing command arguments:[/color] {e.Message}", player);
                    return;
                }

                Packets.ServerHandle.Send.UnitOwnership(unit, player);
                NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"Taken ownership of unit id {unit.netId}", player);
            }));

            clientCommands.register(new AdminCommand("sleep", "", "Sleep all units' collision systems (debug purpose)",
                                                     (player, args) =>
            {
                foreach (Unit unit in NetworkManager.UnitsGroup.Values)
                {
                    unit.Body.Sleeping = true;
                }

                NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"Slept all units.", player);
            }));
            clientCommands.register(new AdminCommand("destroy", "[unitid]", "Destroy the specified unit", (player, args) =>
            {
                Unit unit;
                try
                {
                    unit = NetworkManager.UnitsGroup[int.Parse((string)args[0])];
                }
                catch (Exception e)
                {
                    NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"[color=#e64b40]Error parsing command arguments:[/color] {e.Message}", player);
                    return;
                }

                NetworkManager.DestroyUnit(NetworkManager.loc.SERVER, unit);
                NetworkManager.SendMessage(NetworkManager.loc.SERVER, $"Removed unit id {unit.netId}", player);
            }));
            clientCommands.register(new AdminCommand("players", "", "List all players",
                                                     (player, args) =>
            {
                var msg = String.Empty;
                foreach (Player plr in NetworkManager.PlayersGroup.Values)
                {
                    msg = msg + " id:" + plr.netId + " -> " + plr.Username + (plr.IsHost ? $" [color={Funcs.ColorToHex(Pals.unimportant)}](admin)[/color] " : " ") + "\n";
                }

                msg = msg.Substring(0, msg.Length - 1);

                NetworkManager.SendMessage(NetworkManager.loc.SERVER, msg, player);
            }));
            clientCommands.register(new AdminCommand("rules", "", "List the rules",
                                                     (player, args) =>
            {
                NetworkManager.SendMessage(NetworkManager.loc.SERVER, World.rules.ToString(), player);
            }));
        }
Ejemplo n.º 5
0
        private void DisplayAlert(Vehicle veh, ECamera cam, API.ALPRScanResult r)
        {
            if (veh.Exists())
            {
                if (r.AlertType == EAlertType.Null)
                {
                    return;
                }

                r.LastDisplayed = DateTime.Now;

                if (!Globals.ScanResults.ContainsKey(veh))
                {
                    Globals.ScanResults.Add(veh, r);
                }
                else
                {
                    Globals.ScanResults[veh].LastDisplayed = DateTime.Now;
                }

                if (r.Persona != null)
                {
                    if (veh.HasDriver && veh.Driver.Exists())
                    {
                        Logger.LogTrivialDebug(String.Format("DisplayAlert() -- Setting Persona for driver (lic: {0}), (name: {1})", veh.LicensePlate, r.Persona.FullName));
                        Functions.SetPersonaForPed(veh.Driver, r.Persona);
                    }
                }

                if (r.RegisteredOwner != "")
                {
                    Functions.SetVehicleOwnerName(veh, r.RegisteredOwner);
                }

                string subtitle = "";

                switch (r.AlertType)
                {
                case EAlertType.Stolen_Vehicle:
                    subtitle = "~r~Stolen Vehicle";
                    break;

                case EAlertType.Owner_Wanted:
                    subtitle = "~r~Outstanding Warrant";
                    break;

                case EAlertType.Owner_License_Suspended:
                    subtitle = "~r~License Suspended";
                    break;

                case EAlertType.Owner_License_Expired:
                    subtitle = "~y~License Expired";
                    break;

                case EAlertType.Registration_Expired:
                    subtitle = "~y~Registration Expired";
                    break;

                case EAlertType.Unregistered_Vehicle:
                    subtitle = "~r~Unregistered Vehicle";
                    break;

                case EAlertType.No_Insurance:
                    subtitle = "~r~No Insurance";
                    break;

                case EAlertType.Insurance_Expired:
                    subtitle = "~y~Insurance Expired";
                    break;
                }

                if (r.IsCustomFlag)
                {
                    subtitle = r.Result;
                }

                string mColorName = "";
                try
                {
                    VehicleColor mColor = Stealth.Common.Natives.Vehicles.GetVehicleColors(veh);
                    mColorName = mColor.PrimaryColorName;
                }
                catch
                {
                    mColorName = "";
                }

                if (mColorName != "")
                {
                    mColorName = mColorName + " ";
                }

                string mTitle    = String.Format("ALPR+ [{0}]", GetCameraName(cam));
                string mVehModel = String.Format("{0}{1}", veh.Model.Name.Substring(0, 1).ToUpper(), veh.Model.Name.Substring(1).ToLower());
                string mText     = String.Format("Plate: ~b~{0} ~n~~w~{1}{2}", veh.LicensePlate, mColorName, mVehModel);

                Funcs.DisplayNotification(mTitle, subtitle, mText);

                if (Config.PlayAlertSound)
                {
                    Audio.PlaySound(Audio.ESounds.TimerStop);
                }

                API.Functions.RaiseALPRResultDisplayed(veh, new ALPREventArgs(r, cam));
            }
        }
        public static void LoadFromFile()
        {
            //LoadLua();
            prototypes      = new Dictionary <string, InstalledItem>();
            trashPrototypes = new List <InstalledItem>();
            //prototypesById = new Dictionary<int, string>();
            prototypeRecipes = new Dictionary <string, string>();


            int    unnamedCounter = 0;
            string path           = Application.streamingAssetsPath;

            path = System.IO.Path.Combine(path, "data", "InstalledItems");

            string[] files = Directory.GetFiles(path, "*.json");

            foreach (string file in files)
            {
                string  json = File.ReadAllText(file);
                JObject installedItemJson = JObject.Parse(json);

                //JArray installedItemsArray = (JArray)jo["InstalledItems"];


                //foreach (JObject installedItemJson in installedItemsArray) {

                string name     = Funcs.jsonGetString(installedItemJson["name"], "unnamed_" + unnamedCounter);
                string niceName = Funcs.jsonGetString(installedItemJson["niceName"], name);
                unnamedCounter += 1;
                string sprite   = Funcs.jsonGetString(installedItemJson["sprite"], null);
                float  movement = Funcs.jsonGetFloat(installedItemJson["movementFactor"], 1);
                bool   trash    = Funcs.jsonGetBool(installedItemJson["trash"], false);
                bool   build    = Funcs.jsonGetBool(installedItemJson["build"], false);
                bool   rotate   = Funcs.jsonGetBool(installedItemJson["randomRotation"], false);
                int    w        = Funcs.jsonGetInt(installedItemJson["width"], 1);
                int    h        = Funcs.jsonGetInt(installedItemJson["height"], 1);
                //int id = Funcs.jsonGetInt(installedItemJson["id"], -1);
                bool   enclosesRoom        = Funcs.jsonGetBool(installedItemJson["enclosesRoom"], false);
                string recipeName          = Funcs.jsonGetString(installedItemJson["recipe"], null);
                bool   linked              = Funcs.jsonGetBool(installedItemJson["linked"], false);
                int    inventorySlots      = Funcs.jsonGetInt(installedItemJson["inventorySlots"], 0);
                int    workTileOffsetX     = Funcs.jsonGetInt(installedItemJson["workTileOffsetX"], 0);
                int    workTileOffsetY     = Funcs.jsonGetInt(installedItemJson["workTileOffsetY"], 0);
                float  updateActionCD      = Funcs.jsonGetFloat(installedItemJson["updateActionCountDown"], 0);
                float  updateActionCDRange = Funcs.jsonGetFloat(installedItemJson["updateActionCountDownRange"], 0);
                bool   IsWorkstation       = Funcs.jsonGetBool(installedItemJson["workstation"], false);
                string workRecipeName      = Funcs.jsonGetString(installedItemJson["workRecipe"], null);
                bool   paletteSwap         = Funcs.jsonGetBool(installedItemJson["paletteSwap"], false);
                float  trashSpawnChance    = Funcs.jsonGetFloat(installedItemJson["trashSpawnChance"], 0);
                string deconRecipeName     = Funcs.jsonGetString(installedItemJson["deconstructRecipe"], null);
                int    yClearance          = Funcs.jsonGetInt(installedItemJson["y_clearance"], 0);
                int    xClearance          = Funcs.jsonGetInt(installedItemJson["x_clearance"], 0);
                string workCondition       = Funcs.jsonGetString(installedItemJson["workCondition"], null);
                bool   editOnClick         = Funcs.jsonGetBool(installedItemJson["editOnClick"], false);
                bool   canChangeRecipe     = Funcs.jsonGetBool(installedItemJson["canChangeRecipe"], false);

                //string onPlaced = Funcs.jsonGetString(installedItemJson["onPlaced"], null);
                string onRemoved      = Funcs.jsonGetString(installedItemJson["onRemoved"], null);
                float  powerGenerated = Funcs.jsonGetFloat(installedItemJson["powerGenerated"], 0);
                float  powerUsed      = Funcs.jsonGetFloat(installedItemJson["powerUsed"], 0);



                string luaOnCreate = Funcs.jsonGetString(installedItemJson["onCreate"], null);

                JArray        jsonCanSpawnOn = Funcs.jsonGetArray(installedItemJson, "canSpawnOn");
                List <string> canSpawnOn     = new List <string>();
                if (jsonCanSpawnOn != null)
                {
                    foreach (string tempName in jsonCanSpawnOn)
                    {
                        canSpawnOn.Add(tempName);
                    }
                }


                List <string> sprites          = new List <string>();
                JArray        spritesJsonArray = Funcs.jsonGetArray(installedItemJson, "sprites");
                if (spritesJsonArray != null)
                {
                    foreach (string tempSpriteName in spritesJsonArray)
                    {
                        sprites.Add(tempSpriteName);
                    }
                }

                List <string> availableRecipes = new List <string>();
                JArray        otherRecipes     = Funcs.jsonGetArray(installedItemJson, "availableWorkRecipes");
                if (otherRecipes != null)
                {
                    foreach (string tempRecipeName in otherRecipes)
                    {
                        availableRecipes.Add(tempRecipeName);
                    }
                }
                if (workRecipeName != null && !availableRecipes.Contains(workRecipeName))
                {
                    availableRecipes.Add(workRecipeName);
                }

                List <string> neighbourTypeList = new List <string>();
                if (linked)
                {
                    JArray neighbourTypes = Funcs.jsonGetArray(installedItemJson, "neighbourTypes");//(JArray)installedItemJson["neighbourTypes"];

                    if (neighbourTypes != null)
                    {
                        foreach (string s in neighbourTypes)
                        {
                            neighbourTypeList.Add(s);
                            Debug.Log("added [" + s + "]");
                        }
                    }
                }
                if (!neighbourTypeList.Contains(name))
                {
                    neighbourTypeList.Add(name);
                }



                InstalledItem proto = new InstalledItem();//CreateOneInstalledItemPrototype(name, niceName, sprite, movement, w, h, linked, build, trash, rotate, id, enclosesRoom, recipeName);
                proto.neighbourTypes = neighbourTypeList;
                //proto.roomEnclosure = enclosesRoom;
                proto.niceName = niceName;
                //proto.prototypeId = id;
                proto.type                       = name;
                proto.spriteName                 = sprite;
                proto.movementFactor             = movement;
                proto.width                      = w;
                proto.height                     = h;
                proto.linksToNeighbour           = linked;
                proto.funcPositionValid          = proto.isPositionValid;
                proto.build                      = build;
                proto.trash                      = trash;
                proto.prototype                  = null;
                proto.randomRotation             = rotate;
                proto.roomEnclosure              = enclosesRoom;
                proto.recipeName                 = recipeName;
                proto.inventorySlots             = inventorySlots;
                proto.workTileOffset             = new Vector2(workTileOffsetX, workTileOffsetY);
                proto.updateActionCountDownMax   = updateActionCD;
                proto.updateActionCountDownRange = updateActionCDRange;
                proto.isWorkstation              = IsWorkstation;
                proto.workRecipeName             = workRecipeName;
                proto.paletteSwap                = paletteSwap;
                proto.trashSpawnChance           = trashSpawnChance;
                proto.canSpawnOnTileTypeList     = canSpawnOn;
                proto.deconRecipeName            = deconRecipeName;
                proto.xClearance                 = xClearance;
                proto.yClearance                 = yClearance;
                proto.luaOnCreate                = luaOnCreate;
                proto.workCondition              = workCondition;
                proto.editOnClick                = editOnClick;
                proto.availableRecipes           = availableRecipes;
                proto.canChangeRecipe            = canChangeRecipe;
                proto.powerGenerated             = powerGenerated;
                proto.powerUsed                  = powerUsed;



                proto.onRemoved = onRemoved;
                //proto.inventory = new Inventory(inventorySlots, INVENTORY_TYPE.INSTALLED_ITEM, proto);

                //Debug.Log(proto.ToString() + "\n" + workTileOffsetX + "," + workTileOffsetY);

                if (linked)
                {
                    string n_s    = Funcs.jsonGetString(installedItemJson["neighbour_s"], "");
                    string n_ns   = Funcs.jsonGetString(installedItemJson["neighbour_ns"], "");
                    string n_nsw  = Funcs.jsonGetString(installedItemJson["neighbour_nsw"], "");
                    string n_sw   = Funcs.jsonGetString(installedItemJson["neighbour_sw"], "");
                    string n_nesw = Funcs.jsonGetString(installedItemJson["neighbour_nesw"], "");
                    proto.setLinkedSpriteNames(n_ns, n_nsw, n_s, n_sw, n_nesw);
                }

                if (proto.paletteSwap)
                {
                    List <string> randoSprites = NYDISpriteManager.Instance.GetSpritesStarting(proto.spriteName);
                    //foreach (string s in randoSprites) {
                    //  Debug.Log(s);
                    //}
                    proto.setRandomSprites(randoSprites);
                }
                else if (sprites.Count > 0)
                {
                    proto.setRandomSprites(sprites);
                    //Debug.Log("proto " + proto.type + " has " + proto.randomSprites.Count + " random sprites");
                }

                JArray growth = Funcs.jsonGetArray(installedItemJson, "growth");
                proto.growthStages = new Dictionary <int, Growth>();

                if (growth != null)
                {
                    foreach (JObject growthStage in growth)
                    {
                        int    stage   = Funcs.jsonGetInt(growthStage["stage"], -1);
                        int    length  = Funcs.jsonGetInt(growthStage["length"], -1);
                        string gSprite = Funcs.jsonGetString(growthStage["sprite"], null);
                        string gdecon  = Funcs.jsonGetString(growthStage["deconstructRecipe"], deconRecipeName);

                        if (stage >= 0 && length > 0 && gSprite != null)
                        {
                            proto.growthStages[stage] = new Growth(stage, length, gSprite, gdecon);
                        }
                    }
                }
                if (proto.growthStages.Count > 0)
                {
                    proto.growthStage = 0;
                    proto.itemParameters.SetInt("maxGrowthStage", proto.growthStages.Values.Max(e => e.stage));
                }
                else
                {
                    proto.growthStage = -1;
                }


                JArray parameters = Funcs.jsonGetArray(installedItemJson, "parameters");
                if (parameters != null)
                {
                    foreach (JObject prm in parameters)
                    {
                        string prmName = Funcs.jsonGetString(prm["name"], null);
                        string prmType = Funcs.jsonGetString(prm["type"], null);

                        if (prmName != null && prmType != null)
                        {
                            switch (prmType)
                            {
                            case "float":
                                float prmValueFloat = Funcs.jsonGetFloat(prm["value"], 0);
                                proto.itemParameters.SetFloat(prmName, prmValueFloat);
                                break;

                            case "int":
                                int prmValueInt = Funcs.jsonGetInt(prm["value"], 0);
                                proto.itemParameters.SetInt(prmName, prmValueInt);
                                break;

                            case "string":
                                string prmValueString = Funcs.jsonGetString(prm["value"], "");
                                proto.itemParameters.Set(prmName, prmValueString);
                                break;

                            case "bool":
                                bool prmValueBool = Funcs.jsonGetBool(prm["value"], false);
                                proto.itemParameters.SetBool(prmName, prmValueBool);
                                break;
                            }
                        }
                    }
                }

                string updateActionName = Funcs.jsonGetString(installedItemJson["updateAction"], null);
                if (updateActionName != null)
                {
                    proto.updateActions = new List <string>();
                    proto.updateActions.Add(updateActionName);
                }

                string enterRequestionName = Funcs.jsonGetString(installedItemJson["onEnterRequested"], null);

                if (enterRequestionName != null)
                {
                    proto.enterRequestedFunc = enterRequestionName;
                }

                //if (name == "installed::door") {
                //  proto.enterRequested += InstalledItemActions.Door_EnterRequested;
                //}
                //  proto.updateActions += InstalledItemActions.Door_UpdateActions;


                //} else if (name == "installed::stockpile") {
                //  proto.updateActions += InstalledItemActions.Stockpile_UpdateActions;
                //} else if (IsWorkstation) {
                //  proto.updateActions += InstalledItemActions.Workstation_UpdateActions;
                //}
                prototypes.Add(proto.type, proto);
                //prototypesById.Add(proto.prototypeId, proto.type);
                prototypeRecipes.Add(proto.type, proto.recipeName);
                proto.recipe = GetRecipe(proto.type);
            }
            //InstalledItem proto = InstalledItemProto("installed::wall", "walls_none", 0, 1, 1,true);
            //

            foreach (string ss in prototypes.Keys)
            {
                InstalledItem item = prototypes[ss];
                if (item.trash)
                {
                    trashPrototypes.Add(item);
                }
            }
        }
Ejemplo n.º 7
0
        public override async System.Threading.Tasks.Task Run()
        {
            // Initial await
            await ClockAsync();

            double[] positions  = new double[data_size];
            double[] velocities = new double[data_size];

            for (int i = 0; i < data_size; i++)
            {
                if (init_position.valid && init_velocity.valid)
                {
                    // Get data from master simulation process
                    ulong position = init_position.val;
                    positions[i] = Funcs.FromUlong(position);
                    ulong velocity = init_velocity.val;
                    velocities[i] = Funcs.FromUlong(velocity);

                    // Write initial data to position ram
                    position_ramctrl.Address   = i;
                    position_ramctrl.Data      = position;
                    position_ramctrl.IsWriting = true;
                    position_ramctrl.Enabled   = true;

                    // Write initial data to velocity ram
                    init_velocity_ramctrl.Address = i;
                    // Initial value is 0
                    init_velocity_ramctrl.Data      = velocity;
                    init_velocity_ramctrl.IsWriting = true;
                    init_velocity_ramctrl.Enabled   = true;
                }
                else
                {
                    i--;
                }
                await ClockAsync();
            }

            // MD loop
            for (int k = 0; k < (uint)Number_of_loops.n; k++)
            {
                bool running = true;
                position_ramctrl.Enabled        = false;
                position_ramctrl.Data           = 0;
                position_ramctrl.IsWriting      = false;
                init_velocity_ramctrl.Enabled   = false;
                init_velocity_ramctrl.Data      = 0;
                init_velocity_ramctrl.IsWriting = false;
                acc_ready.val        = data_size;
                acc_ready.valid      = true;
                velocity_reset.valid = true;
                position_reset.valid = true;
                await ClockAsync();

                acc_ready.valid      = false;
                velocity_reset.valid = false;
                position_reset.valid = false;


                // Calculating data for verifying results
                double[] accelerations = new double[data_size];
                for (long i = 0; i < data_size; i++)
                {
                    for (long j = i + 1; j < data_size; j++)
                    {
                        double result = Sim_Funcs.Acceleration_2d_Calc(positions[i], positions[j]);
                        accelerations[i] += result;
                        accelerations[j] += -result;
                    }
                }

                double[] updated_velocity = new double[data_size];
                // Calculate data for tests
                for (long i = 0; i < data_size; i++)
                {
                    // Initial velocity is 0
                    double update_result = Sim_Funcs.Update_Data_Calc(velocities[i], accelerations[i], timestep);
                    updated_velocity[i] = update_result;
                }

                double[] updated_positions = new double[data_size];
                // Calculate data for tests
                for (long i = 0; i < data_size; i++)
                {
                    double update_result = Sim_Funcs.Update_Data_Calc(positions[i], updated_velocity[i], timestep);
                    updated_positions[i] = update_result;
                }

                int  m          = 0;
                int  n          = 0;
                bool data_ready = false;

                while (running)
                {
                    if (finished.valid)
                    {
                        data_ready = true;
                    }

                    if (data_ready)
                    {
                        if (m < data_size)
                        {
                            position_ramctrl.Enabled   = true;
                            position_ramctrl.Data      = 0;
                            position_ramctrl.IsWriting = false;
                            position_ramctrl.Address   = m;
                            m++;
                        }
                        else
                        {
                            position_ramctrl.Enabled = false;
                        }

                        if (m - n > 2 || m >= data_size)
                        {
                            double input_result = Funcs.FromUlong(position_ramresult.Data);
                            if (Math.Abs(updated_positions[n] - input_result) > 0.00001f)
                            {
                                Console.WriteLine("Update position result - Got {0}, expected {1} at {2}",
                                                  input_result, updated_positions[n], n);
                            }
                            n++;
                        }
                        if (n >= data_size)
                        {
                            running    = false;
                            data_ready = false;
                            positions  = updated_positions;
                            velocities = updated_velocity;
                        }
                    }
                    await ClockAsync();
                }
                Console.WriteLine("Loop {0} finished", k);
            }
            sim_finished.valid = true;
        }
Ejemplo n.º 8
0
        public void Action()
        {
            if (SkillsCount == 0)
            {
                return;
            }

            if (Npc.Attack != null && !Npc.Attack.IsFinished)
            {
                return;
            }

            lock (Lock)
            {
                Creature target  = null;
                int      maxHate = int.MinValue;

                foreach (var hate in Hate)
                {
                    if (hate.Key.Position.DistanceTo(Npc.Position) > 1500 || hate.Key.LifeStats.IsDead())
                    {
                        Damage.Remove(hate.Key);
                        Hate.Remove(hate.Key);
                        return;
                    }

                    if (hate.Value > maxHate)
                    {
                        target  = hate.Key;
                        maxHate = hate.Value;
                    }
                }

                Npc.Target = target;
            }

            if (Npc.Target == null)
            {
                return;
            }

            if (SelectedSkill == null)
            {
                if (Funcs.Random().Next(0, 1000) < 250)
                {
                    Global.SkillEngine.UseSkill(Npc, MoveSkills[Funcs.Random().Next(0, MoveSkills.Count)]);
                    return;
                }

                SelectedSkill = AttackSkills[Funcs.Random().Next(0, AttackSkills.Count)];
            }

            int distance = SeUtils.GetAttackDistance(SelectedSkill);

            if (Npc.Position.DistanceTo(Npc.Target.Position.X, Npc.Target.Position.Y) > distance + 10)
            {
                long now = Funcs.GetCurrentMilliseconds();
                if (now > LastMoveUts + 100)
                {
                    LastMoveUts = now;
                    ((NpcAi)Npc.Ai).MoveController.MoveTo(Npc.Target.Position, distance);
                }
                return;
            }

            ((NpcAi)Npc.Ai).MoveController.Stop();

            Global.SkillEngine.UseSkill(Npc, SelectedSkill);
            SelectedSkill = null;
        }
Ejemplo n.º 9
0
        private void UpdateMoney()
        {
            interestRate = interestRateMarket.GetNextValue();

            money = money + (money * (interestRate / 100f)); //Mathf.Pow((1f + (((interestRate) / 100f) / SECONDS_PER_DAY)), SECONDS_PER_DAY);
                                                             //+ (money * interestRate * Time.deltaTime);


            Text t = cashText.GetComponent <Text>();


            t.text  = "<color=\"" + (money < 0 ? negativeBalanceColourString : positiveBalanceColourString) + "\">" + Funcs.PadPair(20, "money", string.Format("{0:00.00}", money)) + "</color>";
            t.text += "\n" + Funcs.PadPair(20, "interest", string.Format("{0:0.000}", 100.0 * interestRate));
            t.text += "\n" + "<color=\"" + (world.usedPower >= world.currentPower ? negativeBalanceColourString : positiveBalanceColourString) + "\">" +
                      Funcs.PadPair(20, "power", string.Format("{0:0.00}kW", world.currentPower)) + "</color>";

            t.text += "\n" + "<color=\"" + (world.usedPower >= world.currentPower ? negativeBalanceColourString : positiveBalanceColourString) + "\">" +
                      Funcs.PadPair(20, "used", string.Format("{0:0.00}kW", world.usedPower)) + "</color>";

            //if (money < 0) {
            //  t.color = negativeBalanceColour;
            //} else {
            //  t.color = positiveBalanceColour;
            //}
        }
Ejemplo n.º 10
0
 // Deirvative rule
 public override Function Derivative()
 {
     return((new Constant(1) - Funcs.Cth(InnerF)) ^ (new Constant(2) * InnerF.Derivative()));
 }
Ejemplo n.º 11
0
        public void FilterDataDrivenTest <T>(List <T> list, Predicate <T> predicate, List <T> expected)
        {
            var actual = Funcs.Filter <T>(list, predicate);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 12
0
        public void When_ObservableVectorStringChanged()
        {
            var count          = 0;
            var containerCount = 0;
            var panel          = new StackPanel();

            panel.ForceLoaded();

            var source = new ObservableVector <string>()
            {
                "1", "2", "3"
            };

            Style BuildContainerStyle() =>
            new Style(typeof(Windows.UI.Xaml.Controls.ListViewItem))
            {
                Setters =
                {
                    new Setter <ContentControl>("Template",                                t =>
                                                t.Template = Funcs.Create(() => {
                        containerCount++;
                        return(new Grid
                        {
                            Children =
                            {
                                new ContentPresenter()
                                .Apply(p => {
                                    p.SetBinding(ContentPresenter.ContentTemplateProperty, new Binding()
                                    {
                                        Path = "ContentTemplate",                          RelativeSource = RelativeSource.TemplatedParent
                                    });
                                    p.SetBinding(ContentPresenter.ContentProperty,         new Binding()
                                    {
                                        Path = "Content",                                  RelativeSource = RelativeSource.TemplatedParent
                                    });
                                })
                            }
                        });
                    })
                                                )
                }
            };

            var SUT = new ListView()
            {
                ItemsPanelRoot         = panel,
                InternalItemsPanelRoot = panel,
                ItemContainerStyle     = BuildContainerStyle(),
                ItemTemplate           = new DataTemplate(() =>
                {
                    count++;
                    return(new Border());
                })
            };

            Assert.AreEqual(0, count);
            Assert.AreEqual(0, containerCount);
            Assert.AreEqual(0, containerCount);

            SUT.ItemsSource = source;
            Assert.AreEqual(3, count);
            Assert.AreEqual(3, containerCount);
            Assert.AreEqual(3, containerCount);

            source.Add("4");
            Assert.AreEqual(4, count);
            Assert.AreEqual(4, containerCount);
            Assert.AreEqual(4, containerCount);

            source.Remove("1");
            Assert.AreEqual(4, count);
            Assert.AreEqual(4, containerCount);
            Assert.AreEqual(4, containerCount);

            source[0] = "5";
            // Data template is not recreated because of pooling
            Assert.AreEqual(4, count);
            // The item container style is reapplied (not cached)
            Assert.AreEqual(5, containerCount);
        }
Ejemplo n.º 13
0
        protected override void OnTick()
        {
            if (ready.valid)
            {
                amount_of_data   = ready.val;
                number_of_blocks = amount_of_data / (ulong)cache_size;

                // Output is not ready
                output.valid = false;

                initial_clock_cycle = true;


                index_cache_A1 = 0;
                index_cache_A2 = 0;
                index_cache_B  = 1;
                index_cache_C  = 2;
                cache_A1_or_A2 = true; // A1 == true, A2 == false
                copy_cache_A   = false;

                current_i = 0;
                current_j = 0;

                current_cache_index_i = 0;
                current_cache_index_j = 0;
                current_index_i       = 0;
                current_index_j       = 1;
                last_cache_blocks     = false;

                last_cache_index_i = 0;
                last_cache_index_j = 0;

                dirty_blocks = 0;

                /*  NOTE: The Acceleration manager will never write to more than
                 *  there are amount of data. Therefore it is only a problem when
                 *  we want to read a new cacheline from RAM since it will try to
                 *  read from the elements that does not exists, because it will
                 *  always read cache_size number of items. So the AM does not
                 *  need to handle any cases where the data does not fit in the
                 *  cache lines. Instead the RAM should be changed to handle any
                 *  read that wants to read at an unknown address. This should
                 *  fix our problem.
                 */
            }
            if (initial_clock_cycle)
            {
                running = true;
            }
            if (!running)
            {
                output.valid = false;
            }

            if (acceleration_input.valid && running)
            {
                output.valid = false;

                // Find current i and j
                if (current_j == amount_of_data - 1)
                {
                    //    j is at the end of data and i is moved one forward
                    current_i++;
                    current_j = current_i + 1;
                }
                else
                {
                    current_j++;
                }
                if (current_i == current_j)
                {
                    Console.WriteLine("Something wrong - i is equal to j");
                    running = false;
                }


                // last clock cycle result
                last_cache_index_i = current_cache_index_i;
                last_cache_index_j = current_cache_index_j;
                ulong last_index_i = current_index_i;
                ulong last_index_j = current_index_j;

                // Calculate current cacheblock
                current_cache_index_i = current_i / cache_size;
                current_cache_index_j = current_j / cache_size;
                // Calculate which index within the cache block
                current_index_i = current_i % cache_size;
                current_index_j = current_j % cache_size;

                // if j changes cache block
                if (last_cache_index_j != current_cache_index_j ||
                    last_cache_index_i != current_cache_index_i)
                {
                    // If j was not in cache A
                    if (last_cache_index_j != current_cache_index_i)
                    {
                        write_cache   = true;
                        write_cache_B = last_cache_index_j == index_cache_B;
                        write_cache_C = last_cache_index_j == index_cache_C;
                    }

                    // j moves to last block
                    if (current_cache_index_j == number_of_blocks - 1)
                    {
                        // i moves to a new block next time it moves
                        if (current_index_i == cache_size - 1)
                        {
                            copy_cache_A = true;
                        }
                        // i does not move a block
                        else
                        {
                            copy_cache_A = false;
                        }
                        if (cache_A1_or_A2)
                        {
                            next_cache_address = index_cache_A1 + 1;
                        }
                        else
                        {
                            next_cache_address = index_cache_A2 + 1;
                        }
                        request_cache = true;
                    }
                    // j wraps around to i
                    else if (current_cache_index_j == current_cache_index_i)
                    {
                        request_cache = false;
                        write_cache   = false;
                        // If i moves cache block
                        if (!write_cache_A && last_cache_index_i != current_cache_index_i)
                        {
                            request_cache      = true;
                            write_cache        = true;
                            next_cache_address = current_cache_index_j + 1;
                            write_cache_A      = true;
                            cache_A1_or_A2     = !cache_A1_or_A2;
                        }
                        else if (write_cache_A && last_cache_index_i != current_cache_index_i)
                        {
                            Console.WriteLine("Warning - Cache A not written in time");
                        }
                    }
                    // j does not move to last block
                    else
                    {
                        next_cache_address = current_cache_index_j + 1;
                        if (next_cache_address <= dirty_blocks)
                        {
                            request_cache = true;
                        }
                    }
                    // At the last 3 cache blocks before the end of data
                    // This we already have in cache and therefore we do not
                    // need to write or request the data.
                    if (current_cache_index_i >= number_of_blocks - 3)
                    {
                        request_cache     = false;
                        write_cache       = false;
                        write_cache_A     = false;
                        last_cache_blocks = true;
                        // If i moves block
                        if (current_cache_index_i != last_cache_index_i)
                        {
                            //  If i was in an A cache
                            if (last_cache_index_i == index_cache_A1 || last_cache_index_i == index_cache_A2)
                            {
                                write_cache   = true;
                                write_cache_A = true;
                                write_cache_B = false;
                                write_cache_C = false;
                                // If only two caches it is necessary to change
                                // cache here, so the right cache is written to
                                // ram
                                if (amount_of_data <= cache_size * 2)
                                {
                                    cache_A1_or_A2 = !cache_A1_or_A2;
                                }
                            }
                            else
                            {
                                write_cache   = true;
                                write_cache_B = last_cache_index_i == index_cache_B;
                                write_cache_C = last_cache_index_i == index_cache_C;
                                output.valid  = true;
                            }
                        }
                    }

                    if (dirty_blocks < number_of_blocks)
                    {
                        dirty_blocks++;
                    }
                }
                // TODO: Should be rewritten for better solution
                if (amount_of_data <= cache_size)
                {
                    if (current_j == amount_of_data - 1 && current_i == 0)
                    {
                        dirty_blocks++;
                    }
                }

                /*  NOTE: A request cache will never happen without a write cache
                 *  since we never want to request something if we havent written
                 *  anything yet. Also everytime we request something, we have to
                 *  replace it with something already in the cache, and therefore
                 *  we must write this to RAM before we can override the data.
                 */
                if (request_cache)
                {
                    acc_ramctrl.Enabled = true;
                    acc_ramctrl.Address = next_cache_address;
                    for (int i = 0; i < (int)cache_size; i++)
                    {
                        acc_ramctrl.Data[i] = 0;
                    }
                    acc_ramctrl.IsWriting = false;

                    received_data_address = next_cache_address;
                    request_cache         = false;
                    write_cache           = true;
                    receive_cache         = true;
                }
                else if (write_cache)
                {
                    if (write_cache_B)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_B[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_B;
                        acc_ramctrl.IsWriting = true;

                        if (next_cache_address > dirty_blocks)
                        {
                            index_cache_B = next_cache_address;
                        }
                    }
                    else if (write_cache_C)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_C[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_C;
                        acc_ramctrl.IsWriting = true;

                        if (next_cache_address > dirty_blocks)
                        {
                            index_cache_C = next_cache_address;
                        }
                    }
                    else if (write_cache_A)
                    {
                        if (cache_A1_or_A2)
                        {
                            for (int j = 0; j < (int)cache_size; j++)
                            {
                                acc_ramctrl.Data[j] = Funcs.FromDouble(cache_A2[j]);
                            }

                            acc_ramctrl.Enabled   = true;
                            acc_ramctrl.Address   = index_cache_A2;
                            acc_ramctrl.IsWriting = true;
                        }
                        else
                        {
                            for (int j = 0; j < (int)cache_size; j++)
                            {
                                acc_ramctrl.Data[j] = Funcs.FromDouble(cache_A1[j]);
                            }

                            acc_ramctrl.Enabled   = true;
                            acc_ramctrl.Address   = index_cache_A1;
                            acc_ramctrl.IsWriting = true;
                        }
                        output.valid = true;
                    }
                    write_cache = false;
                }
                else if (receive_cache)
                {
                    if (write_cache_B)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            if (copy_cache_A && !cache_A1_or_A2)
                            {
                                cache_A1[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_A1 = received_data_address;
                                if (received_data_address < number_of_blocks - 3)
                                {
                                    index_cache_B = received_data_address;
                                }
                            }
                            else if (copy_cache_A && cache_A1_or_A2)
                            {
                                cache_A2[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_A2 = received_data_address;
                                if (received_data_address < number_of_blocks - 3)
                                {
                                    index_cache_B = received_data_address;
                                }
                            }
                            else
                            {
                                cache_B[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_B = received_data_address;
                            }
                        }
                        copy_cache_A  = false;
                        write_cache_B = false;
                    }
                    else if (write_cache_C)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            if (copy_cache_A && !cache_A1_or_A2)
                            {
                                cache_A1[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_A1 = received_data_address;
                                if (received_data_address < number_of_blocks - 3)
                                {
                                    index_cache_C = received_data_address;
                                }
                            }
                            else if (copy_cache_A && cache_A1_or_A2)
                            {
                                cache_A2[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_A2 = received_data_address;
                                if (received_data_address < number_of_blocks - 3)
                                {
                                    index_cache_C = received_data_address;
                                }
                            }
                            else
                            {
                                cache_C[j]    = Funcs.FromUlong(acc_ramresult.Data[j]);
                                index_cache_C = received_data_address;
                            }
                        }
                        copy_cache_A  = false;
                        write_cache_C = false;
                    }
                    else if (write_cache_A)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            if (!cache_A1_or_A2)
                            {
                                //  Written cache A1
                                if (index_cache_B == index_cache_A2)
                                {
                                    cache_B[j] = Funcs.FromUlong(acc_ramresult.Data[j]);
                                }
                                else if (index_cache_C == index_cache_A2)
                                {
                                    cache_C[j] = Funcs.FromUlong(acc_ramresult.Data[j]);
                                }
                            }
                            else
                            {
                                // Written cache A2
                                if (index_cache_B == index_cache_A1)
                                {
                                    cache_B[j] = Funcs.FromUlong(acc_ramresult.Data[j]);
                                }
                                else if (index_cache_C == index_cache_A1)
                                {
                                    cache_C[j] = Funcs.FromUlong(acc_ramresult.Data[j]);
                                }
                            }
                        }
                        // Update cache index
                        if (!cache_A1_or_A2)
                        {
                            if (index_cache_B == index_cache_A2)
                            {
                                index_cache_B = received_data_address;
                            }
                            else if (index_cache_C == index_cache_A2)
                            {
                                index_cache_C = received_data_address;
                            }
                        }
                        else
                        {
                            if (index_cache_B == index_cache_A1)
                            {
                                index_cache_B = received_data_address;
                            }
                            else if (index_cache_C == index_cache_A1)
                            {
                                index_cache_C = received_data_address;
                            }
                        }
                        write_cache_A = false;
                    }
                    receive_cache = false;
                }

                // Writing j to cache block
                if (current_cache_index_j >= dirty_blocks)
                {
                    if (current_cache_index_j == index_cache_A1)
                    {
                        cache_A1[current_index_j] = -Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_A2)
                    {
                        cache_A2[current_index_j] = -Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_B)
                    {
                        cache_B[current_index_j] = -Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_C)
                    {
                        cache_C[current_index_j] = -Funcs.FromUlong(acceleration_input.val);
                    }
                }
                else
                {
                    // If A, B or C cache is dirty and have been written too
                    // it is necessary to accumulate the results.
                    if (current_cache_index_j == index_cache_A1)
                    {
                        cache_A1[current_index_j] = cache_A1[current_index_j] - Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_A2)
                    {
                        cache_A2[current_index_j] = cache_A2[current_index_j] - Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_B)
                    {
                        cache_B[current_index_j] = cache_B[current_index_j] - Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_j == index_cache_C)
                    {
                        cache_C[current_index_j] = cache_C[current_index_j] - Funcs.FromUlong(acceleration_input.val);
                    }
                }
                // i will always write in a field that j have already written to
                // unless it is the first initial cycle with input data and so
                // nothing has been written yet.
                // Therefore at the initial clock cycle we simply write to the cache
                // and thereafter we always accumulate the data
                if (initial_clock_cycle)
                {
                    cache_A1[current_index_i] = Funcs.FromUlong(acceleration_input.val);
                    initial_clock_cycle       = false;
                }
                else if (last_cache_blocks)
                {
                    if (current_cache_index_i == index_cache_A1)
                    {
                        cache_A1[current_index_i] = cache_A1[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_i == index_cache_A2)
                    {
                        cache_A2[current_index_i] = cache_A2[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_i == index_cache_B)
                    {
                        cache_B[current_index_i] = cache_B[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                    else if (current_cache_index_i == index_cache_C)
                    {
                        cache_C[current_index_i] = cache_C[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                }
                else
                {
                    if (cache_A1_or_A2)
                    {
                        cache_A1[current_index_i] = cache_A1[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                    else
                    {
                        cache_A2[current_index_i] = cache_A2[current_index_i] + Funcs.FromUlong(acceleration_input.val);
                    }
                }
            }
            else if (running)
            {
                // When at the last elements of the data, it is necessary to
                // write to RAM since the loop will not continue after the last
                // elements
                if (current_i == amount_of_data - 2)
                {
                    // Console.WriteLine("Finished acceleration accumulation");

                    write_cache_B = current_cache_index_i == index_cache_B;
                    write_cache_C = current_cache_index_i == index_cache_C;
                    write_cache_A = current_cache_index_i == index_cache_A1 || current_cache_index_i == index_cache_A2;
                    output.valid  = true;
                    if (write_cache_B)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_B[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_B;
                        acc_ramctrl.IsWriting = true;
                    }
                    else if (write_cache_C)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_C[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_C;
                        acc_ramctrl.IsWriting = true;
                    }
                    else if (write_cache_A && cache_A1_or_A2)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_A1[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_A1;
                        acc_ramctrl.IsWriting = true;
                    }
                    else if (write_cache_A && !cache_A1_or_A2)
                    {
                        for (int j = 0; j < (int)cache_size; j++)
                        {
                            acc_ramctrl.Data[j] = Funcs.FromDouble(cache_A2[j]);
                        }

                        acc_ramctrl.Enabled   = true;
                        acc_ramctrl.Address   = index_cache_A2;
                        acc_ramctrl.IsWriting = true;
                    }
                    write_cache = false;
                }
                running = false;
            }
        }
Ejemplo n.º 14
0
        public static Dictionary <string, object> getMethods(object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            Dictionary <string, object> tempd = new Dictionary <string, object>();

            foreach (var m in obj.GetType().GetMethods())
            {
                if ((!new Regex(RegexStr1).Match(m.DeclaringType.Name).Success) && (!new Regex(RegexStr2).Match(m.DeclaringType.Name).Success) && m.ToString().Substring(0, 4) == RegexStr3 && Regex.IsMatch(m.Name[0].ToString(), "[A-Z]"))
                {
                    if (m.GetParameters().Length == 0)
                    {
                        Funcs funcs1 = new Funcs();

                        funcs1.Func = () =>
                        {
                            m.Invoke(obj, null);
                            return(null);
                        };

                        foreach (var ca in m.CustomAttributes)
                        {
                            if (ca.AttributeType.Name == "Initialize")
                            {
                                if (ca.ConstructorArguments.Count == 1)
                                {
                                    if ((int)(ca.ConstructorArguments[0].Value) == 1)
                                    {
                                        //Do Nothing
                                    }
                                    else if ((int)(ca.ConstructorArguments[0].Value) == 2)
                                    {
                                        funcs1.RunFunc();
                                    }
                                    else if ((int)(ca.ConstructorArguments[0].Value) == 4)
                                    {
                                        Async.RunFuncAsync(funcs1.RunFunc, null);
                                    }
                                }

                                break;
                            }
                        }

                        if (tempd.ContainsKey(m.Name))
                        {
                            Debug.WriteLine("■■■找到重复键:" + m.Name + "。已采用默认值。");
                        }
                        else
                        {
                            tempd.Add(m.Name, new Action(funcs1.RunFunc));
                        }
                    }
                    else
                    {
                        Funcs  funcs2 = new Funcs();
                        object param  = m.GetParameters()[0];

                        funcs2.FuncWithParam = (pam) =>
                        {
                            object[] objs = new object[1];
                            objs[0] = pam;
                            m.Invoke(obj, objs);
                            return(null);
                        };
                        if (tempd.ContainsKey(m.Name))
                        {
                            Debug.WriteLine("■■■找到重复键:" + m.Name + "。已采用默认值。");
                        }
                        else
                        {
                            tempd.Add(m.Name, new Action <object>(funcs2.RunFuncWithParam));
                        }
                    }
                }
            }
            return(tempd);
        }
        private void OnSessionStart(object sender, SessionStartEventArgs e)
        {
            Trace.TraceInformation("Session starting");

            Directory.CreateDirectory(mTempFolder);
            mDataFilePath = Path.Combine(mTempFolder, "TestSessionEvents" + DataFile.ProfileDataFileExtension);

            var outgoingMessageSource = new ReplaySubject <RequestMessage>();

            mSendMessage = outgoingMessageSource.OnNext;

            var outgoingMessages = outgoingMessageSource
                                   .Select(msg => msg.ToByteArray())
                                   .Concat(Observable.Never <byte[]>()); // don't close pipe from this end

            var incomingRawMessageStreams = ProfilerCommunication.CreateRawChannel(mProcessSetup.PipeName, outgoingMessages)
                                            .Publish();

            var incomingMessageStreams = incomingRawMessageStreams
                                         .Select(rawMessages => rawMessages.Select(EventMessage.Parser.ParseFrom));

            var receivedClientEventStreams = incomingMessageStreams
                                             .Select(messages => messages
                                                     .Where(m => m.EventCase == EventMessage.EventOneofCase.ClientEvent)
                                                     .Select(m => m.ClientEvent)
                                                     .Replay(1));

            var latestEndedTest =
                Observable.Defer(() =>
            {
                var returnNull          = Observable.Return((string)null);
                var latestTestPerStream = new Dictionary <int, string>();
                return(receivedClientEventStreams
                       .SelectMany((clientEvents, streamNumber) => clientEvents
                                   .Where(ev => ev.Id == cEndTestCaseEventId)
                                   .Select(ev => ev.Name)
                                   .StartWith(string.Empty)
                                   .Concat(returnNull)
                                   .Select(testName => (streamNumber, testName)))
                       .Select(item =>
                {
                    latestTestPerStream[item.streamNumber] = item.testName;
                    if (item.testName is null)
                    {
                        latestTestPerStream.Remove(item.streamNumber);
                    }

                    int count = latestTestPerStream.Values.Distinct().Take(2).Count();
                    if (count == 0)
                    {
                        return null;
                    }
                    else if (count == 1)
                    {
                        return latestTestPerStream.Values.First();
                    }
                    else
                    {
                        return string.Empty;
                    }
                })
                       .Where(testName => testName != string.Empty));
            })
                .StartWith((string)null)
                .Replay(1);

            latestEndedTest.Connect();
            mLatestEndedTestName = latestEndedTest.AsObservable();

            var fileWriter = Observable.Using(() => OpenDataFile(mDataFilePath),
                                              writer =>
            {
                return(incomingRawMessageStreams
                       .TakeUntil(Observable.FromEvent(h => mSessionEnded += h, h => mSessionEnded -= h))
                       .Merge()
                       .Do(msg =>
                {
                    writer.Write(msg.Length);
                    writer.Write(msg);
                })
                       .LastOrDefaultAsync()
                       .Select(Funcs <byte[]> .DefaultOf <Unit>()));
            })
                             .Publish();

            fileWriter.Connect();
            mFileWriterThing = fileWriter.AsObservable();

            incomingRawMessageStreams.Connect();
        }
Ejemplo n.º 16
0
        public override async System.Threading.Tasks.Task Run()
        {
            await ClockAsync();

            bool   running = true;
            Random rnd     = new Random();


            //// Testing data

            // Generate random data for testing
            double[] position_data = new double[data_size];
            for (long i = 0; i < data_size; i++)
            {
                long random_number = rnd.Next(10, 1000);
                if (!position_data.Contains((double)random_number))
                {
                    position_data[i] = (double)random_number;
                }
                else
                {
                    i--;
                }
            }

            // Creating random or non-random data variables as the external
            // variables in the formula
            double[] random_velocity_data = new double[data_size];
            double[] velocity_data        = new double[data_size];

            // Generate random data for testing
            for (ulong i = 0; i < data_size; i++)
            {
                long random_number = rnd.Next(10, 100);
                if (!random_velocity_data.Contains((double)random_number))
                {
                    random_velocity_data[i] = (double)random_number;
                }
                else
                {
                    i--;
                }
            }

            // Generate data for testing
            for (ulong i = 0; i < data_size; i++)
            {
                velocity_data[i] = i + 1;
            }


            // Write initial data to ram
            for (int i = 0; i < data_size; i++)
            {
                // Data points
                data_point_ramctrl.Enabled   = true;
                data_point_ramctrl.Address   = i;
                data_point_ramctrl.Data      = Funcs.FromDouble(position_data[i]);
                data_point_ramctrl.IsWriting = true;

                // External variable data points
                velocity_data_point_ramctrl.Enabled   = true;
                velocity_data_point_ramctrl.Address   = i;
                velocity_data_point_ramctrl.Data      = Funcs.FromDouble(random_velocity_data[i]);
                velocity_data_point_ramctrl.IsWriting = true;

                await ClockAsync();
            }
            velocity_data_point_ramctrl.Enabled   = false;
            velocity_data_point_ramctrl.IsWriting = false;
            data_point_ramctrl.Enabled            = false;
            data_point_ramctrl.IsWriting          = false;

            double[] updated_data_points = new double[data_size];
            // Calculate data for tests
            for (long i = 0; i < data_size; i++)
            {
                double update_result = Sim_Funcs.Update_Data_Calc(position_data[i], random_velocity_data[i], timestep);
                updated_data_points[i] = update_result;
            }

            sim_ready.valid = true;
            await ClockAsync();

            sim_ready.valid  = false;
            data_ready.valid = true;
            await ClockAsync();

            data_ready.valid = false;

            int  k = 0;
            int  n = 0;
            bool receive_data_ready = false;

            while (running)
            {
                if (finished.valid)
                {
                    receive_data_ready = true;
                }

                if (receive_data_ready)
                {
                    if (k < random_velocity_data.Length)
                    {
                        data_point_ramctrl.Enabled   = true;
                        data_point_ramctrl.Data      = 0;
                        data_point_ramctrl.IsWriting = false;
                        data_point_ramctrl.Address   = k;
                        k++;
                    }
                    else
                    {
                        data_point_ramctrl.Enabled = false;
                    }

                    if (k - n > 2 || k >= random_velocity_data.Length)
                    {
                        double input_result = Funcs.FromUlong(data_point_ramresult.Data);

                        // Assertion for unittest
                        System.Diagnostics.Debug.Assert((Math.Abs(updated_data_points[n] - input_result) < 1 / (Math.Pow(10, 7))), "SME acceleration did not match C# position_update");


                        // if(updated_data_points[n] - input_result > 0.0f)
                        //     Console.WriteLine("Update data result - Got {0}, expected {1} at {2}",
                        //             input_result, updated_data_points[n], n);
                        n++;
                    }
                    if (n >= random_velocity_data.Length)
                    {
                        running            = false;
                        receive_data_ready = false;
                        // TODO: Add looping functionality - see Lennard_Jones.Simulations
                    }
                }
                await ClockAsync();
            }
        }
Ejemplo n.º 17
0
 // Deirvative rule
 public override Function Derivative()
 {
     return(new Constant(1) / Funcs.Sq(new Constant(1) - (InnerF ^ new Constant(2))) * InnerF.Derivative());
 }
Ejemplo n.º 18
0
        // 获取用户类型列表
        private string getTypeList()
        {
            pagingJson paging = new pagingJson();

            try
            {
                //获取Datatables发送的参数 必要
                int draw = Int32.Parse(Funcs.Get("draw"));//请求次数 这个值作者会直接返回给前台

                //排序
                string orderColumn = Funcs.Get("order[0][column]"); //那一列排序,从0开始
                string orderDir    = Funcs.Get("order[0][dir]");    //ase desc 升序或者降序

                //搜索
                string userType = GlobalObject.unescape(Funcs.Get("userType"));//搜索框值

                //分页
                int start  = Int32.Parse(Funcs.Get("start"));  //第一条数据的起始位置
                int length = Int32.Parse(Funcs.Get("length")); //每页显示条数

                // where条件,排序条件
                string strWhere = "parentId=1", strOrderBy = "";
                if (userType != null && userType != "")
                {
                    strWhere += " and paramsName like '%" + Funcs.ToSqlString(userType) + "%'";
                }
                if (orderColumn != "" && orderDir != "")
                {
                    strOrderBy = Funcs.Get("columns[" + orderColumn + "][data]") + " " + orderDir;
                }

                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@param_table", SqlDbType.Text)
                    {
                        Value = "system_params"
                    },
                    new SqlParameter("@param_field", SqlDbType.VarChar)
                    {
                        Value = "*"
                    },
                    new SqlParameter("@param_where", SqlDbType.Text)
                    {
                        Value = strWhere
                    },
                    new SqlParameter("@param_groupBy", SqlDbType.VarChar)
                    {
                        Value = ""
                    },
                    new SqlParameter("@param_orderBy", SqlDbType.VarChar)
                    {
                        Value = strOrderBy
                    },
                    new SqlParameter("@param_pageNumber", SqlDbType.VarChar)
                    {
                        Value = start / length + 1
                    },
                    new SqlParameter("@param_pageSize", SqlDbType.Int)
                    {
                        Value = length
                    },
                    new SqlParameter("@param_isCount", SqlDbType.Int)
                    {
                        Value = 1
                    }
                };

                DataSet ds = Utility.SqlHelper.ExecProcFillDataSet("sp_GetPagingList", param);
                paging.draw            = draw;
                paging.recordsTotal    = Int32.Parse(ds.Tables[1].Rows[0][0].ToString());
                paging.data            = ds.Tables[0];
                paging.recordsFiltered = Int32.Parse(ds.Tables[1].Rows[0][0].ToString());
                return(JsonConvert.SerializeObject(paging));
            }
            catch (Exception ex)
            {
                paging.error = "获取用户类型列表失败:" + ex.Message;
                paging.data  = null;
                return(JsonConvert.SerializeObject(paging));
            }
        }
Ejemplo n.º 19
0
        public void UpdateCurrentTile(SelectionInfo info)
        {
            Text   txt = currentTileText.GetComponent <Text>();
            Tile   t   = info.tile;
            object o   = info.contents[info.subSelect];

            int pw = 38;

            string displayMe = "";


            displayMe += Funcs.PadPair(pw, "chunk x", t.chunk.x.ToString(), '.');
            displayMe += "\n" + Funcs.PadPair(pw, "chunk y", t.chunk.y.ToString(), '.');
            displayMe += "\n" + Funcs.PadPair(pw, "world x", t.world_x.ToString(), '.');
            displayMe += "\n" + Funcs.PadPair(pw, "world y", t.world_y.ToString(), '.');



            displayMe += "\n";
            if (o.GetType() == typeof(Tile))
            {
                Tile tile = (Tile)o;
                displayMe += Funcs.PadPair(pw, "tile type", tile.type.name, '.');

                displayMe += "\n" + tile.JobsToString(pw);
            }
            else if (o.GetType() == typeof(Entity))
            {
                Entity to = (Entity)o;
                displayMe += Funcs.PadPair(pw, "type", to.typeName);
                displayMe += "\n" + Funcs.PadPair(pw, "name", to.name);
                displayMe += "\n" + Funcs.PadPair(pw, "state", to.state);

                //if (to.animator.valid) {
                //  displayMe += "\n" + Funcs.PadPair(pw, "animation", to.animator.currentAnimation.name);
                //  displayMe += "\n" + Funcs.PadPair(pw, "running", to.animator.running.ToString());
                //  //displayMe += "\n" + Funcs.PadPair(pw, "timer", to.animator.timer.ToString());
                //  //displayMe += "\n" + Funcs.PadPair(pw, "index", to.animator.index.ToString());
                //}
            }
            else if (o.GetType() == typeof(InstalledItem))
            {
                InstalledItem item = (InstalledItem)o;
                displayMe += Funcs.PadPair(pw, "installed item", item.niceName, '.');

                if (item.itemParameters.HasProperty("socialMediaName"))
                {
                    displayMe += "\n" + Funcs.PadPair(pw, "social media", item.itemParameters.GetString("socialMediaName"), '.');
                }

                if (item.editOnClick)
                {
                    this.prfInstalledItemOptionsInScene.GetComponent <prfInstalledItemScript>().Set(item);
                }
            }
            else if (o.GetType() == typeof(string))
            {
                string invname = t.GetFirstInventoryItem();
                if (invname != null)
                {
                    string nicename = InventoryItem.GetPrototype(invname).niceName;
                    displayMe += Funcs.PadPair(pw, nicename, t.InventoryTotal(invname).ToString());
                    displayMe += "\n" + Funcs.PadPair(pw, "allocated", t.InventoryTotalAllocated(invname).ToString());
                }
                //displayMe += InventoryItem.GetPrototype(t.GetFirstInventoryItem()).niceName + ": " + t.InventoryTotal(((string)o));
            }
            //displayMe += "\nNeighbours:" + t.neighbours.Count + ", " + t.edges.Count;
            //displayMe += "\nRoom:" + t.room.id;
            //displayMe += "\nInstalled:" + (t.installedItem == null ? "" : t.installedItem.niceName);
            //displayMe += "\nJobs: " + t.JobsToString();
            //displayMe += "\nItems:" + t.GetContents();//(t.inventoryItem == null ? "" : t.inventoryItem.niceName + " " + t.inventoryItem.currentStack + "/" + t.inventoryItem.maxStackSize);
            //displayMe += "\n" + t.WhoIsHere();



            txt.text = displayMe;
        }
Ejemplo n.º 20
0
        // 获取用户列表
        private string getUserList()
        {
            pagingJson paging = new pagingJson();

            try
            {
                //获取Datatables发送的参数 必要
                int draw = Int32.Parse(Funcs.Get("draw"));//这个值作者会直接返回给前台

                //排序
                string orderColumn = Funcs.Get("order[0][column]"); //那一列排序,从0开始
                string orderDir    = Funcs.Get("order[0][dir]");    //ase desc 升序或者降序

                //搜索
                string sStatus   = Funcs.Get("sStatus");                      //用户状态
                string sUserType = Funcs.Get("sUserType");                    //用户类型
                string sName     = GlobalObject.unescape(Funcs.Get("sName")); //搜索框值

                //分页
                int start  = Int32.Parse(Funcs.Get("start"));  //第一条数据的起始位置
                int length = Int32.Parse(Funcs.Get("length")); //每页显示条数

                // where条件,排序条件
                string strWhere = "tt.userStatus!=2", strOrderBy = "";
                if (sStatus != null && sStatus != "")
                {
                    strWhere += " and userStatus=" + sStatus;
                }
                if (sUserType != null && sUserType != "")
                {
                    strWhere += " and userType=" + sUserType;
                }
                if (sName != null && sName != "")
                {
                    strWhere += " and (userName like '%" + Funcs.ToSqlString(sName) + "%' or trueName like '%" + Funcs.ToSqlString(sName) + "%')";
                }
                if (orderColumn != "" && orderDir != "")
                {
                    strOrderBy = Funcs.Get("columns[" + orderColumn + "][data]") + " " + orderDir;
                }

                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@param_table", SqlDbType.Text)
                    {
                        Value = "(select su.*,sp.paramsName from system_users su left join system_params sp on su.userType=sp.id)tt"
                    },
                    new SqlParameter("@param_field", SqlDbType.VarChar)
                    {
                        Value = "*"
                    },
                    new SqlParameter("@param_where", SqlDbType.Text)
                    {
                        Value = strWhere
                    },
                    new SqlParameter("@param_groupBy", SqlDbType.VarChar)
                    {
                        Value = ""
                    },
                    new SqlParameter("@param_orderBy", SqlDbType.VarChar)
                    {
                        Value = strOrderBy
                    },
                    new SqlParameter("@param_pageNumber", SqlDbType.VarChar)
                    {
                        Value = start / length + 1
                    },
                    new SqlParameter("@param_pageSize", SqlDbType.Int)
                    {
                        Value = length
                    },
                    new SqlParameter("@param_isCount", SqlDbType.Int)
                    {
                        Value = 1
                    }
                };

                DataSet ds = Utility.SqlHelper.ExecProcFillDataSet("sp_GetPagingList", param);
                paging.draw            = draw;
                paging.recordsTotal    = Int32.Parse(ds.Tables[1].Rows[0][0].ToString());
                paging.data            = ds.Tables[0];
                paging.recordsFiltered = Int32.Parse(ds.Tables[1].Rows[0][0].ToString());
                return(DateTimeFormat(paging, "yyyy-MM-dd HH:mm "));
            }
            catch (Exception ex)
            {
                paging.error = "获取用户列表失败:" + ex.Message;
                paging.data  = null;
                return(JsonConvert.SerializeObject(paging));
            }
        }
Ejemplo n.º 21
0
        //private static void CreateRecipes(JArray recipeArray) {
        //  foreach (JObject jRecipe in recipeArray) {
        //    CreateRecipePrototype(jRecipe);

        //  }

        //}

        private static void CreateRecipePrototype(JObject jRecipe)
        {
            Recipe recipe = new Recipe();

            recipe.name     = Funcs.jsonGetString(jRecipe["name"], "");
            recipe.niceName = Funcs.jsonGetString(jRecipe["niceName"], "");
            //recipe.id = Funcs.jsonGetInt(jRecipe["id"], -1);
            recipe.buildTime = Funcs.jsonGetFloat(jRecipe["buildTime"], 1);

            recipe.products  = new Dictionary <string, RecipeProduct>();
            recipe.resources = new Dictionary <string, RecipeResource>();
            recipe.cost      = Funcs.jsonGetFloat(jRecipe["cost"], 0);
            recipe.onDemand  = Funcs.jsonGetBool(jRecipe["onDemand"], false);
            recipe.btnText   = Funcs.jsonGetString(jRecipe["btnText"], "");

            JArray jaResources = Funcs.jsonGetArray(jRecipe, "resources");

            if (jaResources != null)
            {
                foreach (JObject jResource in jaResources)
                {
                    string rname = Funcs.jsonGetString(jResource["name"], null);
                    int    rqty  = Funcs.jsonGetInt(jResource["qty"], -1);



                    if (rname != null && rqty > 0)
                    {
                        RecipeResource r = new RecipeResource(rname, rqty);

                        recipe.resources[rname] = r;
                    }
                }
            }


            JArray jaProducts = Funcs.jsonGetArray(jRecipe, "products");

            if (jaProducts != null)
            {
                foreach (JObject jProduct in jaProducts)
                {
                    string rname   = Funcs.jsonGetString(jProduct["name"], null);
                    int    rminQty = Funcs.jsonGetInt(jProduct["qtyMin"], -1);
                    int    rmaxQty = Funcs.jsonGetInt(jProduct["qtyMax"], -1);
                    float  rchance = Funcs.jsonGetFloat(jProduct["chance"], 0);



                    if (rname != null && rminQty >= 0 && rmaxQty > 0)
                    {
                        RecipeProduct r = new RecipeProduct(rname, rminQty, rmaxQty, rchance);

                        recipe.products[rname] = r;
                    }
                }
            }

            recipes[recipe.name] = recipe;
            //Debug.Log("recipe Added: " + recipe.ToString(true) + " " + recipe.buildTime);
        }
Ejemplo n.º 22
0
        // 新增或编辑用户
        private string addOrEditUser()
        {
            myJson my = new myJson();

            try
            {
                var userId     = Funcs.Get("userId") == "" ? "0" : Funcs.Get("userId"); //用户Id
                var userName   = GlobalObject.unescape(Funcs.Get("userName"));          //用户名
                var nikeName   = GlobalObject.unescape(Funcs.Get("nikeName"));          //昵称
                var password   = GlobalObject.unescape(Funcs.Get("password"));          //密码
                var truename   = GlobalObject.unescape(Funcs.Get("truename"));          //真实姓名
                var userType   = Funcs.Get("userType");                                 //用户类型
                var userStatus = Funcs.Get("userStatus");                               //用户状态

                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@param_userId", SqlDbType.Int)
                    {
                        Value = userId
                    },
                    new SqlParameter("@param_userName", SqlDbType.VarChar)
                    {
                        Value = userName
                    },
                    new SqlParameter("@param_nikeName", SqlDbType.VarChar)
                    {
                        Value = nikeName
                    },
                    new SqlParameter("@param_pwd", SqlDbType.VarChar)
                    {
                        Value = Funcs.MD5(password)
                    },
                    new SqlParameter("@param_trueName", SqlDbType.VarChar)
                    {
                        Value = truename
                    },
                    new SqlParameter("@param_userType", SqlDbType.Int)
                    {
                        Value = userType
                    },
                    new SqlParameter("@param_userStatus", SqlDbType.Int)
                    {
                        Value = userStatus
                    },
                    new SqlParameter("@param_createTime", SqlDbType.DateTime)
                    {
                        Value = DateTime.Now
                    }
                };
                //判断此用户名是否被使用
                string sql   = "select count(*) from system_users where username=@param_userName and id!=@param_userId and userstatus!=2";
                int    count = System.Convert.ToInt32(Utility.SqlHelper.ExecuteScalar(sql, param));
                if (count > 0)
                {
                    my.flag = 0;
                    my.msg  = "此用户名已存在,请更换!";
                    return(JsonConvert.SerializeObject(my));
                }

                count = Utility.SqlHelper.ExecProcNonQuery("sp_AddOrUpdateUser", param);

                if (count > 0)
                {
                    my.flag = 1;
                    my.msg  = "保存成功!";
                    return(JsonConvert.SerializeObject(my));
                }
                my.flag = 0;
                my.msg  = "保存失败!";
                return(JsonConvert.SerializeObject(my));
            }
            catch (Exception ex)
            {
                my.flag = 0;
                my.msg  = "保存失败:" + ex.Message;
                return(JsonConvert.SerializeObject(my));
            }
        }
Ejemplo n.º 23
0
        public override async System.Threading.Tasks.Task Run()
        {
            // Initial await
            await ClockAsync();


            Random rnd = new Random();

            // Testing data
            // Positions array is kept double so that the ulong bitstream can be
            // generated correctly
            double[,] positions = new double[(int)Deflib.Dimensions.n, data_size];
            double[,] velocity  = new double[(int)Deflib.Dimensions.n, data_size];
            for (ulong i = 0; i < data_size; i++)
            {
                for (int j = 0; j < (int)Deflib.Dimensions.n; j++)
                {
                    // Non-random data:
                    positions[j, i] = (double)i + 1;
                    velocity[j, i]  = 0.0;
                }
            }

            for (int i = 0; i < data_size; i++)
            {
                for (int j = 0; j < (int)Deflib.Dimensions.n; j++)
                {
                    // Write initial positions to external sim
                    init_position[j].valid = true;
                    init_position[j].val   = Funcs.FromDouble(positions[j, i]);

                    // Write initial velocity to external sim
                    init_velocity[j].valid = true;
                    init_velocity[j].val   = Funcs.FromDouble(velocity[j, i]);
                }
                await ClockAsync();
            }

            bool running = true;

            while (running)
            {
                bool isfinished = true;
                for (int i = 0; i < (int)Deflib.Dimensions.n; i++)
                {
                    if (finished[i].valid && isfinished)
                    {
                        isfinished = true;
                    }
                    else
                    {
                        isfinished = false;
                    }
                }
                if (isfinished)
                {
                    running = false;
                    Console.WriteLine("All dimensions have completed");
                }
                else
                {
                    await ClockAsync();
                }
            }
        }
Ejemplo n.º 24
0
        // 用户登录
        private string userLogin()
        {
            myJson my = new myJson();

            try
            {
                #region 检测用户名,密码
                string userName = Funcs.Get("userName"); //用户名
                string pwd      = Funcs.Get("pwd");      //密码

                string         strSql = "select su.*,sp.paramsName userTypeName from system_users su inner join system_params sp on su.userType=sp.id where su.userName=@userName and su.password=@pwd";
                SqlParameter[] param  = new SqlParameter[] {
                    new SqlParameter("@userName", SqlDbType.VarChar)
                    {
                        Value = userName
                    },
                    new SqlParameter("@pwd", SqlDbType.VarChar)
                    {
                        Value = Funcs.MD5(pwd)
                    }
                };

                DataTable tb = Utility.SqlHelper.GetDataTable(strSql, param);
                if (tb == null || tb.Rows.Count < 1)
                {
                    my.flag = 0;
                    my.msg  = "用户名或密码错误!";
                    return(JsonConvert.SerializeObject(my));
                }
                if (int.Parse(tb.Rows[0]["userstatus"].ToString()) == 0)
                {
                    my.flag = 0;
                    my.msg  = "您的帐号已暂停使用,请联系管理员!";
                    return(JsonConvert.SerializeObject(my));
                }
                #endregion

                #region 保存用户信息,权限到Session
                string loginUserId = tb.Rows[0]["id"].ToString();
                //防止一个帐号多处登录
                Global.Add(int.Parse(loginUserId), HttpContext.Current.Session.SessionID);


                //保存用户的信息到Session
                MySession.Add("userId", tb.Rows[0]["id"]);
                MySession.Add("userName", tb.Rows[0]["userName"]);
                MySession.Add("userTypeName", tb.Rows[0]["userTypeName"]);
                MySession.Add("trueName", tb.Rows[0]["trueName"]);

                #endregion

                my.flag = 1;
                my.msg  = "登录成功";
                return(JsonConvert.SerializeObject(my));
            }
            catch (Exception ex)
            {
                my.flag = 0;
                my.msg  = "登录失败:" + ex.Message;
                return(JsonConvert.SerializeObject(my));
            }
        }
Ejemplo n.º 25
0
        private EAlertType CheckForExistingFlags(Vehicle veh)
        {
            if (veh.Exists() && (veh.HasDriver && veh.Driver.Exists()))
            {
                Persona p = Functions.GetPersonaForPed(veh.Driver);

                if (veh.IsStolen)
                {
                    return(EAlertType.Stolen_Vehicle);
                }

                if (p.Wanted)
                {
                    return(EAlertType.Owner_Wanted);
                }

                if (p.LicenseState == ELicenseState.Suspended)
                {
                    return(EAlertType.Owner_License_Suspended);
                }

                if (p.LicenseState == ELicenseState.Expired)
                {
                    return(EAlertType.Owner_License_Expired);
                }

                if (Funcs.IsTrafficPolicerRunning())
                {
                    EVehicleStatus mRegistration = TrafficPolicer.GetVehicleRegistrationStatus(veh);
                    EVehicleStatus mInsurance    = TrafficPolicer.GetVehicleInsuranceStatus(veh);

                    if (mRegistration == EVehicleStatus.Expired)
                    {
                        return(EAlertType.Registration_Expired);
                    }
                    else if (mRegistration == EVehicleStatus.None)
                    {
                        return(EAlertType.Unregistered_Vehicle);
                    }

                    if (mInsurance == EVehicleStatus.Expired)
                    {
                        return(EAlertType.Insurance_Expired);
                    }
                    else if (mInsurance == EVehicleStatus.None)
                    {
                        return(EAlertType.No_Insurance);
                    }
                }
            }
            else if (veh.Exists() && (!veh.HasDriver || !veh.Driver.Exists()))
            {
                if (veh.IsStolen)
                {
                    return(EAlertType.Stolen_Vehicle);
                }

                if (Funcs.IsTrafficPolicerRunning())
                {
                    EVehicleStatus mRegistration = TrafficPolicer.GetVehicleRegistrationStatus(veh);
                    EVehicleStatus mInsurance    = TrafficPolicer.GetVehicleInsuranceStatus(veh);

                    if (mRegistration == EVehicleStatus.Expired)
                    {
                        return(EAlertType.Registration_Expired);
                    }
                    else if (mRegistration == EVehicleStatus.None)
                    {
                        return(EAlertType.Unregistered_Vehicle);
                    }

                    if (mInsurance == EVehicleStatus.Expired)
                    {
                        return(EAlertType.Insurance_Expired);
                    }
                    else if (mInsurance == EVehicleStatus.None)
                    {
                        return(EAlertType.No_Insurance);
                    }
                }
            }

            return(EAlertType.Null);
        }
Ejemplo n.º 26
0
 // Deirvative rule
 public override Function Derivative()
 {
     return(Funcs.Cos(InnerF) * InnerF.Derivative());
 }
Ejemplo n.º 27
0
        public static void LoadFromFile()
        {
            TYPES.Clear();
            //TYPES_BY_ID.Clear();
            countNatural = 0;

            string path = Path.Combine(Application.streamingAssetsPath, "data", "TileTypes");

            string[] files = Directory.GetFiles(path, "*.json");

            foreach (string file in files)
            {
                string json = File.ReadAllText(file);

                JObject tileTypeJson = JObject.Parse(json);

                string n = Funcs.jsonGetString(tileTypeJson["name"], null);

                string minedProduct = Funcs.jsonGetString(tileTypeJson["minedProduct"], null);

                List <string> sprites = new List <string>();

                for (int i = 0; i < 8; i += 1)
                {
                    sprites.Add("tiles::" + n + "_" + i);
                }



                //Debug.Log(n + " " + sprites[0] + " " + sprites.Count);
                TileType t = new TileType(n, sprites.ToArray <string>());



                //t.rangeLow = (float)tileTypeJson["rangeLow"];
                //t.rangeHigh = (float)tileTypeJson["rangeHigh"];
                t.build          = Funcs.jsonGetBool(tileTypeJson["build"], false);
                t.movementFactor = Funcs.jsonGetFloat(tileTypeJson["movementFactor"], 0.5f);
                t.height         = Funcs.jsonGetInt(tileTypeJson["height"], -1);
                t.minedProduct   = minedProduct;
                t.varieties      = new Dictionary <string, Tuple <float, float> >();
                JArray typeVarieties = Funcs.jsonGetArray(tileTypeJson, "varieties");

                if (typeVarieties != null)
                {
                    foreach (JObject variety in typeVarieties)
                    {
                        string vName     = Funcs.jsonGetString(variety["name"], null);
                        float  vzoffsetA = Funcs.jsonGetFloat(variety["zOffsetA"], 10);
                        float  vzoffsetB = Funcs.jsonGetFloat(variety["zOffsetB"], 10);
                        if (vName != null)
                        {
                            t.varieties[vName] = new Tuple <float, float>(vzoffsetA, vzoffsetB);
                        }
                    }
                }



                TYPES.Add(n, t);
                //TYPES_BY_ID.Add(t.id, t);

                if (t.height >= 0)
                {
                    countNatural += 1;
                }
                //}
                //loaded = true;
            }
            int heightIndex = 0;

            foreach (TileType tt in TYPES.Values.OrderBy(e => e.height))
            {
                if (tt.height < 0)
                {
                    tt.heightIndex = -1;
                }
                else
                {
                    tt.heightIndex = heightIndex;
                    heightIndex   += 1;
                }
            }
        }
Ejemplo n.º 28
0
        public void When_SingleSelectedItem_Event()
        {
            var style = new Style(typeof(Windows.UI.Xaml.Controls.ListViewBase))
            {
                Setters =
                {
                    new Setter <ItemsControl>("Template", t =>
                                              t.Template = Funcs.Create(() =>
                                                                        new ItemsPresenter()
                                                                        )
                                              )
                }
            };

            var panel = new StackPanel();

            var item = new Border {
                Name = "b1"
            };
            var SUT = new ListViewBase()
            {
                Style      = style,
                ItemsPanel = new ItemsPanelTemplate(() => panel),
                Items      =
                {
                    item
                }
            };

            var model = new MyModel
            {
                SelectedItem = (object)null
            };

            SUT.SetBinding(
                Selector.SelectedItemProperty,
                new Binding()
            {
                Path   = "SelectedItem",
                Source = model,
                Mode   = BindingMode.TwoWay
            }
                );

            // Search on the panel for now, as the name lookup is not properly
            // aligned on net46.
            Assert.IsNotNull(panel.FindName("b1"));

            var selectionChanged = 0;

            SUT.SelectionChanged += (s, e) =>
            {
                selectionChanged++;
                Assert.AreEqual(item, SUT.SelectedItem);

                // In windows, when programmatically changed, the bindings are updated *after*
                // the event is raised, but *before* when the SelectedItem is changed from the UI.
                Assert.IsNull(model.SelectedItem);
            };

            SUT.SelectedIndex = 0;

            Assert.AreEqual(item, model.SelectedItem);

            Assert.IsNotNull(SUT.SelectedItem);
            Assert.AreEqual(1, selectionChanged);
            Assert.AreEqual(1, SUT.SelectedItems.Count);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Конструктор для формы с параметрами - параметрами симуляции.
        /// Задает внешний вид формы, значения полей, настраивает
        /// подсказки для пользователя.
        /// </summary>
        /// <param name="form"> Параметр для предыдущей формы. </param>
        /// <param name="homescreen"> Параметр для начального экрана. </param>
        /// <param name="funcs"> Параметр для экземпляра класса функций
        /// матлаб. </param>
        /// <param name="N"> Параметр для количества векторов, по которым
        /// составляются наблюдения. </param>
        /// <param name="Mu"> Параметр для размера решетки радиолокатора
        /// по длине. </param>
        /// <param name="Mv"> Параметр для размера решетки радиолокатора
        /// по ширине. </param>
        /// <param name="Um"> Параметр для ширины главного лепестка
        /// диаграммы направленности модуля по одному углу. </param>
        /// <param name="Vm"> Параметр для ширины главного лепестка
        /// диаграммы направленности модуля по другому углу. </param>
        /// <param name="du"> Параметр для сдвига до центра
        /// просматриваемого сектора по одному углу. </param>
        /// <param name="dv"> Параметр для сдвига до центра
        /// просматриваемого сектора по другому углу. </param>
        /// <param name="u"> Параметр для предполагаемого положения
        /// цели по одному углу. </param>
        /// <param name="v"> Параметр для предполагаемого положения
        /// цели по одному углу. </param>
        /// <param name="a"> Параметр для мощности сигнала. </param>
        /// <param name="Tc"> Параметр для времени начала прихода
        /// сигнала. </param>
        /// <param name="up1"> Параметр для первой компоненты
        /// положения помех по одному углу. </param>
        /// <param name="up2"> Параметр для второй компоненты
        /// положения помех по одному углу. </param>
        /// <param name="vp1"> Параметр для первой компоненты
        /// положения помех по другому углу. </param>
        /// <param name="vp2"> Параметр для второй компоненты
        /// положения помех по другому углу. </param>
        /// <param name="Ap1"> Параметр для первой компоненты
        /// мощности помех. </param>
        /// <param name="Ap2"> Параметр для второй компоненты
        /// мощности помех. </param>
        /// <param name="gamma"> Параметр гамма. </param>
        /// <param name="_mu"> Параметр для коэффициента
        /// регуляризации корреляционной матрицы. </param>
        /// <param name="H"> Параметр для порогового значения
        /// мощности сигнала. </param>
        /// <param name="pq"> Параметр для количества блоков,
        /// по которым составляется корреляционная матрица. </param>
        public Operations(Input form, Homescreen homescreen,
                          Funcs funcs, int N, int Mu, int Mv,
                          float Um, float Vm, float du, float dv, float u, float v,
                          float a, float Tc, float up1, float up2, float vp1, float vp2,
                          float Ap1, float Ap2, float gamma, float _mu, float H, int pq)
        {
            this.Mu         = Mu;
            this.Mv         = Mv;
            this.Um         = Um;
            this.Vm         = Vm;
            this.u          = u;
            this.v          = v;
            this.du         = du;
            this.dv         = dv;
            this.a          = a;
            this.Tc         = Tc;
            this.up1        = up1;
            this.up2        = up2;
            this.vp1        = vp1;
            this.vp2        = vp2;
            this.Ap1        = Ap1;
            this.Ap2        = Ap2;
            this.H          = H;
            this._mu        = _mu;
            this.pq         = pq;
            this.N          = N;
            this.gamma      = gamma;
            this.funcs      = funcs;
            prevForm        = form;
            this.homescreen = homescreen;
            M = Mu * Mv;

            InitializeComponent();

            log.Text = "Параметры симуляции определены";

            dataE = matrixE = statE = bSaveData.Enabled
                                          = bGenMatrix.Enabled = bSaveMatrix.Enabled
                                                                     = bGenStat.Enabled = bSaveStat.Enabled
                                                                                              = bVisualize.Enabled = sliderH.Enabled =
                                                                                                    min.Visible = max.Visible = label1.Visible = false;

            this.BackColor    = log.BackColor = backColor;
            panel.BackColor   = sliderH.BackColor =
                min.BackColor = max.BackColor = panelColor;
            log.ForeColor     = min.ForeColor = max.ForeColor
                                                    = label1.ForeColor = textColor;

            foreach (Button b in GetAllControlsOfType <Button>(this))
            {
                b.FlatAppearance.MouseOverBackColor = hoverColor;
                b.ForeColor = textColor;
            }

            bVisualize.Text = $"Порог сигнала = {H}\nВизуализировать статистику наблюдений";

            toolTip.SetToolTip(bBackToHomepage, "Внимание!" +
                               "\nПри возвращении прогресс текущей сессии будет потерян." +
                               "\nУбедитесь в том, что вы сохранили все файлы," +
                               "\nкоторые не хотите потерять.");
            toolTip.SetToolTip(bBackToInput, "Внимание!" +
                               "\nПри возвращении прогресс текущей сессии," +
                               "\nкроме параметров симуляции, будет потерян." +
                               "\nУбедитесь в том, что вы сохранили все файлы," +
                               "\nкоторые не хотите потерять.");
        }
Ejemplo n.º 30
0
 public int Process(IMyInterface v) => Funcs.Get <int>().With(5).With(z =>
                                                                      new TypeMatcher <int>
 {
     { Case.Is <A>(), x => z.Invoke(((Func <A, int, int>)ProcessA).Curry()(x)) },
     { Case.Is <B>(), x => z.Invoke(((Func <B, int, int>)ProcessB).Curry()(x)) }
 }).Value.Match(v);
Ejemplo n.º 31
0
 public void RunBeforeAnyTests()
 {
     Funcs.RunScript("create-database.sql", Settings.SysConnectionString);
     Funcs.RunScript("stored-procs.sql", Settings.AppConnectionString);
 }
Ejemplo n.º 32
0
        private double y_(List <double> x)
        {
            double y_ = Funcs.sum(x) / x.Count;

            return(y_);
        }