Exemplo n.º 1
0
        public void Remove(Model.Model m)
        {
            m.Delete();
            switch (m.Table)
            {
            case "Educations":
                Educations.Remove((Education)m);
                break;

            case "Students":
                Students.Remove((Student)m);
                break;

            case "Exams":
                Exams.Remove((Exam)m);
                break;

            case "Attempts":
                Attempts.Remove((Attempt)m);
                break;
            }

            dao.UpdateData();
            m.AfterDelete();
        }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);

        if (!authorized)
        {
            return(false);
        }
        var rd         = httpContext.Request.RequestContext.RouteData;
        var action     = rd.GetRequiredString("action");
        var controller = rd.GetRequiredString("controller");
        var key        = string.Format("throttle-{0}-{1}-{2}", httpContext.User.Identity.Name, controller, action);
        var policy     = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(Seconds),
        };
        var attempts = MemoryCache.Default.Get(key) as Attempts;

        if (attempts == null)
        {
            attempts = new Attempts();
            MemoryCache.Default.Set(key, attempts, policy);
        }
        if (attempts.NumberOfAccess < Count)
        {
            attempts.NumberOfAccess++;
            return(true);
        }
        httpContext.Items["throttled"] = true;
        return(false);
    }
Exemplo n.º 3
0
    public void OnAttempt(bool win, float timeOfDeath, float distanceTravelled, float previousCompetenceValue)
    {
        Attempts.AttemptModel attempt = new Attempts.AttemptModel(win, timeOfDeath, distanceTravelled, previousCompetenceValue);

        FileStream   stream = new FileStream(Application.persistentDataPath + "/" + dataFileName, FileMode.OpenOrCreate);
        StreamReader reader = new StreamReader(stream);
        string       json   = reader.ReadToEnd();

        stream.Close();
        stream = new FileStream(Application.persistentDataPath + "/" + dataFileName, FileMode.Truncate);

        Attempts attempts = new Attempts();

        if (!string.IsNullOrEmpty(json))
        {
            attempts = JsonUtility.FromJson <Attempts> (json);
        }

        attempts.Add(attempt);
        json = JsonUtility.ToJson(attempts);
        StreamWriter writer = new StreamWriter(stream);

        writer.Write(json);
        writer.Flush();
        stream.Close();
    }
Exemplo n.º 4
0
        public void Add(Model.Model m)
        {
            switch (m.Table)
            {
            case "Educations":
                Educations.Add((Education)m);
                break;

            case "Students":
                Students.Add((Student)m);
                break;

            case "Exams":
                Exams.Add((Exam)m);
                break;

            case "Attempts":
                Attempts.Add((Attempt)m);
                break;
            }

            DataRow dr = dao.Data.Tables[m.Table].NewRow();

            m.FillRow(dr);
            dao.Data.Tables[m.Table].Rows.Add(dr);
            dao.UpdateTable(m.Table);
            m.Data = dr;
            m.AfterCreate();
        }
Exemplo n.º 5
0
        private static bool Output(long status)
        {
            var previousPosition  = droidPosition;
            var attemptedPosition = Compass.PositionAfterMovement(droidPosition, Attempt);

            if (status == 0)
            {
                // The repair droid hit a wall. Its position has not changed.
                area.Set(attemptedPosition, Day15Cell.Wall);
                Day15Debug.Set(attemptedPosition, Day15Cell.Wall);
                Day15Debug.WriteLine("BLOCKED");
            }
            else
            {
                // The repair droid has moved one step in the requested direction.
                Day15Debug.WriteLine("OK");
                droidPosition = attemptedPosition;
                if (!Backtracking)
                {
                    area.Set(attemptedPosition, Day15Cell.Open);
                    Day15Debug.Set(attemptedPosition, Day15Cell.Open);
                    if (status == 2)
                    {
                        oxygenSystemPosition = attemptedPosition;
                    }
                    EnteredFrom[attemptedPosition] = Attempt;
                    Visited.Add(attemptedPosition);
                    Attempts.Push(Compass.AllDirections);
                }
            }

            return((Attempts.Count() > 1) || (Attempts.Peek().Count > 0));
        }
Exemplo n.º 6
0
        public void UpdateAttemptState(ConnectionStateBase newState, ILogger logger)
        {
            switch (newState.State)
            {
            case ConnectionState.Connecting:
                logger.Debug("Recording connection attempt.");
                Attempts.Add(new ConnectionAttempt(_now()));
                break;

            case ConnectionState.Failed:
            case ConnectionState.Closed:
            case ConnectionState.Connected:
                logger.Debug("Resetting Attempts collection.");
                Reset();
                break;

            case ConnectionState.Suspended:
            case ConnectionState.Disconnected:
                logger.Debug($"Recording failed attempt for state {newState.State}.");
                if (newState.Exception != null)
                {
                    RecordAttemptFailure(newState.State, newState.Exception);
                }
                else
                {
                    RecordAttemptFailure(newState.State, newState.Error);
                }

                break;
            }
        }
Exemplo n.º 7
0
 public static Area <Day15Cell> GenerateMaze()
 {
     area = new Area <Day15Cell>(Day15Cell.Unexplored);
     Attempts.Push(Compass.AllDirections);
     new IntCodeComputer(GetData(), Input, Output).Run();
     return(area);
 }
Exemplo n.º 8
0
        public string GetHost()
        {
            var    lastFailedState = Attempts.SelectMany(x => x.FailedStates).LastOrDefault(x => x.ShouldUseFallback());
            string customHost      = "";

            if (lastFailedState != null)
            {
                if (lastFailedState.State == ConnectionState.Disconnected)
                {
                    customHost = _connection.FallbackHosts[DisconnectedCount % _connection.FallbackHosts.Count];
                }
                if (lastFailedState.State == ConnectionState.Suspended && SuspendedCount > 1)
                {
                    customHost =
                        _connection.FallbackHosts[(DisconnectedCount + SuspendedCount) % _connection.FallbackHosts.Count];
                }

                if (customHost.IsNotEmpty())
                {
                    _connection.Host = customHost;
                    return(customHost);
                }
            }

            _connection.Host = Options.FullRealtimeHost();
            return(_connection.Host);
        }
 public void EndGame(string reason)
 {
     if (!isGameEnded)
     {
         Debug.Log("End reason : " + reason);
         PlayerAdaptiveInfo.IncreaseRestartCount();
         Attempts attempt = new Attempts();
         attempt.Completed   = false;
         attempt.FailureType = reason;
         attempt.Level       = PlayerAdaptiveInfo.getCurrLevel();
         attempt.SessionId   = PlayerStats.SessionDetails.SessionId;
         attempt.SideForce   = PlayerAdaptiveInfo.adaptiveInfo.sideForce;
         attempt.Speed       = PlayerAdaptiveInfo.adaptiveInfo.currSpeed;
         PlayerStats.AddAttemptData(attempt);
         if (reason.Equals(COLLISION))
         {
             PlayerAdaptiveInfo.IncreaseCollisionCount();
         }
         PlayerAdaptiveInfo.adjustSpeedOrLevel();
         Debug.Log("Game Over");
         isGameEnded = true;
         Invoke("Restart", restartDelay);
         //Restart ();
     }
 }
Exemplo n.º 10
0
        public void UpdateAttemptState(ConnectionStateBase newState)
        {
            lock (_syncLock)
                switch (newState.State)
                {
                case ConnectionState.Connecting:
                    Attempts.Add(new ConnectionAttempt(Now()));
                    break;

                case ConnectionState.Failed:
                case ConnectionState.Closed:
                case ConnectionState.Connected:
                    Reset();
                    break;

                case ConnectionState.Suspended:
                case ConnectionState.Disconnected:
                    if (newState.Exception != null)
                    {
                        RecordAttemptFailure(newState.State, newState.Exception);
                    }
                    else
                    {
                        RecordAttemptFailure(newState.State, newState.Error);
                    }
                    break;
                }
        }
Exemplo n.º 11
0
        private List <GroupedAttemptsByLesson> GetGroupedAttempts()
        {
            var groupedAttempts = new List <GroupedAttemptsByLesson>();

            if (Attempts == null || Attempts.Count == 0)
            {
                return(groupedAttempts);
            }

            foreach (var groupedItems in Attempts.OrderBy(x => x.Lesson.LessonOrder).GroupBy(x => x.LessonID))
            {
                int     highScore        = groupedItems.Max(x => x.Score);
                Attempt highScoreAttempt = groupedItems.OrderByDescending(x => x.DateCompleted).First(x => x.Score == highScore);
                groupedAttempts.Add(new GroupedAttemptsByLesson()
                {
                    Lesson        = groupedItems.First().Lesson,
                    TotalAttempts = groupedItems.First().AttemptID == -1 && groupedItems.Count() == 1 ? 0 :  groupedItems.Count(),
                    TotalTimes    = groupedItems.Sum(x => x.TimeToComplete),
                    HighScore     = highScore,
                    DateCompleted = highScoreAttempt.DateCompleted,
                    Infractions   = highScoreAttempt.Infractions,
                    IsComplete    = highScoreAttempt.IsComplete
                });
            }

            return(groupedAttempts);
        }
Exemplo n.º 12
0
 private void RecordAttemptFailure(ConnectionState state, Exception ex)
 {
     if (Attempts.Any())
     {
         var attempt = Attempts.Last();
         attempt.FailedStates.Add(new AttemptFailedState(state, ex));
     }
 }
Exemplo n.º 13
0
 public void Reset()
 {
     lock (_syncLock)
     {
         Attempts.Clear();
         TriedToRenewToken = false;
     }
 }
Exemplo n.º 14
0
        public void AnalysisReceivedData(ref int attemptNumber)
        {
            bool winnerNumbersCowIsAlreadyFound = Convert.ToBoolean(WinnerNumbersCows.Count);

            for (int k = 0; k < Attempts.Count; k++)
            {
                Attempt attempt = Attempts[k];
                if (attempt.CountBulls + attempt.CountCows == 4)
                {
                    if (attempt.CountBulls == 3 && attempt.CountCows == 1)
                    {
                        Console.WriteLine($"Вы запутались в решении поскольку, невозможно чтобы было {attempt.CountBulls} быка и {attempt.CountCows}");
                        Attempts.Remove(attempt);
                        attemptNumber--;
                    }
                    else
                    {
                        if (attempt.CountBulls == 4)
                        {
                            Console.WriteLine($"Решение найдено - > {attempt.Number}");
                            break;
                        }
                        else
                        {
                            if (!winnerNumbersCowIsAlreadyFound)
                            {
                                Console.WriteLine($"Найдены все цифры которые используются в решении -> {attempt.Number}");
                                for (int i = 0; i < attempt.Number.Length; i++)
                                {
                                    WinnerNumbersCows.Add(attempt.Number[i]);
                                }
                                winnerNumbersCowIsAlreadyFound = true;
                                Delete();
                            }
                            FindBullsForWin();
                            break;
                        }
                    }
                }
                else
                {
                    if (attempt.CountBulls + attempt.CountCows == 0)
                    {
                        Console.WriteLine($"Найдено числа которые не используются в решении -> {attempt.Number}");
                        Delete(attempt);
                        Attempts.Remove(attempt);
                        attemptNumber--;
                        break;
                    }
                }
            }
            if (Attempts.Count != 0)
            {
                FindCowsForWin(Attempts[Attempts.Count - 1]);
            }
        }
    public static void AddAttemptData(Attempts attempt)
    {
        System.DateTime epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
        float           cur_time   = (float)(System.DateTime.UtcNow - epochStart).TotalSeconds;
        // TO BE IMPLEMENTED
        //var attmpt = new Attempts{};
        var ds = new DataService("tempDatabase.db");

        ds.CreateGivenAttempt(attempt);
    }
Exemplo n.º 16
0
        private void RecordAttemptFailure(ConnectionState state, ErrorInfo error)
        {
            var attempt = Attempts.LastOrDefault() ?? new ConnectionAttempt(_now());

            attempt.FailedStates.Add(new AttemptFailedState(state, error));
            if (Attempts.Count == 0)
            {
                Attempts.Add(attempt);
            }
        }
Exemplo n.º 17
0
        public override int Guess()
        {
            var result = BasicPlayer.Guess();

            while (Attempts.Contains(result))
            {
                result = BasicPlayer.Guess();
            }

            return(result);
        }
Exemplo n.º 18
0
 public void RecordAttemptFailure(ConnectionState state, Exception ex)
 {
     lock (_syncLock)
     {
         if (Attempts.Any())
         {
             var attempt = Attempts.Last();
             attempt.FailedStates.Add(new AttemptFailedState(state, ex));
         }
     }
 }
Exemplo n.º 19
0
        public CodeResult EnterCode(Code code)
        {
            var result = Code.Match(code);

            Attempts.Add(result);
            if (result.Correct)
            {
                FinishedAt = DateTimeOffset.UtcNow;
                Score      = new Score(Id, (short)Attempts.Count, Duration.Value);
            }
            return(result);
        }
Exemplo n.º 20
0
 public Boolean PassedByDate(DateTime?before)
 {
     if (!before.HasValue)
     {
         return(Passed);
     }
     else
     {
         dtoQuizAttemptInfo last = Attempts.Where(q => q.CompletedOn.HasValue && q.CompletedOn <= before.Value).OrderByDescending(a => a.CompletedOn).ToList().FirstOrDefault();
         return(last != null && (last.Completed && (!Evaluable || (Evaluable && last.Passed))));
     }
 }
Exemplo n.º 21
0
 public Boolean CompiledBeforeDate(DateTime?before)
 {
     if (!before.HasValue)
     {
         return(Attempts.Any());
     }
     else
     {
         dtoQuizAttemptInfo last = Attempts.Where(q => !q.CompletedOn.HasValue || q.CompletedOn <= before.Value).OrderByDescending(a => a.Id).ToList().FirstOrDefault();
         return(last != null);
     }
 }
Exemplo n.º 22
0
 public void RecordAttemptFailure(ConnectionState state, ErrorInfo error)
 {
     lock (_syncLock)
     {
         var attempt = Attempts.LastOrDefault() ?? new ConnectionAttempt(Config.Now());
         attempt.FailedStates.Add(new AttemptFailedState(state, error));
         if (Attempts.Count == 0)
         {
             Attempts.Add(attempt);
         }
     }
 }
Exemplo n.º 23
0
        public async Task AddAttemptToDatabaseAsync(string email, string ipAddress, bool isSuccess)
        {
            var user = await Context.Users.FirstOrDefaultAsync(p => p.Email == email);

            Attempts attempt = new Attempts {
                TimeStamp = DateTime.Now,
                Success   = isSuccess,
                IpAddress = ipAddress,
                User      = user
            };

            Context.Attempts.Add(attempt);
            await Context.SaveChangesAsync();
        }
Exemplo n.º 24
0
 void Start()
 {
     isFinished = false;
     canvas     = GameObject.Find("Canvas");
     if (PlayerManager.numberOfPlayers == 1)
     {
         attempts     = GameObject.Find("Attempts/Time").GetComponent <Attempts>(); //References the scoreManager
         ionPlacement = gameObject.GetComponentInChildren <IonPlacement>();
         origPosIon   = ionPlacement.cannotPlacePositive;                           // What is it set to originally?
         origNegIon   = ionPlacement.cannotPlaceNegative;
     }
     p1CanShoot = true;
     p2CanShoot = true;
     renderers  = new List <GameObject>();
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        public async Task <Question> SubmitAnswer(Answer answer)
        {
            var question = this.treasureHuntDBContext.Questions
                           .Include(x => x.Answers)
                           .FirstOrDefault(x => x.Id == answer.Question.ID);

            if (question != null)
            {
                if (answer.Skipped == true)
                {
                    var attempt = new Attempts()
                    {
                        AnswerId      = null,
                        ParticipantId = this.session.UserID.Value,
                        ProgressedOn  = DateTime.Now,
                        QuestionId    = question.Id,
                        Skipped       = true
                    };

                    this.treasureHuntDBContext.Attempts.Add(attempt);
                    await this.treasureHuntDBContext.SaveChangesAsync();
                }
                else
                {
                    var answerObj = question.Answers.FirstOrDefault(x => x.Title.Equals(answer.Title));
                    if (answerObj != null)
                    {
                        var attempt = new Attempts()
                        {
                            AnswerId      = answerObj.Id,
                            ParticipantId = this.session.UserID.Value,
                            ProgressedOn  = DateTime.Now,
                            QuestionId    = question.Id,
                            Skipped       = false
                        };

                        this.treasureHuntDBContext.Attempts.Add(attempt);
                        await this.treasureHuntDBContext.SaveChangesAsync();
                    }
                    else
                    {
                        throw new Exception("Answer is not valid");
                    }
                }
            }

            return(await GetNextQuestion(question.QuizId));
        }
Exemplo n.º 26
0
    public List <Attempts.AttemptModel> GetCurrentAttemptData()
    {
        if (File.Exists(Application.persistentDataPath + "/" + dataFileName))
        {
            FileStream   stream = new FileStream(Application.persistentDataPath + "/" + dataFileName, FileMode.Open);
            StreamReader reader = new StreamReader(stream);
            string       json   = reader.ReadToEnd();

            if (!string.IsNullOrEmpty(json))
            {
                Attempts attempts = JsonUtility.FromJson <Attempts> (json);
                return(attempts.attempts);
            }
        }
        return(null);
    }
Exemplo n.º 27
0
        private static long Input()
        {
            var attempt = Attempts.Pop().Where(dir => !Visited.Contains(Compass.PositionAfterMovement(droidPosition, dir))).ToList();

            if (attempt.Count == 0)
            {
                Backtracking = true;
                Attempt      = Compass.Opposite(EnteredFrom[droidPosition]);
            }
            else
            {
                Backtracking = false;
                Attempt      = attempt[0];
                attempt.RemoveAt(0);
                Attempts.Push(attempt);
            }
            var backTrackingString = Backtracking ? " (BACKTRACKING)" : "";

            Day15Debug.Write($"({droidPosition.x}),{droidPosition.y}) - {Compass.Name(Attempt)}{backTrackingString} : ");
            return(Compass.ToLong(Attempt));
        }
Exemplo n.º 28
0
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);

        if (!authorized)
        {
            return(false);
        }
        var rd         = httpContext.Request.RequestContext.RouteData;
        var action     = rd.GetRequiredString("action");
        var controller = rd.GetRequiredString("controller");
        // Remark: if you are using areas maybe you could also want
        // to constrain the key per area
        var key    = string.Format("throttle-{0}-{1}-{2}", httpContext.User.Identity.Name, controller, action);
        var policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(Seconds),
        };
        // Here we are using the new caching API introduced in .NET 4.0:
        // http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx
        // If you are using an older version of the framework you could use
        // the legacy HttpContext.Cache instead which offers the same expiration
        // policy features as the new
        var attempts = MemoryCache.Default.Get(key) as Attempts;

        if (attempts == null)
        {
            attempts = new Attempts();
            MemoryCache.Default.Set(key, attempts, policy);
        }
        if (attempts.NumberOfAccess < Count)
        {
            attempts.NumberOfAccess++;
            return(true);
        }
        httpContext.Items["throttled"] = true;
        return(false);
    }
Exemplo n.º 29
0
        public void UpdateLists()
        {
            Educations.Clear();
            Students.Clear();
            Exams.Clear();
            Attempts.Clear();
            foreach (DataRow dr in dao.Data.Tables["Educations"].Rows)
            {
                Education e = new Education(dr);
                Educations.Add(e);

                Students.AddRange(e.Students);
                Exams.AddRange(e.Exams);
            }

            foreach (DataRow dr in dao.Data.Tables["Attempts"].Rows)
            {
                Student s = (from stud in Students where stud.ID == (int)dr["student_id"] select stud).First();
                Exam    e = (from ex in Exams where ex.ID == (int)dr["exam_id"] select ex).First();

                Attempts.Add(new Attempt(dr, e, s));
            }
        }
Exemplo n.º 30
0
        /// <summary>
        ///     Discern whether a user has exceeded command-querying limit
        /// </summary>
        /// <returns>true: user timeout</returns>
        public bool GetTimeout()
        {
            bool doTimeout = false;

            if (Attempts.Equals(4))
            {
                if (Seen.AddMinutes(1) < DateTime.UtcNow)
                {
                    Attempts = 0; // if so, reset their attempts to 0
                }
                else
                {
                    doTimeout = true; // if not, timeout is true
                }
            }
            else if (Access > 1)
            // if user isn't admin/op, increment their attempts
            {
                Attempts++;
            }

            return(doTimeout);
        }