Пример #1
0
 public void ToStream(DataFrames.DataWriter writer, StateDictionary state, Utils.Logger logger)
 {
     if (Bytes != null)
     {
         writer.Write(Bytes);
     }
 }
Пример #2
0
		/// <summary>
		/// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url.
		/// </summary>
		/// <param name="context">
		/// The context.
		/// </param>
		/// <param name="returnUrl">
		/// The return url after users have completed authenticating against external website. 
		/// </param>
        /// <param name="state">
        /// Additional state to pass on the callback url.
        /// </param>
        public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl, StateDictionary state)
        {
			Requires.NotNull(context, "context");
			Requires.NotNull(returnUrl, "returnUrl");
            Requires.NotNull(state, "state");

			Uri redirectUri = this.GetServiceLoginUrl(returnUrl);
            redirectUri = redirectUri.AttachQueryStringParameter("state", state.ToEncodedString());
            context.Response.Redirect(redirectUri.AbsoluteUri, endResponse: true);
		}
Пример #3
0
        /// <summary>
        /// This method reads a text file which contains district (state/province) information for a country
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool LoadStateDictionary(string fileName)
        {
            List <State> stateList = new List <State>();

            // TODO 12: Add exception handling so the program does not blow up with file error
            try
            {
                // TODO 11: Open the file, read each line, parse it, and load up a list of states.
                using (StreamReader reader = new StreamReader(fileName))
                {
                    while (!reader.EndOfStream)
                    {
                        // Read the next line
                        string input = reader.ReadLine();

                        // Split the line into individual fields
                        string[] fields = input.Split("|");

                        string stateName = fields[0];
                        string stateCode = fields[1];
                        string capital   = fields[2];
                        string largest   = fields[3];

                        State state = new State(stateCode, stateName, capital, largest);
                        stateList.Add(state);
                    }
                }

                // Now load this collection into a StateDictionary
                this.stateCodes = new StateDictionary(stateList);
                return(true);
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine($"Unable to load data file {ex.FileName}. Error was {ex.Message}.");
                this.stateCodes = new StateDictionary(new List <State>());
                return(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"File load failed with error {ex.Message}");
                this.stateCodes = new StateDictionary(new List <State>());
                return(false);
            }
        }
Пример #4
0
        private static StateDictionary GetStates(string fileName)
        {
            StateDictionary statesList;

            if (!File.Exists(fileName))
            {
                statesList = new StateDictionary();
            }
            else
            {
                using (StreamReader file = File.OpenText(fileName))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    statesList = (StateDictionary)serializer.Deserialize(file, typeof(StateDictionary));
                }
            }

            return(statesList);
        }
Пример #5
0
        protected override InputState GetIdleState()  //initilization
        {
            var states = new StateDictionary();

            states.Add((int)AllInputStates.Idle, s => new InputIdleState(s));
            states.Add((int)AllInputStates.Rotate, s => new InputRotateState(s));
            states.Add((int)AllInputStates.Zoom, s => new InputZoomState(s));
            states.Add((int)AllInputStates.Pan, s => new InputPanState(s));
            states.Add((int)AllInputStates.Target, s => new InputTargetState(s));
            states.Add((int)AllInputStates.KeywordDown, s => new KeywordMovingState(s));
            states.Add((int)AllInputStates.ChangeFocus, s => new FocusToObjectState(s));

            var router = new StateHandleProcessor <ICameraInputHandler>(states, this);

            router.SwitchTo((int)AllInputStates.Idle, InputStateData.Create());



            return(router);
        }
    //比较比较两组状态 是否一样
    public static bool IsEqual(StateDictionary a, StateDictionary b)
    {
        if (a.conditions.Keys.Count != b.conditions.Keys.Count)
        {
            return(false);
        }
        int equalCount = 0;

        foreach (KeyValuePair <string, object> aPair in a.conditions)
        {
            foreach (KeyValuePair <string, object> bPair in b.conditions)
            {
                if (aPair.Key == bPair.Key && aPair.Value == bPair.Value)
                {
                    equalCount++;
                }
            }
        }
        return(equalCount == a.conditions.Keys.Count);
    }
Пример #7
0
 private List <AIAction> GetRelated(StateDictionary sd, List <AIAction> relatedActionsSoFar, List <AIAction> allActions)
 {
     foreach (var kvp in sd.conditions)
     {
         foreach (var action in allActions)
         {
             foreach (var kvpPost in action.postEffects.conditions)
             {
                 if (kvpPost.Key == kvp.Key && kvpPost.Value.ToString() == kvp.Value.ToString())
                 {
                     if (!relatedActionsSoFar.Contains(action))
                     {
                         relatedActionsSoFar.Add(action);
                         GetRelated(action.preConditions, relatedActionsSoFar, allActions);
                     }
                 }
             }
         }
     }
     return(relatedActionsSoFar);
 }
Пример #8
0
        static void Main()
        {
            string connectionString = CloudConfigurationManager.GetSetting("ConnectionString");
            string containerName    = "sqldbauditlogs";
            string customerId       = CloudConfigurationManager.GetSetting("omsWorkspaceId");
            string sharedKey        = CloudConfigurationManager.GetSetting("omsWorkspaceKey");

            CloudStorageAccount storageAccount;
            var oms = new OMSIngestionApi(s_consoleTracer, customerId, sharedKey);

            if (CloudStorageAccount.TryParse(connectionString, out storageAccount) == false)
            {
                s_consoleTracer.TraceEvent(TraceEventType.Error, 0, "Connection string can't be parsed: {0}", connectionString);
                return;
            }
            try
            {
                CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container  = BlobClient.GetContainerReference(containerName);

                var stateFileName = Path.Combine(Environment.GetEnvironmentVariable("WEBROOT_PATH"), "states.json");

                StateDictionary statesList = GetStates(stateFileName);

                s_consoleTracer.TraceInformation("Sending logs to OMS");

                IEnumerable <CloudBlobDirectory> servers = container.ListBlobs().OfType <CloudBlobDirectory>();
                foreach (var server in servers)
                {
                    SendLogsFromServer(server, statesList, oms);
                }

                File.WriteAllText(stateFileName, JsonConvert.SerializeObject(statesList));
                s_consoleTracer.TraceInformation("{0} logs were successfully sent", totalLogs);
            }
            catch (Exception ex)
            {
                s_consoleTracer.TraceEvent(TraceEventType.Error, 0, "Error: {0}", ex);
            }
        }
Пример #9
0
    private void CreateActionTree(Node root, StateDictionary cWorldState, StateDictionary goalState, List <AIAction> allActions, List <Node> matchNodes, ref float minCostPlanSoFar)
    {
        foreach (AIAction action in allActions)
        {
            if (root.cost + action.Cost < minCostPlanSoFar && action.CanApplyToWorld(cWorldState))
            {
                StateDictionary newWorldState = new StateDictionary(cWorldState.conditions);
                StateDictionary.OverrideCombine(action.postEffects, newWorldState);
                Node newNode = new Node(/*letter++ + "",*/ root.cost + action.Cost, root, action);

                // check to see if goal is satisfied
                if (StateDictionary.ConditionsMatch(goalState, newWorldState))
                {
                    matchNodes.Add(newNode);
                    minCostPlanSoFar = newNode.cost;

                    minCostPlan.Clear();
                    Node tempNode = newNode;
                    while (tempNode.parent != null)
                    {
                        minCostPlan.Insert(0, tempNode.upperAction);
                        tempNode = tempNode.parent;
                    }

                    continue;
                }
                else
                {
                    List <AIAction> newActionsList = new List <AIAction>(allActions);
                    newActionsList.Remove(action);
                    CreateActionTree(newNode, newWorldState, goalState, newActionsList, matchNodes, ref minCostPlanSoFar);
                }
            }
            else
            {
                continue;
            }
        }
        return;
    }
Пример #10
0
 private void MakeFakeStartWorld()
 {
     WorldState = new StateDictionary();
     WorldState.Add(DS.killTarget, false);
     WorldState.Add(DS.haveSafePosition, false);
     WorldState.Add(DS.haveWeapon, true);
     WorldState.Add(DS.haveAmmo, true);
     WorldState.Add(DS.weaponArmed, false);
     WorldState.Add(DS.weaponLoaded, true);
     WorldState.Add(DS.targetIsDead, false);
     WorldState.Add(DS.haveTarget, false);
     WorldState.Add(DS.targetLost, false);
     WorldState.Add(DS.weaponAimed, false);
     WorldState.Add(DS.dangerExplosiveExists, false);
     WorldState.Add(DS.atSafePosition, false);
     WorldState.Add(DS.aiStatus, ET.AiStatus.Unknown);
     WorldState.Add(DS.aiAlertness, ET.AiAlertLevel.Relaxed);
     WorldState.Add(DS.takingBulletDamage, false);
     WorldState.Add(DS.bulletDodged, true);
     WorldState.Add(DS.haveFriendsAround, false);
     WorldState.Add(DS.isNearCurrentTarget, false);
 }
Пример #11
0
        public static void Main(string[] args)
        {
            var hello = Hello.Deserialize(new Reader(new byte[] {
                // Numbers: 1, 2, 1337
                2, 7, 0, 2, 8, 4, 16, 242, 20,
                // Others: -1, -2, 1337
                10, 4, 1, 3, 242, 20,
            }));

            Console.WriteLine("Numbers: {0}", String.Join(", ", hello.Numbers));
            Console.WriteLine("Others: {0}", String.Join(", ", hello.Others));

            Outer.OnUpdateFoo((newValue, oldValue, container) => {
                Console.WriteLine("Outer / Foo: {0} => {1}", oldValue, newValue);
            });

            Outer.OnUpdateBar((newValue, oldValue, container) => {
                Console.WriteLine("Outer / Bar: {0} => {1}", oldValue, newValue);
            });

            Outer.OnUpdateInner((newValue, oldValue, container) => {
                Console.WriteLine("Outer / Inner: {0} => {1}", InnerToString(oldValue), InnerToString(newValue));
            });

            Inner.OnUpdateFoo((newValue, oldValue, container) => {
                Console.WriteLine("Outer / Inner / Foo: {0} => {1}", oldValue, newValue);
            });

            Inner.OnUpdateBar((newValue, oldValue, container) => {
                Console.WriteLine("Outer / Inner / Bar: {0} => {1}", oldValue, newValue);
            });

            var outer = new Outer();

            Replayer.Replay(ref outer, new Reader(new byte[] {
                8, 0, 2, 1, 0, 10, 2, 254, 1,
                7, 0, 2, 1, 1, 10, 1, 1,
                10, 0, 2, 1, 2, 10, 4, 0, 44, 8, 1,
                9, 0, 2, 2, 2, 0, 10, 2, 192, 2,
                4, 0, 2, 1, 2,
                1, 0,
            }));

            Console.WriteLine("{0} {1} {2}", outer.Foo, outer.Bar, InnerToString(outer.Inner));

            Multicase.OnUpdate((newValue, newVariant, oldValue, oldVariant, container) => {
                Console.WriteLine("Multicase: variant {0} ({1}) => variant {2} ({3}", oldVariant, oldValue, newVariant, newValue);
            });

            Multicase.FirstCase.OnUpdateFoo((newValue, oldValue, container) => {
                Console.WriteLine("Multicase / FirstCase / Foo: {0} => {1}", oldValue, newValue);
            });

            Multicase.FirstCase.OnUpdateBar((newValue, oldValue, container) => {
                Console.WriteLine("Multicase / FirstCase / Bar: {0} => {1}", oldValue, newValue);
            });

            Multicase.SecondCase.OnUpdateFoo((newValue, oldValue, container) => {
                Console.WriteLine("Multicase / SecondCase / Foo: {0} => {1}", oldValue, newValue);
            });

            Multicase.SecondCase.OnUpdateBar((newValue, oldValue, container) => {
                Console.WriteLine("Multicase / SecondCase / Bar: {0} => {1}", oldValue, newValue);
            });

            var multicase = new Multicase();

            Replayer.Replay(ref multicase, new Reader(new byte[] {
                4, 0, 10, 1, 1,
                9, 0, 2, 2, 1, 0, 10, 2, 136, 1,
            }));

            var list1 = new StateList <Inner>();

            list1.OnUpdate((newItem, oldItem, tag, container) => {
                Console.WriteLine("List<Inner>, update #{0}: {1} => {2}", tag, InnerToString(oldItem), InnerToString(newItem));
            });

            list1.OnAdd((item, tag, container) => {
                Console.WriteLine("List<Inner>, add #{0}: {1}", tag, InnerToString(item));
            });

            list1.OnRemove((item, tag, container) => {
                Console.WriteLine("List<Inner>, remove #{0}: {1}", tag, InnerToString(item));
            });

            Replayer.Replay(ref list1, new Reader(new byte[] {
                5, 1, 10, 2, 0, 12,
                8, 1, 10, 5, 0, 154, 1, 8, 1,
                1, 1,
                9, 0, 2, 2, 1, 0, 10, 2, 136, 1,
                4, 2, 2, 1, 0,
                4, 2, 2, 1, 1,
            }));

            var list2 = new StateList <SByte>();

            list2.OnUpdate((newItem, oldItem, tag, container) => {
                Console.WriteLine("List<SByte>, update #{0}: {1} => {2}", tag, oldItem, newItem);
            });

            list2.OnAdd((item, tag, container) => {
                Console.WriteLine("List<SByte>, add #{0}: {1}", tag, item);
            });

            list2.OnRemove((item, tag, container) => {
                Console.WriteLine("List<SByte>, remove #{0}: {1}", tag, item);
            });

            Replayer.Replay(ref list2, new Reader(new byte[] {
                4, 1, 10, 1, 20,
                4, 1, 10, 1, 22,
                4, 1, 10, 1, 0,
                4, 2, 2, 1, 1,
            }));

            var map1 = new StateDictionary <Inner>();

            map1.OnUpdate((newItem, oldItem, tag, container) => {
                Console.WriteLine("Dictionary<Inner>, update #{0}: {1} => {2}", tag, InnerToString(oldItem), InnerToString(newItem));
            });

            map1.OnRemove((item, tag, container) => {
                Console.WriteLine("Dictionary<Inner>, remove #{0}: {1}", tag, InnerToString(item));
            });

            Replayer.Replay(ref map1, new Reader(new byte[] {
                8, 0, 2, 1, 5, 10, 2, 0, 12,
                11, 0, 2, 1, 1, 10, 5, 0, 154, 1, 8, 1,
                4, 0, 2, 1, 0,
                9, 0, 2, 2, 1, 0, 10, 2, 136, 1,
                4, 2, 2, 1, 0,
            }));

            var map2 = new StateDictionary <SByte>();

            map2.OnUpdate((newItem, oldItem, tag, container) => {
                Console.WriteLine("Dictionary<SByte>, update #{0}: {1} => {2}", tag, oldItem, newItem);
            });

            map2.OnRemove((item, tag, container) => {
                Console.WriteLine("Dictionary<SByte>, remove #{0}: {1}", tag, item);
            });

            Replayer.Replay(ref map2, new Reader(new byte[] {
                7, 0, 2, 1, 1, 10, 1, 20,
                7, 0, 2, 1, 3, 10, 1, 22,
                7, 0, 2, 1, 7, 10, 1, 0,
                4, 2, 2, 1, 1,
            }));

            Action.OnUpdate((newValue, newVariant, oldValue, oldVariant, container) => {
                Console.WriteLine("Action: variant {0} ({1}) => variant {2} ({3}", oldVariant, oldValue, newVariant, newValue);
            });

            Action.Attack.OnUpdateAttacker((newValue, oldValue, container) => {
                Console.WriteLine("Action / Attack / Attacker: {0} => {1}", oldValue, newValue);
            });

            Action.Attack.OnUpdateDefender((newValue, oldValue, container) => {
                Console.WriteLine("Action / Attack / Defender: {0} => {1}", oldValue, newValue);
            });

            Action.Attack.OnUpdateHits((newValue, oldValue, container) => {
                Console.WriteLine("Action / Attack / Hits:");

                if (oldValue.Count > 0)
                {
                    Console.WriteLine("Old Hits:");
                    foreach (var hit in oldValue)
                    {
                        Console.WriteLine(HitToString(hit));
                    }
                }
                else
                {
                    Console.WriteLine("Old Hits:\n<empty>");
                }

                if (newValue.Count > 0)
                {
                    Console.WriteLine("New Hits:");
                    foreach (var hit in newValue)
                    {
                        Console.WriteLine(HitToString(hit));
                    }
                }
                else
                {
                    Console.WriteLine("New Hits:\n<empty>");
                }
            });

            var action = new Action();

            Replayer.Replay(ref action, new Reader(new byte[] {
                // Set variant from to `Action::Attack`
                4, 0, 10, 1, 1,
                // Set attacker to 1
                8, 0, 2, 2, 1, 0, 10, 1, 1,
                // Set defender to 2
                8, 0, 2, 2, 1, 1, 10, 1, 2,
                // Add 4 hits with dummy values from 6 to 9, inclusive
                83, 0, 2, 2, 1, 2, 10, 76,
                2, 17, 2, 1, 0, 10, 1, 0, 18, 1, 0, 26, 1, 0, 34, 1, 0, 40, 12,
                10, 17, 2, 1, 0, 10, 1, 0, 18, 1, 0, 26, 1, 0, 34, 1, 0, 40, 14,
                18, 17, 2, 1, 0, 10, 1, 0, 18, 1, 0, 26, 1, 0, 34, 1, 0, 40, 16,
                26, 17, 2, 1, 0, 10, 1, 0, 18, 1, 0, 26, 1, 0, 34, 1, 0, 40, 18,
            }));
        }
Пример #12
0
 /// <summary>
 /// ステートと子要素のPresenterを紐づける。
 /// あるステートに状態遷移した時、結びつけられた子要素のPresenterが呼び出される。
 /// </summary>
 private void BindState()
 {
     StateDictionary.Add(LobbyState.JoinRoom, joinRoomPresenter);
     StateDictionary.Add(LobbyState.EditPlayerName, editPlayerNamePresenter);
     StateDictionary.Add(LobbyState.CreateRoom, createRoomPresenter);
 }
	    /// <summary>
	    /// Validates the request against XSRF attack.
	    /// </summary>
	    /// <param name="sessionId">The session id embedded in the query string.</param>
        /// <param name="state">Additional state to pass on the callback url.</param>
	    /// <returns>
	    ///   <c>true</c> if the request is safe. Otherwise, <c>false</c>.
	    /// </returns>
	    private bool ValidateRequestAgainstXsrfAttack(out string sessionId, StateDictionary state)
        {
			sessionId = null;

			// get the session id query string parameter
            string queryStringSessionId = state[SessionIdQueryStringName];

			// verify that the query string value is a valid guid
			Guid guid;
			if (!Guid.TryParse(queryStringSessionId, out guid)) {
				return false;
			}

			// the cookie value should be the current username secured against this guid
			var cookie = this.requestContext.Request.Cookies[SessionIdCookieName];
			if (cookie == null || string.IsNullOrEmpty(cookie.Value)) {
				return false;
			}

			// extract the username embedded within the cookie
			// if there is any error at all (crypto, malformed, etc.), fail gracefully
			string usernameInCookie = null;
			try {
				byte[] encryptedCookieBytes = HttpServerUtility.UrlTokenDecode(cookie.Value);
				byte[] decryptedCookieBytes = MachineKeyUtil.Unprotect(encryptedCookieBytes, AntiXsrfPurposeString, "Token: " + queryStringSessionId);
				usernameInCookie = Encoding.UTF8.GetString(decryptedCookieBytes);
			}
			catch {
				return false;
			}

			string currentUsername = GetUsername(this.requestContext);
			bool successful = string.Equals(currentUsername, usernameInCookie, StringComparison.OrdinalIgnoreCase);

			if (successful) {
				// be a good citizen, clean up cookie when the authentication succeeds
				var xsrfCookie = new HttpCookie(SessionIdCookieName, string.Empty) {
					HttpOnly = true,
					Expires = DateTime.Now.AddYears(-1)
				};
				this.requestContext.Response.Cookies.Set(xsrfCookie);
			}

			sessionId = queryStringSessionId;
			return successful;
		}
 public Task <InterseptorStatus> InterceptAsync(object[] values, StateDictionary stateDictionary)
 {
     return(Task.FromResult(new InterseptorStatus {
         Cancel = false
     }));
 }
Пример #15
0
 public StateHandleProcessor(StateDictionary states, THandler inputHandler) : base(states)
 {
     this.inputHandler = inputHandler;
 }
Пример #16
0
 public StateMachine()
 {
     factory = new Factory<TState, TEvent>();
     stateDict = new StateDictionary<TState, TEvent>(factory);
 }
Пример #17
0
 public override void SwitchTo(int stateTo, InputStateData state)
 {
     current?.LeaveState(state);
     current = states[stateTo](this);
     current.EnterState(state);
 }
Пример #18
0
 private void BindState()
 {
     StateDictionary.Add(GameState.Ready, readyPresenter);
     StateDictionary.Add(GameState.Play, playPresenter);
     StateDictionary.Add(GameState.Result, resultPresenter);
 }
Пример #19
0
    public Queue <AIAction> CalculatePlan(AIBrain ai, List <AIAction> allActions, StateDictionary currentWorldState, List <AIGoal> allGoals, out AIGoal activeGoal)
    {
        List <AIAction> applicapableActions = new List <AIAction>();

        foreach (AIAction action in allActions)
        {
            if (action.CanBeAddedToPlan(ai)) // to remove unnecessary action branch in tree
            {
                action.JustBeforePlan(ai);
                action.CalculateCost(ai); // Some actions can use dynamic cost based on confidence factors
                applicapableActions.Add(action);
            }
        }

        applicapableActions = applicapableActions.OrderBy(x => x.Cost).ToList();

        List <Node> goalMatchingNodes = new List <Node>();

        foreach (AIGoal goal in allGoals)
        {
            if (!goal.IsApplicapable(ai))
            {
                goal.Applicapable = false;
                continue;
            }
            goal.Applicapable = true;

            minCostPlan = new List <AIAction>();

            //letter = 0;
            Node            startNode   = new Node(/*letter++ + ""*/);
            StateDictionary cWorldState = new StateDictionary(currentWorldState.conditions);

            // Creates paths including first lowest cost action path
            float maxCSoFar = Mathf.Infinity;

            List <AIAction> applicapableNRelatedActions = new List <AIAction>();
            foreach (var action in applicapableActions)
            {
                if (goalsToRelatedActions[goal].Contains(action))
                {
                    applicapableNRelatedActions.Add(action);
                }
            }

            CreateActionTree(startNode, cWorldState, goal.goalStates, applicapableNRelatedActions /*applicapableActions*/, goalMatchingNodes, ref maxCSoFar);
            if (minCostPlan.Count > 0)
            {
                Queue <AIAction> actionQ = new Queue <AIAction>();
                foreach (AIAction action in minCostPlan)
                {
                    actionQ.Enqueue(action);
                }
                activeGoal      = goal;
                goal.lastUsedAt = Time.time;
                return(actionQ);
            }
            else
            {
                continue;
            }
        }
        activeGoal = null;
        return(null);
    }
Пример #20
0
 public abstract void Initialize(IInitializableService service, StateDictionary state, object[] parameters);
Пример #21
0
 /// <summary>
 /// ステートと子要素のPresenterを紐づける。
 /// あるステートに状態遷移した時、結びつけられた子要素のPresenterが呼び出される。
 /// </summary>
 private void BindState()
 {
     StateDictionary.Add(GroupState.Title, titlePresenter);
     StateDictionary.Add(GroupState.Lobby, lobbyPresenter);
     StateDictionary.Add(GroupState.Game, gamePresenter);
 }
Пример #22
0
    public Queue <AIAction> CalculatePlan(AIBrain ai, List <AIAction> allActions, StateDictionary currentWorldState, List <AIGoal> allGoals, out AIGoal activeGoal)
    {
        // 挑选出当前可行的 行为然后计算消耗 加入可执行列表
        List <AIAction> applicapableActions = new List <AIAction>();

        foreach (AIAction action in allActions)
        {
            if (action.CanBeAddedToPlan(ai))             // to remove unnecessary action branch in tree
            {
                action.JustBeforePlan(ai);
                action.CalculateCost(ai);                 // Some actions can use dynamic cost based on confidence factors
                applicapableActions.Add(action);
            }
        }


        //按照消耗排序当前 可以执行的行为
        applicapableActions = applicapableActions.OrderBy(x => x.Cost).ToList();

        List <Node> goalMatchingNodes = new List <Node>();

        foreach (AIGoal goal in allGoals)
        {
            //跳过当前不能执行的方案
            if (!goal.IsApplicapable(ai))
            {
                goal.Applicapable = false;
                continue;
            }

            //更新目标的可执行状态
            goal.Applicapable = true;

            //最小消耗的行为列表
            minCostPlan = new List <AIAction>();

            //letter = 0;
            Node            startNode   = new Node(/*letter++ + ""*/);
            StateDictionary cWorldState = new StateDictionary(currentWorldState.conditions);            //拷贝了一个状态
            List <AIAction> applicapableNRelatedActions = new List <AIAction>();

            // Creates paths including first lowest cost action path
            float maxCSoFar = Mathf.Infinity;


            //所有可用行为中 如果有涉及当前目标的行为 则加入列表
            foreach (var action in applicapableActions)
            {
                if (goalsToRelatedActions[goal].Contains(action))
                {
                    applicapableNRelatedActions.Add(action);
                }
            }

            // 至此 已经按照消耗排序 并且筛选当前目标可用的行为
            //
            CreateActionTree(/* 空节点 */ startNode, /* 世界状态 */ cWorldState, /* 当前目的 */ goal.goalStates, /* 当前目标牵涉到的行为 */ applicapableNRelatedActions /*applicapableActions*/, goalMatchingNodes, ref maxCSoFar);


            if (minCostPlan.Count > 0)
            {
                Queue <AIAction> actionQ = new Queue <AIAction>();
                foreach (AIAction action in minCostPlan)
                {
                    actionQ.Enqueue(action);
                }
                activeGoal      = goal;
                goal.lastUsedAt = Time.time;
                return(actionQ);
            }
            else
            {
                continue;
            }
        }
        activeGoal = null;
        return(null);
    }
		/// <summary>
		/// Requests the specified provider to start the authentication by directing users to an external website
		/// </summary>
		/// <param name="returnUrl">
		/// The return url after user is authenticated. 
		/// </param>
		/// <param name="state">
		/// Additional state to be passed on the return url.
		/// </param>
		public void RequestAuthentication(string returnUrl, StateDictionary state = null) {
		    state = state ?? new StateDictionary();

			// convert returnUrl to an absolute path
			Uri uri;
			if (!string.IsNullOrEmpty(returnUrl)) {
				uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext);
			}
			else {
				uri = this.requestContext.Request.GetPublicFacingUrl();
			}

			// attach the provider parameter so that we know which provider initiated 
			// the login when user is redirected back to this page
			// Guard against XSRF attack by injecting session id into the redirect url and response cookie.
			// Upon returning from the external provider, we'll compare the session id value in the query 
			// string and the cookie. If they don't match, we'll reject the request.
			string sessionId = Guid.NewGuid().ToString("N");
            state.Add(ProviderQueryStringName, this.authenticationProvider.ProviderName);
            state.Add(SessionIdQueryStringName, sessionId);

			// The cookie value will be the current username secured against the session id we just created.
			byte[] encryptedCookieBytes = MachineKeyUtil.Protect(Encoding.UTF8.GetBytes(GetUsername(this.requestContext)), AntiXsrfPurposeString, "Token: " + sessionId);

			var xsrfCookie = new HttpCookie(SessionIdCookieName, HttpServerUtility.UrlTokenEncode(encryptedCookieBytes)) {
				HttpOnly = true
			};
			if (FormsAuthentication.RequireSSL) {
				xsrfCookie.Secure = true;
			}
			this.requestContext.Response.Cookies.Add(xsrfCookie);

			// issue the redirect to the external auth provider
			this.authenticationProvider.RequestAuthentication(this.requestContext, uri, state);
		}
Пример #24
0
 public void FromStream(DataReader reader, StateDictionary state, Utils.Logger logger)
 {
     Bytes = reader.ReadToEnd();
 }
Пример #25
0
		/// <summary>
		/// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url.
		/// </summary>
		/// <param name="context">
		/// The context.
		/// </param>
		/// <param name="returnUrl">
		/// The return url after users have completed authenticating against external website. 
		/// </param>
        /// <param name="state">
        /// Additional state to pass on the callback url.
        /// </param>
        public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl, StateDictionary state)
        {
			Requires.NotNull(returnUrl, "returnUrl");
			Requires.NotNull(context, "context");
            Requires.NotNull(state, "state");

			Uri callback = returnUrl.StripQueryArgumentsWithPrefix("oauth_");
            callback = callback.AttachQueryStringParameter("state", state.ToEncodedString());
			this.WebWorker.RequestAuthentication(callback);
		}
 public Task <object> InterceptAsync(object result, StateDictionary getState)
 {
     return(Task.FromResult(result));
 }
Пример #27
0
 public StateHandleProcessor(StateDictionary states, params THandler[] inputHandler) : base(states)
 {
     this.inputHandlers = inputHandler;
 }
Пример #28
0
        private static StateDictionary CreateState(object target)
        {
            StateDictionary ret = new StateDictionary();

            IChildObject child = target as IChildObject;

            if (child != null)
            {
                ret.Add("parent", child.Parent);
            }

            return ret;
        }
Пример #29
0
        public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl, StateDictionary state)
        {
			Requires.NotNull(returnUrl, "returnUrl");
            Requires.NotNull(state, "state");
            returnUrl = returnUrl.AttachQueryStringParameter("state", state.ToEncodedString());
			var realm = new Realm(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));
			IAuthenticationRequest request = RelyingParty.CreateRequest(this.providerIdentifier, realm, returnUrl);

			// give subclasses a chance to modify request message, e.g. add extension attributes, etc.
			this.OnBeforeSendingAuthenticationRequest(request);

			request.RedirectToProvider();
		}
 public object Intercept(object result, StateDictionary getState)
 {
     return(result);
 }