private void AddChallenges() { if (challenges.Count == 0) { return; } float totalChallengeRating = challengeRating * levelIndexMultiplier; int iterations = 9999; while (totalChallengeRating > 0 && iterations > 0) { iterations--; challenges = RandomUtil.ShuffleHostList(challenges.Cast <IGeneratedHostInhabitant>().ToList()).Cast <IChallenge>().ToList(); IChallenge challenge = challenges.Find(c => c.GetChallengeRating() <= totalChallengeRating); if (challenge == null) { break; } if (!GetSpawnDirectory(out Directory directory, challenge as IGeneratedHostInhabitant)) { continue; } EntityHandler.I.CreateChallengeAt(directory, challenge, out IChallenge newChallenge); totalChallengeRating -= challenge.GetChallengeRating(); } }
/// <summary> /// Validates the http challenge /// </summary> /// <param name="challenge"><see cref="IChallenge"/></param> private void ValidateHttpChallenge(IChallenge challenge) { var authz = AuthorizationRepository.GetById(challenge.AuthorizationId) ?? throw new MalformedException("Cannot get Authorization by Id"); var url = $"http://{authz.Identifier.Value}/.well-known/acme-challenge/{challenge.Token}"; var request = (HttpWebRequest)WebRequest.Create(url); #if !DEBUG var response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { var stream = response.GetResponseStream(); var reader = new StreamReader(stream); var text = reader.ReadToEnd(); //Accounts.GetById(challenge.Authorization.AccountId var account = AccountService.GetById(authz.AccountId); var thumbprint = Base64Url.Encode(account.Key.GetThumbprint()); var controlValue = $"{challenge.Token}.{thumbprint}"; if (!controlValue.Equals(text)) { var errMessage = "The key authorization file from the server did not match this challenge."; throw new UnauthorizedException(errMessage); } } else { throw new Exception("Respons status is not 200(OK)"); } #else Logger.Warn("HTTP challenge validation is disabled fo DEBUG mode"); #endif }
public static ChallengeDto Map(IChallenge challenge) { return(new ChallengeDto { Id = challenge.Id, Name = challenge.Name, Game = challenge.Game.ToEnum <EnumGame>(), State = challenge.Timeline.State.ToEnum <EnumChallengeState>(), BestOf = challenge.BestOf, Entries = challenge.Entries, SynchronizedAt = challenge.SynchronizedAt.ToTimestampUtcOrNull(), Timeline = new ChallengeTimelineDto { CreatedAt = challenge.Timeline.CreatedAt.ToTimestampUtc(), StartedAt = challenge.Timeline.StartedAt.ToTimestampUtcOrNull(), EndedAt = challenge.Timeline.EndedAt.ToTimestampUtcOrNull(), ClosedAt = challenge.Timeline.ClosedAt.ToTimestampUtcOrNull(), Duration = TimeSpan.FromTicks(challenge.Timeline.Duration.Ticks).ToDuration() }, Scoring = { challenge.Scoring.ToDictionary(scoring => scoring.Key.ToString(), scoring => scoring.Value.ToSingle()) }, Participants = { challenge.Participants.Select(participant => Map(challenge, participant)) } }); }
public async Task <DomainValidationResult <Participant> > SnapshotChallengeParticipantAsync( IChallenge challenge, PlayerId gamePlayerId, IDateTimeProvider synchronizedAt, Func <IScoring, IImmutableSet <Match> > snapshotMatches, CancellationToken cancellationToken = default ) { var result = new DomainValidationResult <Participant>(); if (!challenge.ParticipantExists(gamePlayerId)) { result.AddFailedPreconditionError("Participant doesn't exists."); } if (result.IsValid) { var participant = challenge.FindParticipant(gamePlayerId); var matches = snapshotMatches(challenge.Scoring); participant.Snapshot(matches, synchronizedAt); await _challengeRepository.CommitAsync(true, cancellationToken); return(participant); } return(result); }
internal ChallengeInfo(string name, string contest, IChallenge challenge, Uri uri = null) { Name = name; Contest = contest; Challenge = challenge; Uri = uri; }
private void SubscribeChallenges(int pack, int level) { packIndex = pack; levelIndex = level; currentChallengeLog = GetCurrentChallengeLog(packIndex, levelIndex); if (currentChallengeLog != null) { SaveDataAccessor saveDataAccessor = new SaveDataAccessor(); Dictionary <int, bool> challengeDictionary = saveDataAccessor.GetDataValue <Dictionary <int, bool> >(SaveKeys.COMPLETED_CHALLENGES_SAVE_KEY); int challengeCount = currentChallengeLog.GetChallengeCount(); currentChallenges = new List <IChallenge>(); for (int i = 0; i < challengeCount; i++) { int challengeKey = Challenge.GetChallengeKey(packIndex, levelIndex, i); if (challengeDictionary == null || !challengeDictionary.ContainsKey(challengeKey) || challengeDictionary[challengeKey] == false) { IChallenge challenge = currentChallengeLog.GetChallengeData(i) as IChallenge; challenge.SetUpChallenge(); currentChallenges.Add(challenge); } } } }
public long RunSecond() { var allLines = IChallenge.GetAllLines("6_1.txt"); //var allLines= IChallenge.GetAllLines("test_6_1.txt"); return(GetSharedAnswers(allLines)); }
public async Task RunAsync(Guid id, string basePath) { var challenge = await _context.Challenges .Include(c => c.Results) .FirstOrDefaultAsync(c => c.Id == id); _inputPath = Path.Combine(basePath, "input"); _outputPath = Path.Combine(basePath, "output"); _challengeRunner = ChallengeFactory.CreateChallenge(challenge.ChallengeType); foreach (var file in Directory.GetFiles(_inputPath)) { challenge.Results.Add(new Result { FileName = Path.GetFileName(file) }); } await _context.SaveChangesAsync(); var tasks = challenge.Results.Select(ProcessInput).ToHashSet(); while (tasks.Count > 0) { var task = await Task.WhenAny(tasks); await _context.SaveChangesAsync(); tasks.Remove(task); } challenge.EndTime = DateTime.Now; challenge.Done = true; await _context.SaveChangesAsync(); }
/// <summary> /// Main method of this program. /// </summary> /// <param name="args">Arguments passed to the program.</param> public static void Main(string[] args) { try { Console.WriteLine("HackerRank."); IChallenge challenge = DomainChooser(); Console.WriteLine(challenge.Instructions()); challenge.Input(); Console.WriteLine(challenge.Output()); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } catch (ChallengeException e) { Console.WriteLine("Please choose a valid challenge.\n" + "See valid challenge in https://www.hackerrank.com/domains"); Console.Error.WriteLine(e.Message); } catch (DomainException e) { Console.WriteLine("Please choose a valid domains.\n" + "See valid challenge in https://www.hackerrank.com/domains"); Console.Error.WriteLine(e.Message); } catch (FormatException e) { Console.WriteLine("Please enter a valid number."); Console.Error.WriteLine(e.Message); } }
public Task <Challenge> GetChallenge(String challengeCode) { Identifier identifier = GetChallengeIdentifierForChallengeCode(challengeCode); IChallenge challenge = _challengeLibrary[identifier]; return(challenge.GetChallenge()); }
public DashboardController(ILogger <DashboardController> _logger, IHttpContextAccessor httpContextAccessor, IUser _user, IChallenge _challenge) { this._logger = _logger; this._httpContextAccessor = httpContextAccessor; this._user = _user; this._challenge = _challenge; }
/// <summary> /// Constructor. /// </summary> public PauseMenuScreen(IChallenge challenge) : base("PAUSED") { // Flag that there is no need for the game to transition // off when the pause menu is on top of it. VibrationManager.Instance.CancelAllVibrations(); IsPopup = true; this.challenge = challenge; this.SetShowBackgroundColor(false); this.SetShowBackgroundDecoration(false); // Create our menu entries. MenuEntry resumeGameMenuEntry = new MenuEntry("Resume Game"); MenuEntry challengeInfoEntry = new MenuEntry("Current Challenge Info"); MenuEntry controlsEntry = new MenuEntry("Controls"); MenuEntry helpEntry = new MenuEntry("Game Help"); MenuEntry quitGameMenuEntry = new MenuEntry("Quit Game"); // Hook up menu event handlers. resumeGameMenuEntry.Selected += OnCancel; challengeInfoEntry.Selected += ChallengeInfoEntrySelected; controlsEntry.Selected += ControlsEntrySelected; helpEntry.Selected += HelpEntrySelected; quitGameMenuEntry.Selected += QuitGameMenuEntrySelected; // Add entries to the menu. MenuEntries.Add(resumeGameMenuEntry); if (this.challenge != null) { MenuEntries.Add(challengeInfoEntry); } MenuEntries.Add(controlsEntry); MenuEntries.Add(helpEntry); MenuEntries.Add(quitGameMenuEntry); }
public long RunFirst() { //var allLines= IChallenge.GetAllLines("test_6_1.txt"); var allLines = IChallenge.GetAllLines("6_1.txt"); var totalAnswers = GetDistinctAnswers(allLines); return(totalAnswers); }
public long RunFirst() { //var allLines = IChallenge.GetAllLines("test_9.txt"); var allLines = IChallenge.GetAllLines("9_1.txt"); var first = FindFirstInvalidXMAS(allLines.Select(long.Parse).ToArray(), 25); return(long.Parse(allLines[first])); }
public long RunFirst() { _instructions = IChallenge.GetAllLines("8_1.txt"); //_instructions = IChallenge.GetAllLines("test_8_1.txt"); DoInstruction(0); return(_accumulator); }
public ChallengeModeScreen(IChallenge challenge, PlayerIndex playerIndex) : base(1) { this.challenge = challenge; base.SetPlayerOne(playerIndex); TransitionOnTime = TimeSpan.FromSeconds(1.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); }
public HomeController(ILogger <HomeController> logger, INewsApi _newsApi, IWeatherApi _weatherApi, IHttpContextAccessor httpContextAccessor, IUser _user, IChallenge _challenge) { _logger = logger; this._newsApi = _newsApi; this._weatherApi = _weatherApi; this._httpContextAccessor = httpContextAccessor; this._user = _user; this._challenge = _challenge; }
public long RunSecond() { var dictionaryRatingsPathsToZero = new Dictionary <long, long>(); var ratings = IChallenge.GetAllLines("10_1.txt").Select(long.Parse).ToList(); ratings.Add(0); ratings.Sort(); var endRating = ratings[^ 1] + 3;
public void InvitePlayerToChallenge(IPlayer player, IChallenge challenge) { if (!challenge.Participants.Any(p => p.Nick == player.Nick) && !player.GamesHistory.Any(c => c.Equals(challenge))) { challenge.Participants.Add(player); player.GamesHistory.Single(x => x.Challenges.Any(c => c.Id == challenge.Id)).Challenges.Add(challenge); } }
public ChallengeEditorDialog(IModel model, IChallenge challenge) { InitializeComponent(); Model = model; Challenge = challenge.GetCopy(); IsNewChallenge = false; DataContext = this; TestListView_SizeChanged(TestList, null); TestList.Items.Refresh(); }
public static ChallengeModel ToModel(this IChallenge model) { return(new ChallengeModel { Id = model.Id, EntryFeeCurrency = model.Payout.EntryFee.Type.Value, EntryFeeAmount = model.Payout.EntryFee.Amount, PayoutBuckets = model.Payout.Buckets.Select(bucket => bucket.ToModel()).ToList() }); }
public long RunSecond() { //var allLines = IChallenge.GetAllLines("test_simple_7_2.txt"); //var allLines = IChallenge.GetAllLines("test_7_2.txt"); var allLines = IChallenge.GetAllLines("7_1.txt"); var contents = GetDictionaryOfContents(allLines); var bagCount = TraverseBags("shiny gold", contents) - 1; // do not count the shiny bag in it self return(bagCount); }
/// <summary> /// Fills parameters /// </summary> /// <param name="challenge"></param> /// <param name="authzId"></param> /// <param name="type"></param> protected virtual void OnCreateParams(IChallenge challenge, int authzId, string type) { challenge.Type = type; challenge.AuthorizationId = authzId; challenge.Status = ChallengeStatus.Pending; var httpToken = new byte[20]; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(httpToken); challenge.Token = Base64Url.Encode(httpToken); }
/// <inheritdoc/> public void Validate(IChallenge challenge) { if (challenge.Status == ChallengeStatus.Pending) { challenge.Status = ChallengeStatus.Processing; ChallengeRepository.Update(challenge); Logger.Info("Challenge {id} status updated to {status}", challenge.Id, challenge.Status); Task .Run(() => { // validate challenge switch (challenge.Type) { case "http-01": ValidateHttpChallenge(challenge); break; default: throw new Exception($"Unsupported Challenge type '{challenge.Type}'"); } }) .ContinueWith(t => { // Fault validate if (t.IsFaulted) { Error err = t.Exception.InnerException; challenge.Error = ChallengeRepository.CreateError(); challenge.Error.Detail = err.Detail; challenge.Error.Type = err.Type; challenge.Status = ChallengeStatus.Invalid; ChallengeRepository.Update(challenge); } //Complete validate if (t.IsCompleted) { if (challenge.Status == ChallengeStatus.Processing) { challenge.Status = ChallengeStatus.Valid; challenge.Validated = DateTime.UtcNow; ChallengeRepository.Update(challenge); } } Logger.Info("Challenge {id} status updated to {status}", challenge.Id, challenge.Status); }); } else { throw new MalformedException("Wrong challenge status"); } }
/// <summary> /// Assign values from <see cref="IChallenge"/> to JSON <see cref="Challenge"/>. /// For expended objects need add assign values /// </summary> /// <param name="chall">JSON <see cref="Challenge"/></param> /// <param name="data"><see cref="IChallenge"/></param> protected virtual Challenge OnToChallengeConvert(Challenge chall, IChallenge data) { chall.Status = data.Status; chall.Type = data.Type; chall.Validated = data.Validated; chall.Error = data.Error != null?ToError(data.Error) : null; chall.Token = data.Token; chall.Url = $"{Options.BaseAddress}challenge/{data.Id}"; return(chall); }
public long RunFirst() { //var allLines = IChallenge.GetAllLines("test_7_1.txt"); var allLines = IChallenge.GetAllLines("7_1.txt"); var containerDictionary = GetDictionaryOfContainers(allLines); containerDictionary.TryGetValue("shiny gold", out var containers); var allNodes = TraverseContainers(containers, containerDictionary); return(allNodes.Count); }
private string GetChallengeData(IChallenge challenge) { var challengeDataString = challenge.RetrieveSampleInput(); string challengeData = null; if (challengeDataString != null) { challengeData = challengeDataString.Substring(Environment.NewLine.Length); } return(challengeData); }
public async Task <Response> ValidateChallenge(Answer answer) { var storedChallenge = await _challengeLogic.GetChallengeById(answer.ChallengeId); if (storedChallenge == null) { throw new AnswerToUnknownChallengeException(); } IChallenge challenge = _challengeLibrary[storedChallenge.Identifier]; return(await challenge.ValidateChallenge(answer, storedChallenge.Identifier)); }
public IChallenge InitializeChallenge(ChallengeConfiguration configuration) { IChallenge challenge = ChallengeFactory.CreateChallenge(configuration.ChallengeGuid); if (challenge != null) { List <IRobot> robots = RobotFactory.CreateRobots(configuration.Robots); challenge.Initialize(robots, configuration.ChallengeMatDetails, configuration.IsSinglePlayer); } return(challenge); }
private void ChallengeIsInitialized() { _challenge = new SquareCardMatChallenge(); List <IRobot> robots = new List <IRobot>() { new Robot("TestRobot", new Guid("{44684A66-7BF3-4F6B-969D-BC0F40CAEC10}")) }; SquareMatConfiguration squareMat = new SquareMatConfiguration(); squareMat.Width = 5; _challenge.Initialize(robots, JsonConvert.SerializeObject(squareMat)); }
protected Challenge(IRankIdentifier rankIdentifier, IClashResolver clashResolver) { this.clashResolver = clashResolver; this.rankIdentifier = rankIdentifier; this.nextChallenge = NoChallenge; }
public void SetUp() { _sut = new Challenge3(); }
public IChallenge SetNext(IChallenge next) { return this.nextChallenge = next; }