public bool RequestService(int userId, ServiceRequestDTO serviceRequest) { using (var entities = new UCAInvestDBEntities()) { var userDbResponse = entities.users.SingleOrDefault(t => t.user_id == userId); if (userDbResponse != null) { if (userDbResponse.status == "service_requested") { return(false); } long timeStamp = (long)TimeFunctions.DateTimeToUnixTimestamp(DateTime.Now); var location = LocationServices.GenerateDBGeographyFromCoordinates(serviceRequest.coordinates); UserService serviceToAdd = new UserService() { client_user_id = userId, request_timestamp = timeStamp, location = location, description = serviceRequest.description, taken_timestamp = 0, completed_timestamp = 0 }; entities.user_services.Add(serviceToAdd); userDbResponse.status = "service_requested"; entities.SaveChanges(); return(true); } } return(false); }
/// <summary> /// A function that blocks until all threads in the supplied closing worker are complete and closed. /// This function will display status in a persistent dialog. /// </summary> /// <param name="closingWorker">The ClosingWorker to perform the actions on.</param> public static void WaitForThreadsToCloseDialogOutput(this ClosingWorker closingWorker) { // run the closing worker until all child threads are closed ClosingInfo status; var cycles = 0; while ((status = closingWorker.ShutdownThreads()).ShutdownReady == false) { if (++cycles % 6 == 0) { if (!CrossThreadDialogs.MessageBoxPersistentExists()) { CrossThreadDialogs.MessageBoxPersistentCreate(new DialogConfiguration { Message = status.Message, Title = "CV-LS Dashboard Closing Status", ButtonIsVisible = false, DialogWidth = 600, MessageAlignment = ContentAlignment.MiddleLeft }); } else { CrossThreadDialogs.MessageBoxPersistentUpdateMessage(status.Message); } } TimeFunctions.Wait(50); } CrossThreadDialogs.MessageBoxPersistentClose(); }
public ActionResult <DateParseResponse> ParseEstimatedDate(string estimatedReleaseDate) { var dates = TimeFunctions.ParseEstimatedReleaseDate(estimatedReleaseDate, _clock); var response = new DateParseResponse(dates.minimumReleaseDate, dates.maximumReleaseDate); return(response); }
public UserTokenDTO GiveMeUniqueAvailableToken(int userId) { var GuidString = CryptoServices.GenerateToken(); long expireTime = Convert.ToInt64(TimeFunctions.DateTimeToUnixTimestamp( DateTime.Now.AddMinutes(GlobalConfig.TokenExpiresInMinutes))); using (var entities = new UCAInvestDBEntities()) { var dbResponse = entities.user_tokens.FirstOrDefault(t => t.token == GuidString); if (dbResponse == null) { var tokenToAdd = new UserToken() { user_id = userId, expire_timestamp = expireTime, token = GuidString }; entities.user_tokens.Add(tokenToAdd); entities.SaveChanges(); var config = new MapperConfiguration(cfg => { cfg.CreateMap <UserToken, UserTokenDTO>(); }); IMapper iMapper = config.CreateMapper(); return(iMapper.Map <UserToken, UserTokenDTO>(tokenToAdd)); } } return(GiveMeUniqueAvailableToken(userId)); }
public RegisterUserDTO UserForToken(string token) { RegisterUserDTO response = null; using (var entities = new UCAInvestDBEntities()) { var dbResponse = entities.user_tokens.SingleOrDefault(t => t.token == token); if (dbResponse != null) { var expireTime = TimeFunctions.UnixTimeStampToDateTime(Convert.ToInt64(dbResponse.expire_timestamp)); if (expireTime < DateTime.Now) // Token expired, has to delete { entities.user_tokens.Remove(dbResponse); entities.SaveChanges(); } else { var userLinked = dbResponse.users; var config = new MapperConfiguration(cfg => { cfg.CreateMap <User, RegisterUserDTO>(); }); IMapper iMapper = config.CreateMapper(); response = iMapper.Map <User, RegisterUserDTO>(userLinked); } } } return(response); }
public bool TakeService(int craneUserId, int serviceId) { using (var entities = new UCAInvestDBEntities()) { var craneUser = entities.users.SingleOrDefault(t => t.user_id == craneUserId); if (craneUser == null || craneUser.status == "unavailable_crane") { return(false); } craneUser.status = "unavailable_crane"; entities.SaveChanges(); var serviceResponse = entities.user_services.SingleOrDefault(t => t.service_id == serviceId); if (serviceResponse != null && serviceResponse.taken_timestamp == 0) { serviceResponse.taken_timestamp = (long?)TimeFunctions.DateTimeToUnixTimestamp(DateTime.Now); serviceResponse.crane_user_id = craneUserId; var serviceUser = serviceResponse.ServiceUser; if (serviceUser != null) { serviceUser.status = "waiting_crane_arrival"; } entities.SaveChanges(); return(true); } return(false); } }
/// <summary> /// A function that blocks until all threads in the supplied closing worker are complete and closed. /// This function will display status in the console. /// </summary> /// <param name="closingWorker">The ClosingWorker to perform the actions on.</param> public static void WaitForThreadsToCloseNoOutput(this ClosingWorker closingWorker) { // run the closing worker until all child threads are closed while (closingWorker.ShutdownThreads().ShutdownReady == false) { TimeFunctions.Wait(50); } }
public void GetLastWeekDayTest() { var res = TimeFunctions.GetLastWeekDay(2020, 4, DayOfWeek.Friday); Assert.AreEqual(new DateTime(2020, 04, 24), res); res = TimeFunctions.GetLastWeekDay(2020, 4, DayOfWeek.Thursday); Assert.AreEqual(new DateTime(2020, 04, 30), res); }
public void GetXWeekDayTest() { var res = TimeFunctions.GetXWeekDay(2020, 4, DayOfWeek.Thursday, 3); Assert.AreEqual(res, TEST_DATE.Date); var test = TimeFunctions.GetXWeekDay(2020, 4, DayOfWeek.Friday, 5); Assert.IsNull(TimeFunctions.GetXWeekDay(2020, 4, DayOfWeek.Friday, 5)); }
public static int CBA_HerbTime(DateTime date, int time, string stationIATA) { var localTime = TimeFunctions.HerbDateandIntegerTimeToStationTime(date, time, stationIATA); int hour = localTime.Hour * 100 + localTime.Minute; using (SqlConnection conn = new SqlConnection("context connection=true")) { conn.Open(); SqlCommand cmd = new SqlCommand( "select actual from [Scheduling].[dbo].[CBA_Duty_Limits] where " + hour.ToString() + " between startTime and endTime", conn); return((int)cmd.ExecuteScalar()); } }
public void FinishService(int userId, int serviceId) { using (var entities = new UCAInvestDBEntities()) { var serviceDbResponse = entities.user_services.SingleOrDefault(t => (t.crane_user_id == userId || t.client_user_id == userId) && t.service_id == serviceId); serviceDbResponse.ServiceUser.status = "freeuser"; serviceDbResponse.CraneUser.status = "available_crane"; serviceDbResponse.completed_timestamp = (long)TimeFunctions.DateTimeToUnixTimestamp(DateTime.Now); entities.SaveChanges(); } }
// Update is called once per frame public static Color getCurrentShading() { if (!hasInitializedTones) { DayNightShading.initializeTones(); } if (CheckCurrentMetadata.isIndoorMap()) { return(new Color(1, 1, 1, 1)); } int hour = TimeFunctions.getHour(); return(hourlyTones[hour]); }
private void AssertStandDevEqualsVolSquRootTimeToMaturity(MultiFactorSpotSimResults <Day> simResults) { for (int i = 0; i < simResults.NumSteps; i++) { ReadOnlyMemory <double> simulatedSpotPrices = simResults.SpotPricesForStepIndex(i); Day period = simResults.SimulatedPeriods[i]; double factorVolForPeriod = _singleNonMeanRevertingFactorParams.Factors.Single().Volatility[period]; double timeToMaturity = TimeFunctions.Act365(_currentDate, period.Start); double expectedLogStanDev = factorVolForPeriod * Math.Sqrt(timeToMaturity); double simulatedLogStanDev = LogStandardDeviation(simulatedSpotPrices.Span); double percentageError = Math.Abs((simulatedLogStanDev - expectedLogStanDev) / expectedLogStanDev); Assert.LessOrEqual(percentageError, 0.001); } }
public static double FAR117_Table_B_HerbTime(DateTime date, int time, string stationIATA, int numberOfSegments) { numberOfSegments = Math.Min(Math.Max(numberOfSegments, 1), 7); var localTime = TimeFunctions.HerbDateandIntegerTimeToStationTime(date, time, stationIATA); int hour = localTime.Hour * 100 + localTime.Minute; using (SqlConnection conn = new SqlConnection("context connection=true")) { conn.Open(); SqlCommand cmd = new SqlCommand( "select [" + numberOfSegments.ToString() + "] from [Scheduling].[dbo].[FAR117_Table_B] where " + hour.ToString() + " between startTime and endTime", conn); return((double)cmd.ExecuteScalar()); } }
protected void WaitForCompleteOrTimeout(int timeoutSeconds) { var timeout = DateTime.Now.AddSeconds(timeoutSeconds); while (_currentTransferState == TransferState.Running) { if (DateTime.Now > timeout) { // timed out SetTransferState(TransferState.FailedTimeOut); Stop(); break; } TimeFunctions.Wait(50); } }
private List <string> ReadLine(int linesToRead, int timeoutMilliseconds) { var workingString = ""; var finishBy = DateTime.Now.AddMilliseconds(timeoutMilliseconds); while (DateTime.Now < finishBy && _serialPort.IsOpen) { if (_serialPort.BytesToRead > 0) { _lastReceiveTime = DateTime.Now; workingString += _serialPort.ReadExisting(); // special case for dealing with linux vs windows new line commands workingString = workingString.Replace("\n", ""); // we have at least started the last requested line var workingStrings = workingString.Split(new[] { _portParameters.TerminationChar }).ToList(); if (_portParameters.EndPrompt.Length > 0 && workingStrings.Any(s => s.Contains(_portParameters.EndPrompt))) { return(workingStrings); } if (workingStrings.Count >= linesToRead) { // now we need to check to make sure the last line has the closing character var lastLine = workingString.Substring(workingString.IndexOf(workingStrings[linesToRead - 1], StringComparison.Ordinal)); if (lastLine.Contains(_portParameters.TerminationChar)) { return(workingStrings); } } } TimeFunctions.Wait(10); } // we failed so return empty return(new List <string> { "" }); }
// Use this for initialization void Start() { //swordCollider = GetComponent<Collider2D> (); attachedCollider = GetComponent <PolygonCollider2D> (); if (attachedCollider == null) { Debug.Log("MISSING COLLIDER REF"); } Debug.Log("GOT COLLIDER REF"); targetsHit = new List <int> (); moveInfo = GetComponentInParent <AbilityBasicMovement> (); playerAttackInfo = GetComponentInParent <AttackInfoContainer> (); SPManager = GetComponentInParent <PlayerSPComponent>(); SPValues = new PlayerSPValues(); timeManager = GameObject.Find("Time Manager").GetComponent <TimeFunctions> (); hitParticles = GameObject.Find("HitParticles"); DisableCollider(); }
private void OnGameUpdate(EventArgs args) { if (ScheduledScripts != null) { var currentTime = TimeFunctions.GetTimeOfDay(); foreach (var script in ScheduledScripts.Values) { var scheduler = script.GetSchedulerObject(); var shouldRun = scheduler?.OnUpdate(currentTime); if (shouldRun == true) { RunScript(script); } } } }
/// <summary> /// Stop the worker thread. /// </summary> /// <param name="timeoutMilliseconds">Number of milliseconds to wait for state machine to Stop.</param> /// <returns>True if state machine is stoped, false otherwise.</returns> protected virtual bool Stop(int timeoutMilliseconds = 50) { // tell the state machine to stop StopWorker = true; PulseWorker(); var timeout = DateTime.Now.AddMilliseconds(timeoutMilliseconds); while (StopWorker == true) { // timed out waiting if (timeout < DateTime.Now) { return(false); } TimeFunctions.Wait(10); } // stop successfull return(true); }
/// <summary> /// A function that blocks until all threads in the supplied closing worker are complete and closed. /// This function will display status in the console. /// </summary> /// <param name="closingWorker">The ClosingWorker to perform the actions on.</param> public static void WaitForThreadsToCloseConsoleOutput(this ClosingWorker closingWorker) { // run the closing worker until all child threads are closed ClosingInfo status; var cycles = 0; var previousLines = 0; while ((status = closingWorker.ShutdownThreads()).ShutdownReady == false) { if (cycles++ % 6 == 0) { ConsoleFunctions.ClearLine(previousLines); Console.WriteLine(status.Message); previousLines = status.Message.Split('\r').Length; } TimeFunctions.Wait(50); } // clean up console ConsoleFunctions.ClearLine(previousLines); Console.WriteLine("Shutdown Threads Complete!"); }
public UserTokenDTO RegisterUser(RegisterUserDTO userToRegister) { User addedUser = null; using (var entities = new UCAInvestDBEntities()) { var dbResponse = entities.users.SingleOrDefault(t => t.mail == userToRegister.mail || t.username == userToRegister.username); if (dbResponse == null) { long creationTimeStamp = Convert.ToInt64(TimeFunctions.DateTimeToUnixTimestamp(DateTime.Now)); string salt = CryptoServices.GenerateGuid().Substring(0, 8); string password = CryptoServices.SHA256Encrypt(userToRegister.password, salt); var userToAdd = new User() { first_name = userToRegister.first_name, mail = userToRegister.mail, last_name = userToRegister.last_name, mobile_phone = userToRegister.mobile_phone, creation_timestamp = creationTimeStamp, password = password, salt = salt, username = userToRegister.username, status = "freeuser" }; addedUser = entities.users.Add(userToAdd); entities.SaveChanges(); } } if (addedUser != null) { return(GiveMeUniqueAvailableToken(addedUser.user_id)); } return(null); }
static void Main(string[] args) { // Uses TZConvert Nugat Library // https://github.com/mj1856/TimeZoneConverter // PM> Install-Package TimeZoneConverter var time = 500; DateTime date = new DateTime(2019, 6, 18); var hour = time / 100; var minutes = time - (hour * 100); var originalTime = new DateTime(date.Year, date.Month, date.Day, hour, minutes, 0); var stationTime = TimeFunctions.HerbDateandIntegerTimeToStationTime(date, time, "DEN"); var utcTime = TimeFunctions.StationTimeToUTC(stationTime, "LAX"); var bwiTime = TimeFunctions.UTCtoStationTime(utcTime, "BWI"); var laxTime = TimeFunctions.StationTimeToStationTime(bwiTime, "BWI", "LAX"); var herbTime = TimeFunctions.StationTimeToStationTime(laxTime, "LAX", "DAL"); var phxTime = TimeFunctions.StationTimeToStationTime(herbTime, "DAL", "PHX"); var max_block_LocalTime = FAR117Functions.FAR117_Table_A_LocalTime(originalTime); var max_fdp_LocalTime = FAR117Functions.FAR117_Table_B_LocalTime(originalTime, 5); var max_cba_LocalTime = FAR117Functions.CBA_LocalTime(originalTime); var max_block_HerbTime = FAR117Functions.FAR117_Table_A_HerbTime(originalTime, time, "DEN"); var max_fdp_HerbTime = FAR117Functions.FAR117_Table_B_HerbTime(originalTime, time, "DEN", 5); var max_cba_HerbTime = FAR117Functions.CBA_HerbTime(originalTime, time, "DEN"); Console.WriteLine("originalTime HerbTime: {0}\nLAX_Time: {1}\nutcTime: {2}\nBWI_Time: {3}\nLAX_Time:{4}\nHerbTime:{5}\nPHX_Time:{6}", originalTime, stationTime, utcTime, bwiTime, laxTime, herbTime, phxTime); Console.WriteLine("Local Time {0} Max_FDP: {1}, Max_Block: {2}, CBA_Actual: {3}", originalTime, max_fdp_LocalTime, max_block_LocalTime, max_cba_LocalTime); Console.WriteLine("Herb Time {0} Max_FDP: {1}, Max_Block: {2}, CBA_Actual: {3}", stationTime, max_fdp_HerbTime, max_block_HerbTime, max_cba_HerbTime); //Console.WriteLine("{0} {1} is {2} {3}.", //convertedDate, tzStation.IsDaylightSavingTime(newDate) ? tzStation.DaylightName : tzStation.StandardName, //newDate, tzCentral.IsDaylightSavingTime(newDate) ? tzCentral.DaylightName : tzCentral.StandardName); Console.ReadLine(); }
public void UpdatePosition(int userId, CoordinateDTO coordinates) { using (var entities = new UCAInvestDBEntities()) { var dbResponse = entities.user_locations.SingleOrDefault(t => t.user_id == userId); var currentLocation = GenerateDBGeographyFromCoordinates(coordinates); var currentTimestamp = (long?)TimeFunctions.DateTimeToUnixTimestamp(DateTime.Now); if (dbResponse != null) { dbResponse.location = currentLocation; dbResponse.timestamp = currentTimestamp; } else { entities.user_locations.Add(new UserLocation() { location = currentLocation, timestamp = currentTimestamp, user_id = userId }); } entities.SaveChanges(); } }
public static int getMinute() { System.DateTime date = TimeFunctions.getCurrentDate(); return(date.Minute); }
/// <summary> /// Send a command to the unit. /// </summary> /// <param name="command">The command to send.</param> /// <param name="linesToRead">Number of lines to read for the responce. /// Do not include this optional parameter to use the default value assigned at creation of the port.</param> /// <param name="echoComTraffic">Com traffic will be sent to registered output functions when true.</param> /// <returns>Returns a list of strings based on the default number of lines to read.</returns> public List <string> SendCommand(List <byte> command, int linesToRead = -1, bool echoComTraffic = false) { if (linesToRead < 0) { linesToRead = _portParameters.LinesToRead; } var linesToReturn = new List <string> { "" }; if (!Monitor.TryEnter(_comLock, _portParameters.MaxDelayMilliseconds)) { return(linesToReturn); } try { if (_serialPort.IsOpen) { _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); // send the data var commandClone = command.CloneList(); commandClone.Add((byte)_portParameters.TerminationChar); if (echoComTraffic) { RunMessageOutput( $"USER> {Encoding.ASCII.GetString(commandClone.ToArray())}{Environment.NewLine}"); } if (!_portParameters.DelaySecondCharacter || commandClone.Count == 1) { _serialPort.Write(commandClone.ToArray(), 0, commandClone.Count); } else { var array = commandClone.ToArray(); _serialPort.Write(array, 0, 1); TimeFunctions.Wait(50); _serialPort.Write(array, 1, commandClone.Count - 1); } if (linesToRead > 0) { linesToReturn = ReadLine(linesToRead, _portParameters.TimeoutMilliseconds); if (echoComTraffic) { var returnStrings = string.Join(Environment.NewLine, linesToReturn.ToArray()); RunMessageOutput($"UNIT> {returnStrings}{Environment.NewLine}"); } } } else { RunMessageOutput($"SYSTEM> Open Serial Port First"); } } catch (Exception exc) { // ignore var test = exc.ToString(); } finally { Monitor.Exit(_comLock); } return(linesToReturn); }
public LoggerService(string baseLogDirectory) { _baseLogDirectory = baseLogDirectory; _fileSystem = new FileSystem(); _timeFunctions = new TimeFunctions(); }
public static int getSecond() { System.DateTime date = TimeFunctions.getCurrentDate(); return(date.Second); }
public static int getHour() { System.DateTime date = TimeFunctions.getCurrentDate(); return(date.Hour); }
/// <summary> /// Send a command to the unit. /// </summary> /// <param name="command">The command to send.</param> /// <param name="linesToRead">Number of lines to read for the responce. /// Do not include this optional parameter to use the default value assigned at creation of the port.</param> /// <param name="echoComTraffic">Com traffic will be sent to registered output functions when true.</param> /// <returns>Returns a list of strings based on the default number of lines to read.</returns> public List <string> SendCommand(List <byte> command, int linesToRead = -1, bool echoComTraffic = false) { if (linesToRead < 0) { linesToRead = ComParameters.LinesToRead; } var linesToReturn = new List <string> { "" }; if (!Monitor.TryEnter(_comLock, ComParameters.MaxDelayMilliseconds)) { return(linesToReturn); } try { if (IsConnected) { _socketInFifo.Clear(); // send the data var commandClone = command.CloneList(); commandClone.Add((byte)ComParameters.TerminationChar); if (echoComTraffic) { RunMessageOutput($"USER> {Encoding.ASCII.GetString(commandClone.ToArray())}{Environment.NewLine}"); } if (!ComParameters.DelaySecondCharacter || commandClone.Count == 1) { SendData(commandClone.ToArray()); } else { var array = commandClone.ToArray(); SendData(array, 0, 1); TimeFunctions.Wait(50); SendData(array, 1, commandClone.Count - 1); } if (linesToRead > 0) { linesToReturn = ReadLine(linesToRead, ComParameters.TimeoutMilliseconds); if (echoComTraffic) { var returnStrings = string.Join(Environment.NewLine, linesToReturn.ToArray()); RunMessageOutput($"UNIT> {returnStrings}{Environment.NewLine}"); } } } } catch { // ignored } finally { Monitor.Exit(_comLock); } return(linesToReturn); }