Beispiel #1
0
 public Toxicity(SharedData shared, DatabaseContextBuilder db, InteractivityExtension interactive, StartTimes starttimes)
 {
     this.Database      = db;
     this.Shared        = shared;
     this.Interactivity = interactive;
     this.StartTimes    = starttimes;
 }
        public FeasibilityStatus Check(
            Instance instance,
            StartTimes startTimes,
            SolverConfig solverConfig,
            int?objective = null)
        {
            this.instance = ExtendedInstance.GetExtendedInstance(instance);
            this.instance.ComputeOptimalSwitchingCosts();    // For TEC computation.

            this.startTimes   = startTimes;
            this.solverConfig = solverConfig;

            this.Job     = null;
            this.NextJob = null;
            this.Machine = null;
            this.Status  = FeasibilityStatus.Unknown;

            var feasible =
                this.EveryJobHasStartTime() &&
                this.JobsWithinHorizon() &&
                this.JobsNotOverlapping() &&
                this.TransitionsExist() &&
                this.ObjectiveCorrespondsWithStartTimes(objective);

            if (feasible)
            {
                this.Status = FeasibilityStatus.Feasible;
            }

            return(this.Status);
        }
        protected override StartTimes GetStartTimes()
        {
            var startTimes = new StartTimes();

            foreach (var job in this.Instance.Jobs)
            {
                startTimes[job] = this.vars.JobProcessed[job].WhereNonZero().First();
            }

            return(startTimes);
        }
 protected override void SetInitStartTimes(StartTimes initStartTimes)
 {
     foreach (var job in this.Instance.Jobs)
     {
         var startIntervalIdx      = initStartTimes.StartInterval(job, this.Instance).Index;
         var completionIntervalIdx = initStartTimes.CompletionInterval(job, this.Instance).Index;
         foreach (var intervalIdx in EnumerableExtensions.RangeTo(startIntervalIdx, completionIntervalIdx))
         {
             this.vars.JobProcessed[job][intervalIdx].Start = 1;
         }
     }
 }
Beispiel #5
0
        public void StartTimesTotalEnergyCostTheory(string instanceName, string resultName, int expectedTec)
        {
            var instance         = new InputReader().ReadFromPath(Path.Combine("instances", instanceName));
            var extendedInstance = ExtendedInstance.GetExtendedInstance(instance);

            extendedInstance.ComputeOptimalSwitchingCosts();
            extendedInstance.ComputeGapsLowerBounds();

            var result     = JsonConvert.DeserializeObject <Result>(File.ReadAllText(Path.Combine("results", resultName)));
            var startTimes = new StartTimes(instance, result.StartTimes);

            Assert.Equal(expectedTec, startTimes.TotalEnergyCost(extendedInstance));
        }
Beispiel #6
0
        //Method to retrieve the starttimes.
        //First parameter is an int restaurantId of which you want to retrieve the start times
        //Second parameter is a Bool. True returns a string of the start time hours. False returns a list of dinnersessions containing the different start times.
        public StartTimes retrieveStarttimes(int restaurantId, bool stringOrListAsSession)
        {
            List <DinnerSession> dinnerSessions = dinnerSessionRepository.GetAllDinnerSessionsByRestaurantId(restaurantId).ToList();
            List <DateTime>      timeCheck      = new List <DateTime>();

            string startTimesString = "";
            List <DinnerSession> startTimesDateTime = new List <DinnerSession>();

            StartTimes returnValue = new StartTimes();

            foreach (DinnerSession session in dinnerSessions)
            {
                if (startTimesString == "")
                {
                    if (!timeCheck.Contains(session.StartTime))
                    {
                        if (stringOrListAsSession == true)
                        {
                            timeCheck.Add(session.StartTime);
                            startTimesString = session.StartTime.ToString("HH:mm");
                        }
                        else
                        {
                            timeCheck.Add(session.StartTime);
                            startTimesDateTime.Add(session);
                        }
                    }
                }
                else
                {
                    if (!timeCheck.Contains(session.StartTime))
                    {
                        if (stringOrListAsSession == true)
                        {
                            timeCheck.Add(session.StartTime);
                            startTimesString += ", " + session.StartTime.ToString("HH:mm");
                        }
                        else
                        {
                            timeCheck.Add(session.StartTime);
                            startTimesDateTime.Add(session);
                        }
                    }
                }
            }
            returnValue.startTimeSession = startTimesDateTime;
            returnValue.startTimeString  = startTimesString;

            return(returnValue);
        }
Beispiel #7
0
        public SolverResult Solve(
            SolverConfig solverConfig,
            TSpecializedSolverConfig specializedSolverConfig,
            Instance instance)
        {
            this.SolverConfig            = solverConfig;
            this.specializedSolverConfig = specializedSolverConfig;

            this.timer = new Timer(this.SolverConfig.TimeLimit);
            this.timer.Restart();

            this.SetInstance(instance);

            this.CheckConfigValidity();
            this.CheckInstanceValidity();

            var        status     = this.Solve();
            StartTimes startTimes = null;

            if (status.IsFeasibleSolution())
            {
                startTimes = this.GetStartTimes();
#if DEBUG
                this.CheckSolution(startTimes);
#endif
            }
            var timeLimitReached = this.SolverReachedTimeLimit();
            var lowerBound       = this.GetLowerBound();
            var objective        = status.IsFeasibleSolution() ? this.GetObjective() : null;
            this.Cleanup();

            this.timer.Stop();
            return(new SolverResult
            {
                Status = status,
                StartTimes = startTimes,
                TimeLimitReached = timeLimitReached,
                RunningTime = TimeSpan.FromMilliseconds(this.timer.ElapsedMilliseconds),
                LowerBound = lowerBound,
                Metadata = this.GetResultMetadata(),
                Objective = objective,
                TimeToBest = status.IsFeasibleSolution() ? this.GetTimeToBest() : null,
                AdditionalInfo = this.GetAdditionalInfo()
            });
        }
Beispiel #8
0
        public void AddShowtimes()
        {
            DateTime startDate = DateTime.Now.Date;
            DateTime currDate  = startDate;
            DateTime startTime = currDate.AddHours(10).AddMinutes(Offset);

            while (currDate.AddDays(1) < startDate.AddDays(8))
            {
                DateTime latestStart = currDate.AddHours(22);


                if (CanAnotherShowtimeBeAdded(latestStart))
                {
                    StartTimes.Add(startTime);
                    startTime = startTime.AddMinutes(Runtime + Gap);
                    startTime = RoundStartTimeToNext15(startTime);
                }
                else
                {
                    currDate  = currDate.AddDays(1);
                    startTime = currDate.AddHours(10).AddMinutes(Offset);
                }
            }
        }
 protected virtual void SetInitStartTimes(StartTimes startTimes)
 {
 }
Beispiel #10
0
        internal void Initialize()
        {
            // Store the Start Times to use in DI
            // SocketStartTime will be updated in the SocketOpened event,
            // For now we just need to make sure its not null.
            StartTimes = new StartTimes(SharedData.ProcessStartTime, SharedData.ProcessStartTime);

            // Initialize the DiscordClient
            var cfg = new DiscordConfiguration
            {
                AutoReconnect           = true,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250,
                LogLevel              = LogLevel.Debug,
                Token                 = Settings.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                ShardCount            = this.Settings.ShardCount,
                ShardId               = this.ShardId
            };

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.OSVersion.Version <= new Version(6, 1, 7601, 65536))
            {
                // NT 6.1 (Win7 SP1)
                cfg.WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew;
            }
            this.Client = new DiscordClient(cfg);

            Client.ClientErrored += async args =>
            {
                await Task.Yield();

                Console.WriteLine(args.Exception);
            };

            this.Interactivity = Client.UseInteractivity(new InteractivityConfiguration
            {
                PollBehaviour = PollBehaviour.DeleteEmojis,
                Timeout       = TimeSpan.FromSeconds(15)
            });

            // Add the instances we need to dependencies
            var deps = new ServiceCollection()
                       .AddSingleton(this.SharedData)
                       //.AddInstance(this.Settings)
                       .AddSingleton(this.Interactivity)
                       .AddSingleton(this.StartTimes)
                       .AddSingleton(this.Database)
                       .BuildServiceProvider();

            // enable commandsnext
            this.Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = false,
                EnableDefaultHelp   = true,
                EnableDms           = false,
                EnableMentionPrefix = true,
                PrefixResolver      = this.GetPrefixPositionAsync,
                Services            = deps,
            });

            // set the converters
            this.Commands.RegisterConverter(new AugmentedBoolConverter());
            this.Commands.RegisterConverter(new CustomDiscordMessageConverter());

            // register commands
            this.Commands.RegisterCommands(Assembly.GetExecutingAssembly());

            foreach (var c in this.Commands.RegisteredCommands)
            {
                var reqperm = c.Value.ExecutionChecks.Where(x => x.GetType() == typeof(RequirePermissionsAttribute));
                foreach (RequirePermissionsAttribute att in reqperm)
                {
                    if (!SharedData.AllPerms.Contains(att.Permissions))
                    {
                        SharedData.AllPerms.Add(att.Permissions);
                    }
                }
                var requsrperm = c.Value.ExecutionChecks.Where(x => x.GetType() == typeof(RequireBotPermissionsAttribute));
                foreach (RequireBotPermissionsAttribute att in requsrperm)
                {
                    if (!SharedData.AllPerms.Contains(att.Permissions))
                    {
                        SharedData.AllPerms.Add(att.Permissions);
                    }
                }
            }

            // Update the SocketStartTime
            this.Client.SocketOpened += async() =>
            {
                await Task.Yield();

                StartTimes.SocketStartTime = DateTime.Now;
            };

            // register event handlers
            this.Client.Ready += Client_Ready;

            AsyncListenerHandler.InstallListeners(Client, this);
        }
Beispiel #11
0
        public Bot()
        {
            if (!File.Exists("config.json"))
            {
                new Config().SaveToFile("config.json");
                #region !! Report to user that config has not been set yet !! (aesthetics)
                Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.Black;
                WriteCenter("▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▒", 2);
                WriteCenter("▒▒▒▒▒▒▄▀▀▓▓▓▀█▒▒▒▒▒▒");
                WriteCenter("▒▒▒▒▄▀▓▓▄██████▄▒▒▒▒");
                WriteCenter("▒▒▒▄█▄█▀░░▄░▄░█▀▒▒▒▒");
                WriteCenter("▒▒▄▀░██▄░░▀░▀░▀▄▒▒▒▒");
                WriteCenter("▒▒▀▄░░▀░▄█▄▄░░▄█▄▒▒▒");
                WriteCenter("▒▒▒▒▀█▄▄░░▀▀▀█▀▒▒▒▒▒");
                WriteCenter("▒▒▒▄▀▓▓▓▀██▀▀█▄▀▀▄▒▒");
                WriteCenter("▒▒█▓▓▄▀▀▀▄█▄▓▓▀█░█▒▒");
                WriteCenter("▒▒▀▄█░░░░░█▀▀▄▄▀█▒▒▒");
                WriteCenter("▒▒▒▄▀▀▄▄▄██▄▄█▀▓▓█▒▒");
                WriteCenter("▒▒█▀▓█████████▓▓▓█▒▒");
                WriteCenter("▒▒█▓▓██▀▀▀▒▒▒▀▄▄█▀▒▒");
                WriteCenter("▒▒▒▀▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒");
                Console.BackgroundColor = ConsoleColor.Yellow;
                WriteCenter("WARNING", 3);
                Console.ResetColor();
                WriteCenter("Thank you Mario!", 1);
                WriteCenter("But our config.json is in another castle!");
                WriteCenter("(Please fill in the config.json that was generated.)", 2);
                WriteCenter("Press any key to exit..", 1);
                Console.SetCursorPosition(0, 0);
                Console.ReadKey();
                #endregion
                Environment.Exit(0);
            }

            _config = Config.LoadFromFile("config.json");
            _client = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect     = true,
                EnableCompression = true,
                Token             = _config.Token,
                TokenType         = TokenType.Bot,
            });

            _interactivity = _client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = TimeoutBehaviour.Delete,
                PaginationTimeout   = TimeSpan.FromSeconds(30),
                Timeout             = TimeSpan.FromSeconds(30)
            });

            _startTimes = new StartTimes
            {
                BotStart    = DateTime.Now,
                SocketStart = DateTime.MinValue
            };

            _cts = new CancellationTokenSource();

            DependencyCollection dep;
            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(new Dependencies
                {
                    Interactivity = _interactivity,
                    StartTimes    = _startTimes,
                    Cts           = _cts
                });
                dep = d.Build();
            }

            _cnext = _client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive       = false,
                EnableDefaultHelp   = true,
                EnableDms           = true,
                EnableMentionPrefix = true,
                StringPrefix        = _config.Prefix,
                Dependencies        = dep
            });

            _cnext.RegisterCommands <Commands.Etime>();

            // Hook some events for logging.
            _client.Ready          += OnReadyAsync;
            _client.ClientErrored  += ClientError;
            _cnext.CommandExecuted += CommandExecuted;
            _cnext.CommandErrored  += CommandErrored;
        }
Beispiel #12
0
 public string Data2String() => MyPlaneFullName + '\t' + ((int)Rank).ToString() + '\t' + StartTimes.ToString() + '\t' + PlayingTime.ToString() + '\t' + ClearTimes.ToString() + '\t' + NoContinueClearTimes.ToString() + '\t' + PracticeLevel.ToString() + "\r\n";
Beispiel #13
0
		public static Event AddEvent(
			string name, 
			int venueK, 
			StartTimes? startTime, 
			DateTime date, 
			string shortDetails, 
			string safeLongDetails, 
			Guid? duplicateGuid, 
			int? capacity, 
			Usr usr, 
			int[] musicTypeKs, 
			int[] brandKs,
			bool spotterRequest,
			string spotterRequestName,
			string spotterRequestNumber)
		{
			Event ev = new Event();

			Venue venue = new Venue(venueK);
			Transaction t = null;//new Transaction();
			try
			{
				ev.AddedDateTime = DateTime.Now;
				ev.VenueK = venue.K;
				ev.Name = Cambro.Web.Helpers.StripHtml(name).Trim();
				ev.StartTime = startTime ?? StartTimes.Evening;;
				ev.DateTime = date;
				ev.ShortDetailsHtml = Cambro.Misc.Utility.Snip(Cambro.Web.Helpers.StripHtml(shortDetails ?? ""), 500);

				ev.LongDetailsHtml = safeLongDetails;

				ev.DuplicateGuid = duplicateGuid ?? Guid.NewGuid();

				ev.Capacity = capacity ?? venue.Capacity;

				ev.AdminNote += "Event added by owner " + DateTime.Now.ToString();

				ev.OwnerUsrK = Usr.Current.K;

				ev.SpotterRequest = spotterRequest;
				ev.SpotterRequestName = spotterRequestName;
				ev.SpotterRequestNumber = spotterRequestNumber;

				if (!usr.IsSuper)
				{
					ev.IsNew = true;
					ev.ModeratorUsrK = Usr.GetEventModeratorUsrK();
				}
				ev.InitUrlFragment();
				ev.Update(t);

				foreach (int musicTypeK in musicTypeKs ?? new int[]{})
				{
					MusicType mt = new MusicType(musicTypeK);
					EventMusicType emt = new EventMusicType();
					emt.EventK = ev.K;
					emt.MusicTypeK = mt.K;
					emt.Update(t);
				}
				foreach (int brandK in brandKs ?? new int[] { })
				{
					EventBrand eb = new EventBrand();
					eb.BrandK = brandK;
					eb.EventK = ev.K;
					eb.Update(t);
				}

				ev.UpdateMusicTypesString(t);

				ev.Venue.UpdateTotalEvents(t);
				ev.Owner.UpdateEventCount(t);

				//t.Commit();
				

			}
			catch (Exception ex)
			{
				//t.Rollback();
				ev.DeleteAll(null);
				throw ex;
			}
			finally
			{
				//t.Close();
			}

			Mailer sm = new Mailer();
			sm.TemplateType = Mailer.TemplateTypes.AnotherSiteUser;
			sm.UsrRecipient = Usr.Current;
			sm.To = Usr.Current.Email;
			sm.Subject = "You've added an event!";
			sm.Body += "<p>You've added an event to the DontStayIn events database.</p>";
			sm.Body += "<p>Click the link below to view the event:</p>";
			sm.Body += "<p><a href=\"[LOGIN(" + ev.Url() + ")]\">" + HttpUtility.HtmlEncode(ev.FriendlyName) + "</a></p>";
			sm.Body += "<h2>Make changes</h2>";
			sm.Body += "<p>You can make changes or corrections to the event details by clicking the link below:</p>";
			sm.Body += "<p><a href=\"[LOGIN(/event-" + ev.K.ToString() + "/edit)]\">Edit your event</a></p>";
			sm.Body += "<h2>How about a banner advert?</h2>";
			sm.Body += "<p>You can add a banner advert to your event by using the link below:</p>";
			sm.Body += "<p><a href=\"[LOGIN(/pages/bannerpreview/eventk-" + ev.K.ToString() + ")]\">Add a banner</a></p>";
			sm.Body += "<h2>Add photos or a review</h2>";
			sm.Body += "<p>After the event you can upload photos or add a review with the links below:</p>";
			sm.Body += "<p><a href=\"[LOGIN(/pages/galleries/add/eventk-" + ev.K.ToString() + ")]\">Add photos</a> or <a href=\"[LOGIN(" + ev.UrlApp("review") + ")]\">add a review</a></p>";
			sm.Body += "<h2>Are you the event promoter?</h2>";
			sm.Body += "<p>If you organise this event, you can sign up for a FREE promoter account by using the link below:</p>";
			sm.Body += "<p><a href=\"[LOGIN(/pages/promoters/edit)]\">Apply for a promoter account</a></p>";
			sm.RedirectUrl = ev.Url();
			sm.Send();
			return ev;

		}
Beispiel #14
0
 protected virtual void CheckSolution(StartTimes startTimes)
 {
 }