コード例 #1
0
        public async Task <IHttpActionResult> PutUserGraphs(int id, UserGraphsJson userGraph)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != userGraph.Id)
            {
                return(BadRequest());
            }

            User user = db.User.SingleOrDefault(u => u.Id == userGraph.UserId);

            UserGraph foundUserGraph = user.UserGraphs.Where(ug => ug.Id == userGraph.Id).FirstOrDefault();

            foundUserGraph.Favourite = userGraph.Favourite;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserGraphExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #2
0
        private async Task GetGraphData(User user)
        {
            List <HistoricalValutaHours.Rootobject> cryptodataList = new List <HistoricalValutaHours.Rootobject>();
            var           httpClient = new HttpClient();
            List <Valuta> valutas    = db.Valuta.ToList();

            foreach (Valuta valuta in valutas)
            {
                var json = await httpClient.GetStringAsync($"{URL}histohour?fsym={valuta.ShortName}&tsym=USD&limit=30");

                HistoricalValutaHours.Rootobject valutaHours = JsonConvert.DeserializeObject <HistoricalValutaHours.Rootobject>(json);

                Graph graph = new Graph {
                    Name = $"{valuta.Name} {user.Username}", Valuta = valuta
                };
                foreach (HistoricalValutaHours.Datum datum in valutaHours.Data)
                {
                    GraphData graphData = new GraphData {
                        Low = datum.low, High = datum.high, Open = datum.open, Close = datum.close, TimeStamp = datum.time
                    };
                    graph.graphData.Add(graphData);
                }
                UserGraph userGraph = new UserGraph {
                    Favourite = false, Graph = graph
                };
                user.UserGraphs.Add(userGraph);
            }
        }
コード例 #3
0
        public void UnqueryBehaviorGraph(object obj)
        {
            if (UserGraph == null)
            {
                return;
            }
            var knowledge = obj as IKnowledge;

            Debug.Assert(knowledge != null);
            var node = UserGraph.UpdateSolvingCache(knowledge, false);

            if (node != null)
            {
                object obj1     = UserGraph.SearchPrevInnerLoopNode(node);
                var    obj1Node = obj1 as BehaviorGraphNode;
                var    obj1Lst  = obj1 as List <BehaviorGraphNode>;
                if (obj1Node != null)
                {
                    CurrentStateNode = obj1Node;
                }
                if (obj1Lst != null && obj1Lst.Count != 0)
                {
                    CurrentStateNode = obj1Lst[0];
                }
            }
        }
コード例 #4
0
        private string UpdateVerifiedMessage()
        {
            var status = UserGraph.CheckSolvingStatus();

            if (status == BehaviorGraph.SolvingStatus.Partial &&
                UserGraph.CurrentSolvingStatus == BehaviorGraph.SolvingStatus.None)
            {
                UserGraph.CurrentSolvingStatus = status;
                return(AGTutorMessage.SolvingPartialProblem);
            }

            if (status == BehaviorGraph.SolvingStatus.Complete &&
                UserGraph.CurrentSolvingStatus == BehaviorGraph.SolvingStatus.Partial)
            {
                UserGraph.CurrentSolvingStatus = status;
                return(AGTutorMessage.SolvedProblem);
            }

            if (status == BehaviorGraph.SolvingStatus.Complete &&
                UserGraph.CurrentSolvingStatus == BehaviorGraph.SolvingStatus.None)
            {
                UserGraph.CurrentSolvingStatus = status;
                return(AGTutorMessage.SolvedProblem);
            }

            return(null);
        }
コード例 #5
0
        /// <summary>
        /// The method to get a list of the third level connections of the given username
        /// </summary>
        /// <param name="username">the given username</param>
        /// <returns>a list with the usernames</returns>
        public static async Task <List <string> > GetThirdLevelFriends(string username)
        {
            UserGraph graph = await GetUserGraph(username);

            List <Path> friends = await GetOnlyFriends(username);

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

            friendsName.Add(username);

            foreach (Path item in graph.paths)
            {
                if (item.user1 == username || item.user2 == username)
                {
                    if (item.user1 != username)
                    {
                        friendsName.Add(item.user1);
                    }
                    else
                    {
                        friendsName.Add(item.user2);
                    }
                }
            }

            List <string> thirdFriends = graph.nodes;

            foreach (string item in friendsName)
            {
                thirdFriends.Remove(item);
            }

            return(thirdFriends);
        }
コード例 #6
0
        // GET: /
        public async Task <ActionResult> Index()
        {
            string          userID = User.Identity.GetUserId();
            ApplicationUser user   = db.Users.Find(userID);

            IList <int>      tagIDs = (from userToTag in db.UsersTags where (userToTag.UserID == userID) select userToTag.TagID).ToList();
            IQueryable <Tag> tags   = (from tag in db.Tags where tagIDs.Contains(tag.ID) select tag);

            ViewBag.UserTags = tags;

            if (userID != null)
            {
                string    username = user.UserName;
                UserGraph graph    = await Services.GetUserGraph(username);

                // need to remove one because this dimension contains self user
                int dimension = (graph.nodes.Count - 1);

                if (dimension < 0)
                {
                    dimension++;
                }

                ViewBag.Dimension = dimension;
            }

            return(View(user));
        }
コード例 #7
0
        static void Main(string[] args)
        {
            RandomDataGenerator generator = new RandomDataGenerator();
            List <UserNode>     users     = generator.Generate();
            var userGraph = new UserGraph(users);

            var shortestDistance = userGraph.GetShortestDistanceBetweenNodes(users[0], users[6]);
        }
 public void SetUp()
 {
     _users = new List <UserNode>
     {
         new UserNode("Sanyi", "Sanyi"),
         new UserNode("Bela", "Bela"),
         new UserNode("Brandon", "Siska"),
         new UserNode("Sophie", "Varga"),
         new UserNode("Wallie", "Eva")
     };
     SeedData();
     _userGraph = new UserGraph(_users);
 }
コード例 #9
0
        private bool GoalVerify(IKnowledge obj, EqGoal eqGoal, out string msg, out object output)
        {
            msg    = AGTutorMessage.VerifyWrong;
            output = null;

            List <Tuple <object, object> > trace = null;

            var agPropExpr = new AGPropertyExpr(obj.Expr, eqGoal);

            agPropExpr.IsSelected = true;
            agPropExpr.GenerateSolvingTrace();
            trace = agPropExpr.AutoTrace;

            BehaviorGraphNode node;

            if (trace == null || trace.Count == 0)
            {
                node = UserGraph.UpdateSolvingCache(agPropExpr);
                //node = UserGraph.SearchInnerLoopNode(eqGoal);

                if (node == null)
                {
                    return(false);
                }
            }
            if (trace != null)
            {
                bool matchResult = UserGraph.Match(trace);
                if (!matchResult)
                {
                    return(false);
                }
                //insert nodes
                UserGraph.Insert(trace);
                CurrentStateNode = UserGraph.SearchInnerLoopNode(obj); //update _currentStateNode;
            }
            else
            {
                CurrentStateNode = UserGraph.SearchInnerLoopNode(eqGoal);
            }

            /* var nextTuple1 = UserGraph.SearchNextInnerLoopNode(CurrentStateNode);
             * if (nextTuple1 == null) // query-end
             * {
             *   msg = AGTutorMessage.SolvedProblem;
             *   return true;
             * }
             */
            msg = AGTutorMessage.VerifyCorrect;
            return(true);
        }
コード例 #10
0
        /// <summary>
        /// The method to get a list of the friend id's of the given user graph
        /// </summary>
        /// <param name="graph">the user graph</param>
        /// <returns>a list of the friend id's</returns>
        private List <string> FindFriendIds(UserGraph graph)
        {
            List <string> usernames = graph.nodes;
            List <string> userIds   = new List <string>();

            foreach (ApplicationUser item in db.Users)
            {
                if (usernames.Contains(item.UserName))
                {
                    userIds.Add(item.Id);
                }
            }

            return(userIds);
        }
コード例 #11
0
        /// <summary>
        /// The method to get the friend connection to the given user
        /// </summary>
        /// <param name="username">the user username</param>
        /// <returns>a list of the friend connections</returns>
        public static async Task <List <Path> > GetOnlyFriends(string username)
        {
            UserGraph graph = await GetUserGraph(username);

            List <Path> friends = new List <Path>();

            foreach (Path item in graph.paths)
            {
                if (item.user1 == username || item.user2 == username)
                {
                    friends.Add(item);
                }
            }

            return(friends);
        }
コード例 #12
0
        private void DeepVerify(IKnowledge source, IKnowledge obj, out string msg, out object output)
        {
            msg = AGTutorMessage.VerifyWrong;

            object result;
            var    shapeExpr = obj as AGShapeExpr;

            if (shapeExpr != null)
            {
                result = Reasoner.Instance.RelationValidate(shapeExpr.ShapeSymbol, out output);
            }
            else
            {
                result = Reasoner.Instance.RelationValidate(obj.Expr, out output);
            }

            if (result == null)
            {
                return;
            }

            var inputApproximateMatched = result as bool?;

            if (inputApproximateMatched != null)
            {
                if (inputApproximateMatched.Value)
                {
                    msg = AGTutorMessage.VerifyCorrect;
                }
                return;
            }

            var trace = result as List <Tuple <object, object> >;

            if (trace != null)
            {
                bool matchResult = UserGraph.Match(trace); //match and update
                if (matchResult)
                {
                    //insert nodes
                    UserGraph.Insert(trace);
                    CurrentStateNode = UserGraph.SearchInnerLoopNode(source); //update _currentStateNode;
                    //Debug.Assert(_currentStateNode != null);
                    msg = AGTutorMessage.VerifyCorrect;
                }
            }
        }
コード例 #13
0
 public void Reset(object obj)
 {
     if (obj == null)
     {
         _currentStepHintRequired = true;
         //_currentStepAnswerRequired = true;
         CurrentStateNode = null;
     }
     else
     {
         if (TutorMode)
         {
             var    node     = UserGraph.SearchInnerLoopNode(obj);
             object obj1     = UserGraph.SearchPrevInnerLoopNode(node);
             var    obj1Node = obj1 as BehaviorGraphNode;
             var    obj1Lst  = obj1 as List <BehaviorGraphNode>;
             if (obj1Node != null)
             {
                 CurrentStateNode = obj1Node;
             }
             if (obj1Lst != null)
             {
                 CurrentStateNode = obj1Lst[0];
             }
             _currentStepHintRequired = true;
             //_currentStepAnswerRequired = true;
         }
         else
         {
             var    node     = ObjectGraph.SearchInnerLoopNode(obj);
             object obj1     = ObjectGraph.SearchPrevInnerLoopNode(node);
             var    obj1Node = obj1 as BehaviorGraphNode;
             var    obj1Lst  = obj1 as List <BehaviorGraphNode>;
             if (obj1Node != null)
             {
                 CurrentStateNode = obj1Node;
             }
             if (obj1Lst != null)
             {
                 CurrentStateNode = obj1Lst[0];
             }
         }
     }
 }
コード例 #14
0
        private bool ShapeVerify(IKnowledge obj, ShapeSymbol shape, out string msg, out object output)
        {
            msg    = AGTutorMessage.VerifyWrong;
            output = null;

            List <Tuple <object, object> > trace = null;

            var agShapeExpr = new AGShapeExpr(obj.Expr, shape);

            agShapeExpr.IsSelected = true;
            agShapeExpr.GenerateSolvingTrace();
            trace = agShapeExpr.AutoTrace;

            if (trace == null || trace.Count == 0)
            {
                return(false);
            }

            /*   var lastTuple = trace[trace.Count - 1] as Tuple<object, object>;
             * var lastLst = lastTuple.Item2 as List<object>;
             * Debug.Assert(lastLst != null);
             * Debug.Assert(lastLst.Count != 0);
             * var lastTs = lastLst[lastLst.Count - 1] as TraceStepExpr;*/
            bool matchResult = UserGraph.Match(trace); //match and update

            if (!matchResult)
            {
                return(false);
            }

            //insert nodes
            UserGraph.Insert(trace);
            CurrentStateNode = UserGraph.SearchInnerLoopNode(obj); //update _currentStateNode;
            //var nextTuple1 = UserGraph.SearchNextInnerLoopNode(CurrentStateNode);

            /*  if (nextTuple1 == null) // query-end
             * {
             *    msg = AGTutorMessage.SolvedProblem;
             *    return true;
             * }*/
            msg = AGTutorMessage.VerifyCorrect;
            return(true);
        }
コード例 #15
0
        private bool LoadUserModel(int problemIndex)
        {
            _problemIndex = problemIndex;

            var behaviorGraph = BehaviorUserModelLoader.Instance.LoadProblem(problemIndex);

            if (behaviorGraph != null)
            {
                UserGraph        = behaviorGraph;
                CurrentStateNode = UserGraph.RetrieveInitInnerNode();
                HasBehaviorModel = true;
                return(true);
            }

            Debug.Assert(UserGraph == null);
            HasBehaviorModel = false;
            //Capture User Input of the pre-programmed problems.
            return(false);
        }
コード例 #16
0
        // GET: /Statistics
        public async Task <ActionResult> Statistics()
        {
            UserDimension users = await Services.GetAllUsers();

            ViewBag.Dimension = users.users.Count;

            UserDimension userStrenght = await Services.GetAllUsersStrenght();

            ViewBag.Strenght = userStrenght.users;

            ViewBag.Users = users.users;

            ViewBag.AnomUserTag = GetOverallUserTagCount(users.users.Count);

            ViewBag.AnomConnTag = await GetOverallConnectionTagCount();

            // authenticated users
            string userID = User.Identity.GetUserId();

            if (userID != null && User.IsInRole("User"))
            {
                ApplicationUser user  = db.Users.Find(userID);
                UserGraph       graph = await Services.GetUserGraph(user.UserName);

                int nrFriends = graph.nodes.Count;
                ViewBag.nrFriends = nrFriends;

                if (nrFriends > 0)
                {
                    ViewBag.AuthConnTag = await GetAuthenticatedConnectionTagCount(user.UserName);

                    List <string> friendIds = FindFriendIds(graph);

                    ViewBag.AuthUserTag = GetAuthenticatedUserTagCount(graph.nodes.Count, friendIds);
                }
            }

            return(View());
        }
コード例 #17
0
        private QueryFeedbackState VerifyBehaviorGraph(object obj, out string msg, out object output)
        {
            msg    = null;
            output = null;
            Debug.Assert(obj != null);
            var iKnowledge = obj as IKnowledge;

            Debug.Assert(iKnowledge != null);
            //verify user's own step
            var matchedNode = UserGraph.UpdateSolvingCache(iKnowledge);

            msg = matchedNode == null ?
                  AGTutorMessage.VerifyWrong : AGTutorMessage.VerifyCorrect;
            //TODO, wrong node derivation
            if (matchedNode == null)
            {
                //equation -> higher Level Semantics, such as goal or shape.
                var gObj       = Reasoner.Instance.ExprValidate(iKnowledge.Expr);
                var gKnowledge = gObj as IKnowledge;
                if (gKnowledge != null)
                {
                    Verify(iKnowledge, gKnowledge, out msg, out output);
                    if (msg.Equals(AGTutorMessage.VerifyCorrect))
                    {
                        string str = UpdateVerifiedMessage();
                        if (str != null)
                        {
                            msg = str;
                        }
                        return(QueryFeedbackState.TutorQueryProcessedVerify);
                    }
                }
                var gKnowledgeLst = gObj as List <object>;
                if (gKnowledgeLst != null)
                {
                    foreach (var gKTemp in gKnowledgeLst)
                    {
                        gKnowledge = gKTemp as IKnowledge;
                        if (gKnowledge == null)
                        {
                            continue;
                        }

                        Verify(iKnowledge, gKnowledge, out msg, out output);
                        if (!msg.Equals(AGTutorMessage.VerifyWrong))
                        {
                            return(QueryFeedbackState.TutorQueryProcessedVerify);
                        }
                    }
                }
                return(QueryFeedbackState.TutorQueryProcessedVerify);
            }
            Debug.Assert(matchedNode != null);
            CurrentStateNode = matchedNode;
            string str1 = UpdateVerifiedMessage();

            if (str1 != null)
            {
                msg = str1;
            }
            return(QueryFeedbackState.TutorQueryProcessedVerify);

            /* var nextTuple = UserGraph.SearchNextInnerLoopNode(matchedNode);
             * if (nextTuple == null)
             * {
             *   if (UserGraph.IsPartialCorrect())
             *   {
             *       msg = AGTutorMessage.SolvingPartialProblem;
             *   }
             *   else
             *   {
             *       msg = AGTutorMessage.SolvedProblem;
             *   }
             * }*/
        }
コード例 #18
0
        private QueryFeedbackState QueryBehaviorGraph(object obj, out string msg, out object output)
        {
            msg    = null;
            output = null;
            if (UserGraph == null)
            {
                return(QueryFeedbackState.QueryFailed);
            }
            if (UserGraph.Nodes.Count == 0 || UserGraph.Nodes.Count == 1)
            {
                msg = "TODO";
                return(QueryFeedbackState.QueryFailed);
            }

/*            if (!_queryProcessed)
 *          {
 *              _queryProcessed = true;
 *              output = UserGraph.SearchAllOuterEdgeInfos();
 *              msg = AGTutorMessage.InputQuery;
 *              return QueryFeedbackState.TutorQueryStarted;
 *          }*/

            if (obj != null)
            {
                return(VerifyBehaviorGraph(obj, out msg, out output));
            }
            Debug.Assert(obj == null);
            Debug.Assert(_currentStateNode != null);

            object            edgeInfo = null;
            BehaviorGraphNode nextNode = null;
            var nextTuple1             = UserGraph.SearchNextInnerLoopNode(_currentStateNode);

            if (nextTuple1 == null) // query-end
            {
                //partial checking
                BehaviorGraph.SolvingStatus ss = UserGraph.CheckSolvingStatus();
                if (ss == BehaviorGraph.SolvingStatus.Complete)
                {
                    msg = AGDemonstrationMessage.QueryEnd;
                    return(QueryFeedbackState.TutorQueryEnded);
                }
                else if (ss == BehaviorGraph.SolvingStatus.Partial)
                {
                    int nextGoalIndex = UserGraph.FindGoalIndex();
                    _currentStateNode = UserGraph.RetrieveInitInnerNode(nextGoalIndex);
                    nextTuple1        = UserGraph.SearchNextInnerLoopNode(_currentStateNode);
                    if (nextTuple1 == null)
                    {
                        msg = AGDemonstrationMessage.QueryEnd;
                        return(QueryFeedbackState.TutorQueryEnded);
                    }
                    CurrentStepHintRequired = true;
                }
                else
                {
                    msg = AGDemonstrationMessage.QueryEnd;
                    return(QueryFeedbackState.TutorQueryEnded);
                }
            }

            #region Path Selection

            var tuple11    = nextTuple1 as Tuple <object, object>;
            var tuple11Lst = nextTuple1 as List <Tuple <object, object> >;

            if (tuple11 != null)
            {
                edgeInfo = tuple11.Item1;
                nextNode = tuple11.Item2 as BehaviorGraphNode;
                //_currentStateNode = nextNode;
            }
            if (tuple11Lst != null)
            {
                var tupleTemp = tuple11Lst[0];
                edgeInfo = tupleTemp.Item1;
                nextNode = tupleTemp.Item2 as BehaviorGraphNode;
                //_currentStateNode = nextNode;
            }

            #endregion

            if (_currentStepHintRequired)
            {
                if (edgeInfo != null)
                {
                    var innerEdgeProp = edgeInfo as InnerLoopEdgeProperty;
                    Debug.Assert(innerEdgeProp != null);
                    msg = AGTutorMessage.QueryIntermediate;
                    _currentStepHintRequired = false;
                    //int parentIndex = UserGraph.SearchOuterLoopNodeIndex(_currentStateNode);
                    int parentIndex = UserGraph.SearchOuterLoopNodeIndex(nextNode);
                    var lst1        = UserGraph.SearchAllOuterEdgeInfos();
                    var tuple       = new Tuple <object, object, object>(innerEdgeProp.MetaRule, lst1, parentIndex);
                    output = tuple;
                }
                return(QueryFeedbackState.TutorQueryProcessedHint);
            }
            Debug.Assert(nextNode != null);
            _currentStepHintRequired = true;
            var nodeState = nextNode.State as InnerLoopBehaviorState;
            Debug.Assert(nodeState != null);
            var expr           = IKnowledgeGenerator.Generate(nodeState.UserKnowledge);
            var innerEdgeProp1 = edgeInfo as InnerLoopEdgeProperty;
            Debug.Assert(innerEdgeProp1 != null);
            var appliedRule = innerEdgeProp1.AppliedRule;
            //int parentIndex1 = UserGraph.SearchOuterLoopNodeIndex(_currentStateNode);
            int parentIndex1 = UserGraph.SearchOuterLoopNodeIndex(nextNode);
            var lst2         = UserGraph.SearchAllOuterEdgeInfos();
            output           = new Tuple <object, object, object, object>(appliedRule, expr, lst2, parentIndex1);
            CurrentStateNode = nextNode;
            return(QueryFeedbackState.TutorQueryProcessedAnswer);
        }
コード例 #19
0
    public static void Start(SchemaBuilder sb, string?systemUserName, string?anonymousUserName)
    {
        if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
        {
            SystemUserName    = systemUserName;
            AnonymousUserName = anonymousUserName;

            CultureInfoLogic.AssertStarted(sb);

            sb.Include <UserEntity>()
            .WithExpressionFrom((RoleEntity r) => r.Users())
            .WithQuery(() => e => new
            {
                Entity = e,
                e.Id,
                e.UserName,
                e.Email,
                e.Role,
                e.State,
                e.CultureInfo,
            });

            sb.Include <RoleEntity>()
            .WithSave(RoleOperation.Save)
            .WithDelete(RoleOperation.Delete)
            .WithQuery(() => r => new
            {
                Entity = r,
                r.Id,
                r.Name,
            });

            roles           = sb.GlobalLazy(CacheRoles, new InvalidateWith(typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);
            rolesInverse    = sb.GlobalLazy(() => roles.Value.Inverse(), new InvalidateWith(typeof(RoleEntity)));
            rolesByName     = sb.GlobalLazy(() => roles.Value.ToDictionaryEx(a => a.ToString() !), new InvalidateWith(typeof(RoleEntity)));
            mergeStrategies = sb.GlobalLazy(() =>
            {
                var strategies = Database.Query <RoleEntity>().Select(r => KeyValuePair.Create(r.ToLite(), r.MergeStrategy)).ToDictionary();

                var graph = roles.Value;

                Dictionary <Lite <RoleEntity>, RoleData> result = new Dictionary <Lite <RoleEntity>, RoleData>();
                foreach (var r in graph.CompilationOrder())
                {
                    var strat = strategies.GetOrThrow(r);

                    var baseValues = graph.RelatedTo(r).Select(r2 => result[r2].DefaultAllowed);

                    result.Add(r, new RoleData
                    {
                        MergeStrategy  = strat,
                        DefaultAllowed = strat == MergeStrategy.Union ? baseValues.Any(a => a) : baseValues.All(a => a)
                    });
                }

                return(result);
            }, new InvalidateWith(typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);

            sb.Schema.EntityEvents <RoleEntity>().Saving += Schema_Saving;

            UserGraph.Register();

            EmailModelLogic.RegisterEmailModel <UserLockedMail>(() => new EmailTemplateEntity
            {
                Messages = CultureInfoLogic.ForEachCulture(culture => new EmailTemplateMessageEmbedded(culture)
                {
                    Text =
                        "<p>{0}</p>".FormatWith(AuthEmailMessage.YourAccountHasBeenLockedDueToSeveralFailedLogins.NiceToString()) +
                        "<p>{0}</p>".FormatWith(AuthEmailMessage.YouCanResetYourPasswordByFollowingTheLinkBelow.NiceToString()) +
                        "<p><a href=\"@[m:Url]\">@[m:Url]</a></p>",
                    Subject = AuthEmailMessage.YourAccountHasBeenLocked.NiceToString()
                }).ToMList()
            });
        }
    }
 public void TearDown()
 {
     _users     = null;
     _userGraph = null;
 }