public void can_format_24hour_time() { var compareTime = new Time(13, 59, 58, "HH:mm:ss"); var time = compareTime.ToString(); string timeValue = "13:59:58"; Assert.AreEqual(time, timeValue); }
/** == Time units * Whenever durations need to be specified, eg for a timeout parameter, the duration can be specified * as a whole number representing time in milliseconds, or as a time value like `2d` for 2 days. * * === Using Time units in NEST * NEST uses `Time` to strongly type this and there are several ways to construct one. * * ==== Constructor * The most straight forward way to construct a `Time` is through its constructor */ [U] public void Constructor() { var unitString = new Time("2d"); var unitComposed = new Time(2, Nest.TimeUnit.Day); var unitTimeSpan = new Time(TimeSpan.FromDays(2)); var unitMilliseconds = new Time(1000 * 60 * 60 * 24 * 2); /** * When serializing Time constructed from * - a string * - milliseconds (as a double) * - composition of factor and interval * - a `TimeSpan` * * the expression will be serialized to a time unit string composed of the factor and interval e.g. `2d` */ Expect("2d") .WhenSerializing(unitString) .WhenSerializing(unitComposed) .WhenSerializing(unitTimeSpan) .WhenSerializing(unitMilliseconds); /** * The `Milliseconds` property on `Time` is calculated even when not using the constructor that takes a double */ unitMilliseconds.Milliseconds.Should().Be(1000*60*60*24*2); unitComposed.Milliseconds.Should().Be(1000*60*60*24*2); unitTimeSpan.Milliseconds.Should().Be(1000*60*60*24*2); unitString.Milliseconds.Should().Be(1000*60*60*24*2); }
public void VerifyAllEnums() { var acceleration = new Acceleration(1, AccelerationUnit.BaseUnit); var angle = new Angle(1, AngleUnit.BaseUnit); var angularAcceleration = new AngularAcceleration(1, AngularAccelerationUnit.BaseUnit); var area = new Area(1, AreaUnit.BaseUnit); var density = new MassDensity(1, MassDensityUnit.BaseUnit); var electricCurrent = new ElectricCurrent(1, ElectricCurrentUnit.BaseUnit); var electricResistance = new ElectricResistance(1, ElectricResistanceUnit.BaseUnit); var electricVoltage = new ElectricPotential(1, ElectricPotentialUnit.BaseUnit); var energy = new Energy(1, EnergyUnit.BaseUnit); var force = new Force(1, ForceUnit.BaseUnit); var frequency = new Frequency(1, FrequencyUnit.BaseUnit); var jerk = new Jerk(1, JerkUnit.BaseUnit); var length = new Length(1, LengthUnit.BaseUnit); var mass = new Mass(1, MassUnit.BaseUnit); var massFlowRate = new MassFlowRate(1, MassFlowRateUnit.BaseUnit); var momentum = new Momentum(1, MomentumUnit.BaseUnit); var numeric = new Numeric(1, NumericUnit.BaseUnit); var power = new Power(1, PowerUnit.BaseUnit); var pressure = new Pressure(1, PressureUnit.BaseUnit); var speed = new Speed(1, SpeedUnit.BaseUnit); var temperature = new Temperature(1, TemperatureUnit.BaseUnit); var time = new Time(1, TimeUnit.BaseUnit); var torque = new Torque(1, TorqueUnit.BaseUnit); var volume = new Volume(1, VolumeUnit.BaseUnit); var volumetricFlowRate = new VolumetricFlowRate(1, VolumetricFlowRateUnit.BaseUnit); }
public void can_format_12hour_time() { var compareTime = new Time(13, 59, 58, "h:mm:ss tt"); var time = compareTime.ToString(); string timeValue = "1:59:58 " + Thread.CurrentThread.CurrentCulture.DateTimeFormat.PMDesignator; Assert.AreEqual(time, timeValue); }
public static StrategyDecision New( Directive processDirective, MessageDirective messageDirective, IEnumerable<ProcessId> affects, Time pause ) => new StrategyDecision(processDirective, messageDirective, affects, pause);
public Report(Time time, IState state) { if(null == state) throw new ArgumentNullException("state"); _time = time; _state = state; }
public Call (DateTime date, Time time, string dialledPhoneNumber, int duration) { this.Date = date; this.Time = time; this.DialledPhoneNumber = dialledPhoneNumber; this.Duration = duration; }
StrategyContext( StrategyState global, Exception exception, object message, ProcessId sender, ProcessId failedProcess, ProcessId parentProcess, IEnumerable<ProcessId> siblings, IEnumerable<ProcessId> affects, Time pause, Option<Directive> directive, Option<MessageDirective> messageDirective ) { bool isStop = directive == LanguageExt.Directive.Stop; Global = isStop ? StrategyState.Empty : global; Exception = exception; Message = message; Sender = sender; Self = failedProcess; ParentProcess = parentProcess; Siblings = siblings ?? Siblings; Affects = affects ?? Affects; Pause = isStop ? 0 * s : pause; Directive = directive; MessageDirective = messageDirective; }
public void GetSecondsSinceStartToday() { var time = new Time(new MockElapsedTime()); Assert.AreEqual(0.0f, time.GetSecondsSinceStartToday()); time.Run(); Assert.AreNotEqual(0.0f, time.GetSecondsSinceStartToday()); }
public void FormattedTime() { Time task = new Time(); task.BuildEngine = new MockBuild(); // test without the optional Format property Assert.IsNull(task.Format, @"Format not null"); Assert.IsNull(task.FormattedTime, @"Formatted time not null"); Assert.IsTrue(task.Execute(), @"Time task without Format failed"); Assert.IsNull(task.Format, @"Format not null after executing task"); DateTime time = task.DateTimeValue; Assert.IsNotNull(task.FormattedTime, @"Formatted time null after executing task"); task.Log.LogMessage(MessageImportance.Low, "Time without format: \"{0}\" (local)", task.FormattedTime); Assert.AreEqual(time.ToString(DateTimeFormatInfo.InvariantInfo), task.FormattedTime, @"Wrong default local time"); // the .Now property has a limited resolution // according to ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref2/html/P_System_DateTime_Now.htm // therefore wait some time to ensure we get a different value // when executing a second time Thread.Sleep(1000); // second execute must yield another time stamp Assert.IsTrue(task.Execute(), @"Time task without Format failed in second execution"); task.Log.LogMessage(MessageImportance.Low, "Time without format: \"{0}\" (local)", task.FormattedTime); Assert.AreNotEqual(time, task.DateTimeValue, @"Time doesn't change with second execution"); // specify the format task.Format = @"yyyyMMddHHmmss"; task.Kind = System.DateTimeKind.Utc.ToString(); Assert.IsTrue(task.Execute(), @"Time task with Format failed"); task.Log.LogMessage(MessageImportance.Low, "Time with format: \"{0}\" (UTC)", task.FormattedTime); Assert.AreEqual(task.Format.Length, task.FormattedTime.Length, @"Wrong time length"); }
public CreateWIP1(BatchTreeViewItem sender) { Sender = sender; // WorkItem happens after you click InitializeComponent(); // Do Not Run Until Time Time timeUntilTime = new Time(false); dataTableUntil = timeUntilTime.TimeDataTable; timeUntil.ItemsSource = dataTableUntil.AsDataView(); // Do Not Run After Time Time timeAfterTime = new Time(false); // heh dataTableAfter = timeAfterTime.TimeDataTable; timeAfter.ItemsSource = dataTableAfter.AsDataView(); // Recurrence Interval Time recurrenceIntervalTime = new Time(true); dataTableInterval = recurrenceIntervalTime.TimeDataTable; dataGridInterval.ItemsSource = dataTableInterval.AsDataView(); // Start Window Time startWindowTime = new Time(true); dataTableWindow = startWindowTime.TimeDataTable; dataGridWindow.ItemsSource = dataTableWindow.AsDataView(); Loaded += OnLoaded; MainWindow.Resize(MainGrid); }
public void Generate(TimingMethod method) { for (var y = Run.GetMinSegmentHistoryIndex() + 1; y <= Run.AttemptHistory.Count; y++) { var time = TimeSpan.Zero; foreach (var segment in Run) { var segmentHistoryElement = segment.SegmentHistory.FirstOrDefault(x => x.Index == y); if (segmentHistoryElement != null) { var segmentTime = segmentHistoryElement.Time[method]; if (segmentTime != null) { time += segmentTime.Value; if (segment.Comparisons[Name][method] == null || time < segment.Comparisons[Name][method]) { var newTime = new Time(segment.Comparisons[Name]); newTime[method] = time; segment.Comparisons[Name] = newTime; } } } else break; } } }
public void can_parse_time_two_digit_hours() { var compareTime = new Time(13, 59); string timeValue = "13:59:00"; var time = timeValue.ToTimeOfDay(); Assert.AreEqual(time, compareTime); }
public void can_parse_time_leading_zero() { var compareTime = new Time(3, 59, 59); string timeValue = "03:59:59"; var time = timeValue.ToTimeOfDay(); Assert.AreEqual(time, compareTime); }
public void can_extract_time_from_datetime() { var compareTime = new Time(13, 59); var dateTime = new DateTime(2011, 3, 5, 13, 59, 0); var time = dateTime.TimeOfTheDay(); Assert.AreEqual(time, compareTime); }
public static int GetFrequency(ITashaPerson person, Activity activity, Random random, int maxFrequency, Time startTime, Time endTime) { bool feasibleFreq = false; int freq = 0; while ( !feasibleFreq ) { freq = Distribution.GetRandomFrequencyValue( 0, maxFrequency, random, Distribution.GetDistributionID( person, activity ) ); if ( freq == 0 ) { break; } Time duration; if ( !Distribution.GetRandomStartTimeFrequency( Distribution.GetDistributionID( person, activity ), freq, Distribution.TimeOfDayToDistribution( startTime ), Distribution.TimeOfDayToDistribution( endTime ), random, out duration ) ) { //a bad thing happens here } else if ( duration != Time.Zero ) { feasibleFreq = true; } } return freq; }
public void Update(Time deltaTime) { if (Pause || Animation == null) return; // add delta time _currentTime += deltaTime; // if current time is bigger than frame time, advance one frame if (_currentTime <= FrameTime) return; // reset time, but keep remainder _currentTime = _currentTime % FrameTime; // get next frame index if (_currentFrame + 1 < Animation.Frames.Count) { _currentFrame++; } else { // animation has ended _currentFrame = 0; if (!Loop) { Pause = true; } } SetFrame(_currentFrame, false); }
public void SetFrame(int newFrame, bool resetTime) { if (Animation != null) { // calculate new vertex positions and texture coordinates var rect = Animation.Frames[newFrame]; var texCoordA = new Vector2f(0, 0); var texCoordB = new Vector2f(0, rect.Height); var texCoordC = new Vector2f(rect.Width, rect.Height); var texCoordD = new Vector2f(rect.Width, 0); var left = rect.Left + 0.0001f; var right = left + rect.Width; float top = rect.Top; var bottom = top + rect.Height; _vertices[0] = new Vertex(texCoordA, new Vector2f(left, top)); _vertices[1] = new Vertex(texCoordB, new Vector2f(left, bottom)); _vertices[2] = new Vertex(texCoordC, new Vector2f(right, bottom)); _vertices[3] = new Vertex(texCoordD, new Vector2f(right, top)); } if (resetTime) { _currentTime = Time.Zero; } }
public AnimatedSprite(Time frameTime, bool paused, bool looped) { FrameTime = frameTime; Pause = paused; Loop = looped; _vertices = new Vertex[4]; }
internal Gregorian(Time time, TimeZone timezone) { this.time = time; if (timezone == null) timezone = time.Context.Gmt (); this.timezone = timezone; }
public void Can_Add_Minutes() { Time time = new Time(22, 30); time = time.AddMinutes(105); Assert.AreEqual(0, time.Hour); Assert.AreEqual(15, time.Minute); }
protected override void Update(Time time) { sateenkaari.X = (lanta.X + hahmo.X)/2; sateenkaari.Y = hahmo.Y; sateenkaari.Width = hahmo.X - lanta.X; base.Update(time); }
static void Main() { Time Now = new Time(12, 34, 56); Now.OutTime(); Now["분"] = 19; Console.WriteLine("분은 {0}입니다.", Now["분"]); }
internal static void Main(string[] args) { shapes = new List<Shape>(); window = new RenderWindow(new VideoMode(WINDOW_SIZE.X, WINDOW_SIZE.Y), "Physics Playground", Styles.Titlebar | Styles.Close); window.SetVerticalSyncEnabled(true); window.SetKeyRepeatEnabled(false); SetupEvents(); Time lastTime = clock.ElapsedTime; while(window.IsOpen) { Time now = clock.ElapsedTime; Time frame = now - lastTime; lastTime = now; lag += frame; while(lag >= dt) { window.DispatchEvents(); if(!paused) { Update(); } lag -= dt; } Draw(); } }
public TimeSlot(int number, Time startTime, TimeSpan duration, bool isAvailable) { Number = number; StartTime = startTime; Duration = duration; IsAvailable = isAvailable; }
public int GetIsSegmentActiveScore(ActiveMode mode, Time time, double? minPermanence = null, int? activationThreshold = null) { return Synapses.Count(synapse => synapse.IsConnected(minPermanence) && synapse.GetIsActive(mode, time)) - (activationThreshold ?? Network.Instance.Parameters.ActivationThreshold); }
/** # Time units * Whenever durations need to be specified, eg for a timeout parameter, the duration can be specified * as a whole number representing time in milliseconds, or as a time value like `2d` for 2 days. * * ## Using Time units in NEST * NEST uses `Time` to strongly type this and there are several ways to construct one. * * ### Constructor * The most straight forward way to construct a `Time` is through its constructor */ [U] public void Constructor() { var unitString = new Time("2d"); var unitComposed = new Time(2, Nest.TimeUnit.Day); var unitTimeSpan = new Time(TimeSpan.FromDays(2)); var unitMilliseconds = new Time(1000 * 60 * 60 * 24 * 2); /** * When serializing Time constructed from a string, milliseconds, composition of factor and * interval, or a `TimeSpan` the expression will be serialized as time unit string */ Expect("2d") .WhenSerializing(unitString) .WhenSerializing(unitComposed) .WhenSerializing(unitTimeSpan) .WhenSerializing(unitMilliseconds); /** * Milliseconds are always calculated even when not using the constructor that takes a long */ unitMilliseconds.Milliseconds.Should().Be(1000*60*60*24*2); unitComposed.Milliseconds.Should().Be(1000*60*60*24*2); unitTimeSpan.Milliseconds.Should().Be(1000*60*60*24*2); unitString.Milliseconds.Should().Be(1000*60*60*24*2); }
public override void CacheEngineValues(IEngine iEngine) { // Am expecting this to be called just once to initialise values // prior to pull run var iEngineTime = iEngine as IEngineTime; if (iEngineTime == null) throw new Exception("IEngine not IEngineTime"); var at = new Time(iEngineTime.GetCurrentTime()); if (_cache.Count > 0) { if (at.StampAsModifiedJulianDay < _cache.Last().Time.StampAsModifiedJulianDay) throw new Exception(string.Format("Engine moving back in time, {0} < {1}", at.ToString(), _cache.Last().Time.ToString())); else if (at.StampAsModifiedJulianDay == _cache.Last().Time.StampAsModifiedJulianDay) _cache.RemoveAt(_cache.Count - 1); } var vs = _link.SourceComponent.GetValues(Utilities.Standard1.ToTime1(at), _link.ID); var record = ToTimeRecord(at, vs, _missingValue); if (HasItemChangedEvents) SendItemChangedEvent(string.Format("Standard1.ValueSetConvertorTarget: Cached from v1.link at {0}", at.ToString())); _cache.Add(record); if (_counts[(int)Counts.CacheMaxSize] < _cache.Count) _counts[(int)Counts.CacheMaxSize] = _cache.Count; }
public IRun Create(IComparisonGeneratorsFactory factory) { var run = new Run(factory); var reader = new StreamReader(Stream); var line = reader.ReadLine(); var titleInfo = line.Split('|'); run.CategoryName = titleInfo[0].Substring(1); run.AttemptCount = int.Parse(titleInfo[1]); TimeSpan totalTime = TimeSpan.Zero; while ((line = reader.ReadLine()) != null) { if (line.Length > 0) { var majorSplitInfo = line.Split('|'); totalTime += TimeSpanParser.Parse(majorSplitInfo[1]); while (!reader.EndOfStream && reader.Read() == '*') { line = reader.ReadLine(); run.AddSegment(line); } var newTime = new Time(run.Last().PersonalBestSplitTime); newTime.GameTime = totalTime; run.Last().PersonalBestSplitTime = newTime; } else { break; } } return run; }
static void Main() { Time Now = new Time(12, 34, 56); Console.WriteLine((int)Now); Console.WriteLine((double)Now); Console.WriteLine(Now); }
public void LoadConversationTemplates() { _conversationActorTemplateStorage.Clear(); _conversationLineTemplateStorage.Clear(); _conversationTemplateStorage.Clear(); Dictionary <uint, ConversationActorTemplate[]> actorsByConversation = new Dictionary <uint, ConversationActorTemplate[]>(); Dictionary <uint, ulong[]> actorGuidsByConversation = new Dictionary <uint, ulong[]>(); SQLResult actorTemplates = DB.World.Query("SELECT Id, CreatureId, CreatureModelId FROM conversation_actor_template"); if (!actorTemplates.IsEmpty()) { uint oldMSTime = Time.GetMSTime(); do { uint id = actorTemplates.Read <uint>(0); ConversationActorTemplate conversationActor = new ConversationActorTemplate(); conversationActor.Id = id; conversationActor.CreatureId = actorTemplates.Read <uint>(1); conversationActor.CreatureModelId = actorTemplates.Read <uint>(2); _conversationActorTemplateStorage[id] = conversationActor; }while (actorTemplates.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation actor templates in {1} ms", _conversationActorTemplateStorage.Count, Time.GetMSTimeDiffToNow(oldMSTime)); } else { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation actor templates. DB table `conversation_actor_template` is empty."); } SQLResult lineTemplates = DB.World.Query("SELECT Id, StartTime, UiCameraID, ActorIdx, Unk FROM conversation_line_template"); if (!lineTemplates.IsEmpty()) { uint oldMSTime = Time.GetMSTime(); do { uint id = lineTemplates.Read <uint>(0); if (!CliDB.ConversationLineStorage.ContainsKey(id)) { Log.outError(LogFilter.Sql, "Table `conversation_line_template` has template for non existing ConversationLine (ID: {0}), skipped", id); continue; } ConversationLineTemplate conversationLine = new ConversationLineTemplate(); conversationLine.Id = id; conversationLine.StartTime = lineTemplates.Read <uint>(1); conversationLine.UiCameraID = lineTemplates.Read <uint>(2); conversationLine.ActorIdx = lineTemplates.Read <ushort>(3); conversationLine.Unk = lineTemplates.Read <ushort>(4); _conversationLineTemplateStorage[id] = conversationLine; }while (lineTemplates.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation line templates in {1} ms", _conversationLineTemplateStorage.Count, Time.GetMSTimeDiffToNow(oldMSTime)); } else { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation line templates. DB table `conversation_line_template` is empty."); } SQLResult actorResult = DB.World.Query("SELECT ConversationId, ConversationActorId, ConversationActorGuid, Idx FROM conversation_actors"); if (!actorResult.IsEmpty()) { uint oldMSTime = Time.GetMSTime(); uint count = 0; do { uint conversationId = actorResult.Read <uint>(0); uint actorId = actorResult.Read <uint>(1); ulong actorGuid = actorResult.Read <ulong>(2); ushort idx = actorResult.Read <ushort>(3); if (actorId != 0 && actorGuid != 0) { Log.outError(LogFilter.Sql, $"Table `conversation_actors` references both actor (ID: {actorId}) and actorGuid (GUID: {actorGuid}) for Conversation {conversationId}, skipped."); continue; } if (actorId != 0) { ConversationActorTemplate conversationActorTemplate = _conversationActorTemplateStorage.LookupByKey(actorId); if (conversationActorTemplate != null) { if (!actorsByConversation.ContainsKey(conversationId)) { actorsByConversation[conversationId] = new ConversationActorTemplate[idx + 1]; } ConversationActorTemplate[] actors = actorsByConversation[conversationId]; if (actors.Length <= idx) { Array.Resize(ref actors, idx + 1); } actors[idx] = conversationActorTemplate; ++count; } else { Log.outError(LogFilter.Sql, "Table `conversation_actors` references an invalid actor (ID: {0}) for Conversation {1}, skipped", actorId, conversationId); } } else if (actorGuid != 0) { CreatureData creData = Global.ObjectMgr.GetCreatureData(actorGuid); if (creData != null) { if (!actorGuidsByConversation.ContainsKey(conversationId)) { actorGuidsByConversation[conversationId] = new ulong[idx + 1]; } var guids = actorGuidsByConversation[conversationId]; if (guids.Length <= idx) { Array.Resize(ref guids, idx + 1); } guids[idx] = actorGuid; ++count; } else { Log.outError(LogFilter.Sql, $"Table `conversation_actors` references an invalid creature guid (GUID: {actorGuid}) for Conversation {conversationId}, skipped"); } } }while (actorResult.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation actors in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime)); } else { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation actors. DB table `conversation_actors` is empty."); } SQLResult templateResult = DB.World.Query("SELECT Id, FirstLineId, LastLineEndTime, ScriptName FROM conversation_template"); if (!templateResult.IsEmpty()) { uint oldMSTime = Time.GetMSTime(); do { ConversationTemplate conversationTemplate = new ConversationTemplate(); conversationTemplate.Id = templateResult.Read <uint>(0); conversationTemplate.FirstLineId = templateResult.Read <uint>(1); conversationTemplate.LastLineEndTime = templateResult.Read <uint>(2); conversationTemplate.ScriptId = Global.ObjectMgr.GetScriptId(templateResult.Read <string>(3)); conversationTemplate.Actors = actorsByConversation[conversationTemplate.Id].ToList(); conversationTemplate.ActorGuids = actorGuidsByConversation[conversationTemplate.Id].ToList(); ConversationLineRecord currentConversationLine = CliDB.ConversationLineStorage.LookupByKey(conversationTemplate.FirstLineId); if (currentConversationLine == null) { Log.outError(LogFilter.Sql, "Table `conversation_template` references an invalid line (ID: {0}) for Conversation {1}, skipped", conversationTemplate.FirstLineId, conversationTemplate.Id); } while (currentConversationLine != null) { ConversationLineTemplate conversationLineTemplate = _conversationLineTemplateStorage.LookupByKey(currentConversationLine.Id); if (conversationLineTemplate != null) { conversationTemplate.Lines.Add(conversationLineTemplate); } else { Log.outError(LogFilter.Sql, "Table `conversation_line_template` has missing template for line (ID: {0}) in Conversation {1}, skipped", currentConversationLine.Id, conversationTemplate.Id); } if (currentConversationLine.NextLineID == 0) { break; } currentConversationLine = CliDB.ConversationLineStorage.LookupByKey(currentConversationLine.NextLineID); } _conversationTemplateStorage[conversationTemplate.Id] = conversationTemplate; }while (templateResult.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation templates in {1} ms", _conversationTemplateStorage.Count, Time.GetMSTimeDiffToNow(oldMSTime)); } else { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation templates. DB table `conversation_template` is empty."); } }
public static void LoadItemRandomBonusListTemplates() { uint oldMSTime = Time.GetMSTime(); _storage.Clear(); // 0 1 2 SQLResult result = DB.World.Query("SELECT Id, BonusListID, Chance FROM item_random_bonus_list_template"); if (result.IsEmpty()) { Log.outError(LogFilter.Player, "Loaded 0 Item Enchantment definitions. DB table `item_enchantment_template` is empty."); return; } uint count = 0; do { uint id = result.Read <uint>(0); uint bonusListId = result.Read <uint>(1); float chance = result.Read <float>(2); if (Global.DB2Mgr.GetItemBonusList(bonusListId) == null) { Log.outError(LogFilter.Sql, $"Bonus list {bonusListId} used in `item_random_bonus_list_template` by id {id} doesn't have exist in ItemBonus.db2"); continue; } if (chance < 0.000001f || chance > 100.0f) { Log.outError(LogFilter.Sql, $"Bonus list {bonusListId} used in `item_random_bonus_list_template` by id {id} has invalid chance {chance}"); continue; } if (!_storage.ContainsKey(id)) { _storage[id] = new RandomBonusListIds(); } RandomBonusListIds ids = _storage[id]; ids.BonusListIDs.Add(bonusListId); ids.Chances.Add(chance); ++count; } while (result.NextRow()); Log.outInfo(LogFilter.Player, $"Loaded {count} Random item bonus list definitions in {Time.GetMSTimeDiffToNow(oldMSTime)} ms"); }
public override string ToString() { return($"名称:{Name},区域:{Area},日期:{Time?.ToString()},即时配送:{Delivery},性质:{string.Join(",", Type)},特殊资源:{Resource},活动形式:{Description}"); }
/// <summary> /// Gets the logs of a specific live algorithm /// </summary> /// <param name="projectId">Project Id of the live running algorithm</param> /// <param name="algorithmId">Algorithm Id of the live running algorithm</param> /// <param name="startTime">No logs will be returned before this time</param> /// <param name="endTime">No logs will be returned after this time</param> /// <returns><see cref="LiveLog"/> List of strings that represent the logs of the algorithm</returns> public LiveLog ReadLiveLogs(int projectId, string algorithmId, DateTime?startTime = null, DateTime?endTime = null) { var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value); var epochEndTime = endTime == null?Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value); var request = new RestRequest("live/read/log", Method.POST) { RequestFormat = DataFormat.Json }; request.AddParameter("application/json", JsonConvert.SerializeObject(new { format = "json", projectId, algorithmId, start = epochStartTime, end = epochEndTime }), ParameterType.RequestBody); LiveLog result; ApiConnection.TryRequest(request, out result); return(result); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return(Time.Parse(reader.Value.ToString())); }
protected override void UpdateThis(Time time) { DisplayValue = MathHelper.Lerp((float)DisplayValue, (float)Value, lerpSpeed * (float)time.Delta); base.UpdateThis(time); }
void HandlePlayersSubstitutionEvent(Team team, Player p1, Player p2, SubstitutionReason reason, Time time) { widget.ReDraw(); if (PlayersSubstitutionEvent != null) { PlayersSubstitutionEvent(team, p1, p2, reason, time); } }
private void UpdateSpActionGauge() { if (!(owner == null) && owner.CheckAttackMode(Player.ATTACK_MODE.PAIR_SWORDS)) { switch (owner.spAttackType) { case SP_ATTACK_TYPE.HEAT: { if (!owner.isBoostMode) { return; } float num = 1f + owner.buffParam.GetGaugeDecreaseRate(); owner.spActionGauge[owner.weaponIndex] -= pairSwordsInfo.boostGaugeDecreasePerSecond * num * Time.get_deltaTime(); break; } case SP_ATTACK_TYPE.SOUL: if ((chargeState == CHARGE_STATE.LASER_SHOT || chargeState == CHARGE_STATE.LASER_LOOP) && isEventShotLaserExec) { spActionGauge -= pairSwordsInfo.Soul_GaugeDecreaseShootingLaserPerSecond * Time.get_deltaTime(); } else if (timerForSpActionGaugeDecreaseAfterHit >= pairSwordsInfo.Soul_TimeForGaugeDecreaseAfterHit && (!IsComboLvMax() || !(timerForSpActionGaugeDecreaseAfterHit < pairSwordsInfo.Soul_TimeForGaugeDecreaseAfterHitOnComboLvMax))) { if (chargeState == CHARGE_STATE.LOOP || (chargeState == CHARGE_STATE.LASER_SHOT && !isEventShotLaserExec)) { spActionGauge -= pairSwordsInfo.Soul_GaugeDecreaseWaitingLaserPerSecond * Time.get_deltaTime(); } else { spActionGauge -= pairSwordsInfo.Soul_GaugeDecreasePerSecond * Time.get_deltaTime(); } } break; } if (spActionGauge <= 0f) { spActionGauge = 0f; } } }
public void timeChanged(Time t) { Debug.Log("time change"); currentTime = t; StartCoroutine("hueRotate"); }
/// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!data.Bars.ContainsKey(symbol)) { return; } // each month make an action if (Time.Month != LastMonth) { // we'll submit the next type of order from the queue var orderType = _orderTypesQueue.Dequeue(); //Log(""); Log($"\r\n--------------MONTH: {Time.ToStringInvariant("MMMM")}:: {orderType}\r\n"); //Log(""); LastMonth = Time.Month; Log("ORDER TYPE:: " + orderType); var isLong = Quantity > 0; var stopPrice = isLong ? (1 + StopPercentage) * data.Bars[symbol].High : (1 - StopPercentage) * data.Bars[symbol].Low; var limitPrice = isLong ? (1 - LimitPercentage) * stopPrice : (1 + LimitPercentage) * stopPrice; if (orderType == OrderType.Limit) { limitPrice = !isLong ? (1 + LimitPercentage) * data.Bars[symbol].High : (1 - LimitPercentage) * data.Bars[symbol].Low; } var request = new SubmitOrderRequest(orderType, SecType, symbol, Quantity, stopPrice, limitPrice, UtcTime, orderType.ToString()); var ticket = Transactions.AddOrder(request); _tickets.Add(ticket); } else if (_tickets.Count > 0) { var ticket = _tickets.Last(); if (Time.Day > 8 && Time.Day < 14) { if (ticket.UpdateRequests.Count == 0 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { Quantity = ticket.Quantity + Math.Sign(Quantity) * DeltaQuantity, Tag = "Change quantity: " + Time }); Log("UPDATE1:: " + ticket.UpdateRequests.Last()); } } else if (Time.Day > 13 && Time.Day < 20) { if (ticket.UpdateRequests.Count == 1 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { LimitPrice = Security.Price * (1 - Math.Sign(ticket.Quantity) * LimitPercentageDelta), StopPrice = Security.Price * (1 + Math.Sign(ticket.Quantity) * StopPercentageDelta), Tag = "Change prices: " + Time }); Log("UPDATE2:: " + ticket.UpdateRequests.Last()); } } else { if (ticket.UpdateRequests.Count == 2 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Cancel(Time + " and is still open!"); Log("CANCELLED:: " + ticket.CancelRequest); } } } }
private void Clear() { while (true) { try { log.InfoFormat("Start cleaner interation."); using (var db = new DbManager("default")) { var t = new SqlCreate.Table("jabber_clear", true) .AddColumn("lastdate", DbType.DateTime); db.ExecuteNonQuery(t); var mindate = db.ExecuteScalar <DateTime>("select lastdate from jabber_clear limit 1"); var tenants = new List <Tuple <int, string> >(); var maxdate = DateTime.UtcNow.AddDays(-365); var sql = @"select t.id, t.alias from tenants_tenants t, webstudio_uservisit v where t.id = v.tenantid and t.creationdatetime < ? group by 1,2 having max(v.visitdate) between ? and ?"; using (var cmd = CreateCommand(db, sql, maxdate, mindate, maxdate)) using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { tenants.Add(Tuple.Create(reader.GetInt32(0), reader.GetString(1))); } } log.DebugFormat("Find {0} tenants for clear jabber messages", tenants.Count); foreach (var tid in tenants) { // remove all service messages in inactive (no visits at last year) portals var domain = CoreContext.Configuration.BaseDomain; var replace = ConfigurationManager.AppSettings["jabber.replace-domain"]; if (!string.IsNullOrEmpty(replace)) { var arr = replace.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries); var from = arr[0]; var to = arr[1]; domain = domain.Replace(to, from); // revert replace } domain = (tid.Item2.EndsWith("_deleted") ? tid.Item2.Substring(0, tid.Item2.Length - 8) : tid.Item2) + "." + domain; if (stop.WaitOne(TimeSpan.Zero)) { return; } RemoveFromArchive(db, domain, maxdate); var users = new List <string>(); using (var cmd = CreateCommand(db, "select username from core_user where tenant = ? and username <= ?", tid.Item1, tid.Item2)) using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { users.Add(reader.GetString(0)); } } foreach (var user in users) { var username = user.ToLowerInvariant().Trim(); if (stop.WaitOne(TimeSpan.Zero)) { return; } var jid = string.Format("{0}@{1}|{1}", username, domain); RemoveFromArchive(db, jid, maxdate); } } db.ExecuteNonQuery("delete from jabber_clear;"); db.ExecuteNonQuery("insert into jabber_clear values (?)", maxdate); // remove offline messages var id = 0; using (var cmd = CreateCommand(db, "select id, message from jabber_offmessage order by 1")) using (var reader = cmd.ExecuteReader()) { var less = false; while (reader.Read()) { var message = reader.GetString(1); var m = Regex.Match(message, "<x xmlns=\"jabber:x:delay\" stamp=\"(.+)\""); if (m.Success) { var date = Time.Date(m.Groups[1].Value); if (date != DateTime.MinValue && date <= maxdate) { less = true; } else { if (less) { id = reader.GetInt32(0); } break; } } } } if (0 < id) { using (var cmd = CreateCommand(db, "delete from jabber_offmessage where id < ?", id)) { var affected = cmd.ExecuteNonQuery(); log.DebugFormat("Remove {0} messages from jabber_offmessage", affected); } } } } catch (ThreadAbortException) { // ignore } catch (Exception err) { log.Error(err); } if (stop.WaitOne(TimeSpan.FromDays(1))) { break; } } }
/// <summary> /// Get a list of live running algorithms for user /// </summary> /// <param name="status">Filter the statuses of the algorithms returned from the api</param> /// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param> /// <param name="endTime">Latest launched time of the algorithms returned by the Api</param> /// <returns><see cref="LiveList"/></returns> public LiveList ListLiveAlgorithms(AlgorithmStatus?status = null, DateTime?startTime = null, DateTime?endTime = null) { // Only the following statuses are supported by the Api if (status.HasValue && status != AlgorithmStatus.Running && status != AlgorithmStatus.RuntimeError && status != AlgorithmStatus.Stopped && status != AlgorithmStatus.Liquidated) { throw new ArgumentException( "The Api only supports Algorithm Statuses of Running, Stopped, RuntimeError and Liquidated"); } var request = new RestRequest("live/read", Method.GET); if (status.HasValue) { request.AddParameter("status", status.ToString()); } var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value); var epochEndTime = endTime == null?Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value); request.AddParameter("start", epochStartTime); request.AddParameter("end", epochEndTime); LiveList result; ApiConnection.TryRequest(request, out result); return(result); }
/// <summary> /// Gets the logs of a specific live algorithm /// </summary> /// <param name="projectId">Project Id of the live running algorithm</param> /// <param name="algorithmId">Algorithm Id of the live running algorithm</param> /// <param name="startTime">No logs will be returned before this time</param> /// <param name="endTime">No logs will be returned after this time</param> /// <returns><see cref="LiveLog"/> List of strings that represent the logs of the algorithm</returns> public LiveLog ReadLiveLogs(int projectId, string algorithmId, DateTime?startTime = null, DateTime?endTime = null) { var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value); var epochEndTime = endTime == null?Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value); var request = new RestRequest("live/read/log", Method.GET); request.AddParameter("format", "json"); request.AddParameter("projectId", projectId); request.AddParameter("algorithmId", algorithmId); request.AddParameter("start", epochStartTime); request.AddParameter("end", epochEndTime); LiveLog result; ApiConnection.TryRequest(request, out result); return(result); }
protected void LocomotionOnClosePosition() { if (this.LocomotionCount == 0 || !((Behaviour)this.Agent).get_enabled()) { return; } if (1 < this.LocomotionCount) { if (this.HasDestination) { this.destination = new Vector3?(); } if (this.Agent.get_updateRotation()) { return; } this.Agent.set_updateRotation(true); } else { if (!this.AgentHasPath && !this.HasDestination || (this.HasTwoCorners || this.Wait()) || this.Agent.get_isStopped()) { return; } if (!this.HasDestination && this.IsNearPointHasPath(this.disableUpdateDistance)) { this.destination = new Vector3?(this.Agent.get_destination()); this.Agent.set_updateRotation(false); Vector3 velocity = this.Agent.get_velocity(); this.toTargetVelocity = new Vector3(0.0f, 0.0f, ((Vector3) ref velocity).get_magnitude()); this.Agent.ResetPath(); } else if (this.HasDestination && !this.IsNearPoint(this.disableUpdateDistance)) { this.Agent.SetDestination(this.destination.Value); this.Agent.set_updateRotation(true); this.destination = new Vector3?(); } if (!this.HasDestination) { return; } Vector3 vector3_1 = this.destination.Value; Vector2 vector2_1; ((Vector2) ref vector2_1).\u002Ector((float)this.Forward.x, (float)this.Forward.z); Vector2 normalized1 = ((Vector2) ref vector2_1).get_normalized(); Vector2 vector2_2; ((Vector2) ref vector2_2).\u002Ector((float)(vector3_1.x - this.Position.x), (float)(vector3_1.z - this.Position.z)); Vector2 normalized2 = ((Vector2) ref vector2_2).get_normalized(); float num1 = Mathf.Acos(Mathf.Clamp(Vector2.Dot(normalized1, normalized2), -1f, 1f)) * 57.29578f; if (0.0 < (double)num1) { Vector3 vector3_2 = Vector3.Cross(new Vector3((float)normalized1.x, 0.0f, (float)normalized1.y), new Vector3((float)normalized2.x, 0.0f, (float)normalized2.y)); Vector3 eulerAngles = this.EulerAngles; float num2 = this.addAngle * Time.get_deltaTime() * Mathf.Sign((float)vector3_2.y); if ((double)num1 <= (double)Mathf.Abs(num2)) { ref Vector3 local = ref eulerAngles; local.y = (__Null)(local.y + (double)num1 * (double)Mathf.Sign((float)vector3_2.y)); } else { ref Vector3 local = ref eulerAngles; local.y = (__Null)(local.y + (double)num2); } eulerAngles.y = (__Null)(double)this.AngleAbs((float)eulerAngles.y); this.EulerAngles = eulerAngles; }
/// <summary> /// Update method to be called per game update /// </summary> /// <param name="time">Current GameTime</param> public virtual void Update(Time time) { //float delta = (float)(time.SinceLastUpdate.Milliseconds / 1000.0); //LastShot += delta; }
private void ProcessTouchPress(PointerEventData pointerEvent, bool pressed, bool released) { RaycastResult pointerCurrentRaycast = pointerEvent.get_pointerCurrentRaycast(); // ISSUE: explicit reference operation GameObject gameObject1 = ((RaycastResult) @pointerCurrentRaycast).get_gameObject(); if (pressed) { pointerEvent.set_eligibleForClick(true); pointerEvent.set_delta(Vector2.get_zero()); pointerEvent.set_pressPosition(pointerEvent.get_position()); pointerEvent.set_pointerPressRaycast(pointerEvent.get_pointerCurrentRaycast()); if (Object.op_Inequality((Object) pointerEvent.get_pointerEnter(), (Object) gameObject1)) { ((BaseInputModule) this).HandlePointerExitAndEnter(pointerEvent, gameObject1); pointerEvent.set_pointerEnter(gameObject1); } GameObject gameObject2 = ExecuteEvents.ExecuteHierarchy<IPointerDownHandler>(gameObject1, (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_pointerDownHandler()); if (Object.op_Equality((Object) gameObject2, (Object) null)) gameObject2 = ExecuteEvents.GetEventHandler<IPointerClickHandler>(gameObject1); if (Object.op_Inequality((Object) gameObject2, (Object) pointerEvent.get_pointerPress())) { pointerEvent.set_pointerPress(gameObject2); pointerEvent.set_rawPointerPress(gameObject1); pointerEvent.set_clickCount(0); } pointerEvent.set_pointerDrag(ExecuteEvents.GetEventHandler<IDragHandler>(gameObject1)); if (Object.op_Inequality((Object) pointerEvent.get_pointerDrag(), (Object) null)) ExecuteEvents.Execute<IBeginDragHandler>(pointerEvent.get_pointerDrag(), (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_beginDragHandler()); ((BaseInputModule) this).get_eventSystem().SetSelectedGameObject(ExecuteEvents.GetEventHandler<ISelectHandler>(gameObject1), (BaseEventData) pointerEvent); } if (!released) return; float unscaledTime1 = Time.get_unscaledTime(); if ((double) this.mDoubleTap1stReleasedTime < 0.0) this.mDoubleTap1stReleasedTime = unscaledTime1; else if ((double) unscaledTime1 - (double) this.mDoubleTap1stReleasedTime >= 0.300000011920929) { this.mDoubleTap1stReleasedTime = unscaledTime1; } else { this.OnDoubleTap(pointerEvent.get_position()); this.mDoubleTap1stReleasedTime = -1f; } ExecuteEvents.Execute<IPointerUpHandler>(pointerEvent.get_pointerPress(), (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_pointerUpHandler()); GameObject eventHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(gameObject1); if (Object.op_Equality((Object) pointerEvent.get_pointerPress(), (Object) eventHandler) && pointerEvent.get_eligibleForClick()) { float unscaledTime2 = Time.get_unscaledTime(); if ((double) unscaledTime2 - (double) pointerEvent.get_clickTime() < 0.300000011920929) { PointerEventData pointerEventData = pointerEvent; pointerEventData.set_clickCount(pointerEventData.get_clickCount() + 1); } else pointerEvent.set_clickCount(1); pointerEvent.set_clickTime(unscaledTime2); ExecuteEvents.Execute<IPointerClickHandler>(pointerEvent.get_pointerPress(), (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_pointerClickHandler()); this.SpawnTouchEffect(pointerEvent.get_position()); } else if (Object.op_Inequality((Object) pointerEvent.get_pointerDrag(), (Object) null)) ExecuteEvents.ExecuteHierarchy<IDropHandler>(gameObject1, (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_dropHandler()); pointerEvent.set_eligibleForClick(false); pointerEvent.set_pointerPress((GameObject) null); pointerEvent.set_rawPointerPress((GameObject) null); if (Object.op_Inequality((Object) pointerEvent.get_pointerDrag(), (Object) null)) ExecuteEvents.Execute<IEndDragHandler>(pointerEvent.get_pointerDrag(), (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_endDragHandler()); pointerEvent.set_pointerDrag((GameObject) null); ExecuteEvents.ExecuteHierarchy<IPointerExitHandler>(pointerEvent.get_pointerEnter(), (BaseEventData) pointerEvent, (ExecuteEvents.EventFunction<M0>) ExecuteEvents.get_pointerExitHandler()); pointerEvent.set_pointerEnter((GameObject) null); }
internal static void PrimaryWorkStartTimeAndDuration(ITashaPerson person, out Time startTime, out Time duration) { throw new NotImplementedException(); }
public TimerTimeline(List <Timer> timers, bool showName, NodeDraggingMode draggingMode, bool showLine, Time maxTime, double offsetY, Color background, Color lineColor) : this(timers, showName, draggingMode, showLine, maxTime, StyleConf.TimelineCategoryHeight, offsetY, background, lineColor) { }
/// <inheritdoc cref="DynamicIndexSettings.UnassignedNodeLeftDelayedTimeout" /> public TDescriptor UnassignedNodeLeftDelayedTimeout(Time time) => Assign(a => a.UnassignedNodeLeftDelayedTimeout = time);
private void NotifyUser() { #region logging if (this.Time.Hour == 16) { sharesOwned = Portfolio[symbol].Quantity; var _transactionsAsCsv = CsvSerializer.Serialize <OrderTransaction>(",", _transactions, true); StringBuilder sb = new StringBuilder(); foreach (string s in _transactionsAsCsv) { sb.AppendLine(s); } string attachment = sb.ToString(); Notify.Email("*****@*****.**", string.Format("Todays Date: {0} \nNumber of Transactions: {1}", Time.ToLongDateString(), _transactions.Count()), attachment); var _tradesAsCsv = CsvSerializer.Serialize <MatchedTrade>(",", _orderTransactionProcessor.Trades.Where(f => f.DateAcquired == tradingDate), true); sb = new StringBuilder(); foreach (string s in _tradesAsCsv) { sb.AppendLine(s); } attachment = sb.ToString(); Notify.Email("*****@*****.**", string.Format("Todays Date: {0} \nNumber of Trades: {1}", Time.ToLongDateString(), _tradesAsCsv.Count()), attachment); _transactions = new List <OrderTransaction>(); } #endregion }
/// <inheritdoc cref="DynamicIndexSettings.RefreshInterval" /> public TDescriptor RefreshInterval(Time time) => Assign(a => a.RefreshInterval = time);
private Task EstablishConnection() { if (disposed) { return(new CompletedTask()); } var requestParams = new CreateHttpJsonRequestParams(null, url + "/changes/events?id=" + id, "GET", credentials, conventions) { AvoidCachingRequest = true }; return(jsonRequestFactory.CreateHttpJsonRequest(requestParams) .ServerPullAsync() .ContinueWith(task => { if (disposed) { throw new ObjectDisposedException("RemoteDatabaseChanges"); } if (task.IsFaulted) { logger.WarnException("Could not connect to server, will retry", task.Exception); Connected = false; ConnectionStatusChanged(this, EventArgs.Empty); if (disposed) { return task; } if (replicationInformer.IsServerDown(task.Exception) == false) { return task; } if (replicationInformer.IsHttpStatus(task.Exception, HttpStatusCode.NotFound, HttpStatusCode.Forbidden)) { return task; } return Time.Delay(TimeSpan.FromSeconds(15)) .ContinueWith(_ => EstablishConnection()) .Unwrap(); } Connected = true; ConnectionStatusChanged(this, EventArgs.Empty); connection = (IDisposable)task.Result; task.Result.Subscribe(this); Task prev = watchAllDocs ? Send("watch-docs", null) : new CompletedTask(); if (watchAllIndexes) { prev = prev.ContinueWith(_ => Send("watch-indexes", null)); } prev = watchedDocs.Aggregate(prev, (cur, docId) => cur.ContinueWith(task1 => Send("watch-doc", docId))); prev = watchedPrefixes.Aggregate(prev, (cur, prefix) => cur.ContinueWith(task1 => Send("watch-prefix", prefix))); prev = watchedIndexes.Aggregate(prev, (cur, index) => cur.ContinueWith(task1 => Send("watch-indexes", index))); return prev; }) .Unwrap()); }
}// End of Method public int CompareTo(PlayerStats other) { return(Time.CompareTo(Time)); }// End of Method
/// <summary> /// Hides the widget by making it leave with an animation /// </summary> /// <param name="type">Type of the animation</param> /// <param name="duration">Duration of the animation</param> /// <remarks> /// If the widget is already hidden then the animation will still play but you will not see it. /// /// During the animation the position, size and/or opacity may change. Once the animation is done the widget will /// be back in the state in which it was when this function was called, except that it will no longer be visible. /// </remarks> public void HideWithEffect(ShowAnimationType type, Time duration) { tguiWidget_hideWithEffect(CPointer, type, duration); }
static extern private void tguiWidget_hideWithEffect(IntPtr cPointer, ShowAnimationType type, Time duration);
protected override void Run() { output.WriteLine("TimeoutCommand - run() start"); Time.Wait(500); output.WriteLine("TimeoutCommand - run() finish"); }
} // End Run(); /// <summary> /// Every so often send an update to the browser with the current state of the algorithm. /// </summary> public void Update() { //Initialize: Dictionary <int, Order> deltaOrders; //Error checks if the algorithm & threads have not loaded yet, or are closing down. if (_algorithm == null || _algorithm.Transactions == null || _transactionHandler.Orders == null || !_algorithm.GetLocked()) { Log.Error("LiveTradingResultHandler.Update(): Algorithm not yet initialized."); return; } try { if (DateTime.Now > _nextUpdate || _exitTriggered) { //Extract the orders created since last update OrderEvent orderEvent; deltaOrders = new Dictionary <int, Order>(); var stopwatch = Stopwatch.StartNew(); while (_orderEvents.TryDequeue(out orderEvent) && stopwatch.ElapsedMilliseconds < 15) { var order = _algorithm.Transactions.GetOrderById(orderEvent.OrderId); deltaOrders[orderEvent.OrderId] = order.Clone(); } //For charting convert to UTC foreach (var order in deltaOrders) { order.Value.Price = order.Value.Price.SmartRounding(); order.Value.Time = order.Value.Time.ToUniversalTime(); } //Reset loop variables: _lastOrderId = (from order in deltaOrders.Values select order.Id).DefaultIfEmpty(_lastOrderId).Max(); //Limit length of orders we pass back dynamically to avoid flooding. //if (deltaOrders.Count > 50) deltaOrders.Clear(); //Create and send back the changes in chart since the algorithm started. var deltaCharts = new Dictionary <string, Chart>(); Log.Debug("LiveTradingResultHandler.Update(): Build delta charts"); lock (_chartLock) { //Get the updates since the last chart foreach (var chart in _charts) { // remove directory pathing characters from chart names var safeName = chart.Value.Name.Replace('/', '-'); deltaCharts.Add(safeName, chart.Value.GetUpdates()); } } Log.Debug("LiveTradingResultHandler.Update(): End build delta charts"); //Profit loss changes, get the banner statistics, summary information on the performance for the headers. var holdings = new Dictionary <string, Holding>(); var deltaStatistics = new Dictionary <string, string>(); var runtimeStatistics = new Dictionary <string, string>(); var serverStatistics = OS.GetServerStatistics(); var upTime = DateTime.UtcNow - _launchTimeUtc; serverStatistics["Up Time"] = string.Format("{0}d {1:hh\\:mm\\:ss}", upTime.Days, upTime); // only send holdings updates when we have changes in orders, except for first time, then we want to send all foreach (var asset in _algorithm.Securities.Values.Where(x => !x.SubscriptionDataConfig.IsInternalFeed).OrderBy(x => x.Symbol.Value)) { holdings.Add(asset.Symbol.Value, new Holding(asset)); } //Add the algorithm statistics first. Log.Debug("LiveTradingResultHandler.Update(): Build run time stats"); lock (_runtimeLock) { foreach (var pair in _runtimeStatistics) { runtimeStatistics.Add(pair.Key, pair.Value); } } Log.Debug("LiveTradingResultHandler.Update(): End build run time stats"); //Add other fixed parameters. runtimeStatistics.Add("Unrealized:", "$" + _algorithm.Portfolio.TotalUnrealizedProfit.ToString("N2")); runtimeStatistics.Add("Fees:", "-$" + _algorithm.Portfolio.TotalFees.ToString("N2")); runtimeStatistics.Add("Net Profit:", "$" + _algorithm.Portfolio.TotalProfit.ToString("N2")); runtimeStatistics.Add("Return:", ((_algorithm.Portfolio.TotalPortfolioValue - _setupHandler.StartingPortfolioValue) / _setupHandler.StartingPortfolioValue).ToString("P")); runtimeStatistics.Add("Equity:", "$" + _algorithm.Portfolio.TotalPortfolioValue.ToString("N2")); runtimeStatistics.Add("Holdings:", "$" + _algorithm.Portfolio.TotalHoldingsValue.ToString("N2")); runtimeStatistics.Add("Volume:", "$" + _algorithm.Portfolio.TotalSaleVolume.ToString("N2")); // since we're sending multiple packets, let's do it async and forget about it // chart data can get big so let's break them up into groups var splitPackets = SplitPackets(deltaCharts, deltaOrders, holdings, deltaStatistics, runtimeStatistics, serverStatistics); foreach (var liveResultPacket in splitPackets) { _messagingHandler.Send(liveResultPacket); } //Send full packet to storage. if (DateTime.Now > _nextChartsUpdate || _exitTriggered) { Log.Debug("LiveTradingResultHandler.Update(): Pre-store result"); _nextChartsUpdate = DateTime.Now.AddMinutes(1); var chartComplete = new Dictionary <string, Chart>(); lock (_chartLock) { foreach (var chart in Charts) { // remove directory pathing characters from chart names var safeName = chart.Value.Name.Replace('/', '-'); chartComplete.Add(safeName, chart.Value); } } var orders = new Dictionary <int, Order>(_transactionHandler.Orders); var complete = new LiveResultPacket(_job, new LiveResult(chartComplete, orders, _algorithm.Transactions.TransactionRecord, holdings, deltaStatistics, runtimeStatistics, serverStatistics)); StoreResult(complete); Log.Debug("LiveTradingResultHandler.Update(): End-store result"); } // Upload the logs every 1-2 minutes; this can be a heavy operation depending on amount of live logging and should probably be done asynchronously. if (DateTime.Now > _nextLogStoreUpdate || _exitTriggered) { List <LogEntry> logs; Log.Debug("LiveTradingResultHandler.Update(): Storing log..."); lock (_logStoreLock) { var utc = DateTime.UtcNow; logs = (from log in _logStore where log.Time >= utc.RoundDown(TimeSpan.FromHours(1)) select log).ToList(); //Override the log master to delete the old entries and prevent memory creep. _logStore = logs; } StoreLog(logs); _nextLogStoreUpdate = DateTime.Now.AddMinutes(2); Log.Debug("LiveTradingResultHandler.Update(): Finished storing log"); } // Every minute send usage statistics: if (DateTime.Now > _nextStatisticsUpdate || _exitTriggered) { try { _api.SendStatistics( _job.AlgorithmId, _algorithm.Portfolio.TotalUnrealizedProfit, _algorithm.Portfolio.TotalFees, _algorithm.Portfolio.TotalProfit, _algorithm.Portfolio.TotalHoldingsValue, _algorithm.Portfolio.TotalPortfolioValue, ((_algorithm.Portfolio.TotalPortfolioValue - _setupHandler.StartingPortfolioValue) / _setupHandler.StartingPortfolioValue), _algorithm.Portfolio.TotalSaleVolume, _lastOrderId, 0); } catch (Exception err) { Log.Error(err, "Error sending statistics:"); } _nextStatisticsUpdate = DateTime.Now.AddMinutes(1); } Log.Debug("LiveTradingResultHandler.Update(): Trimming charts"); lock (_chartLock) { foreach (var chart in Charts) { foreach (var series in chart.Value.Series) { // trim data that's older than 2 days series.Value.Values = (from v in series.Value.Values where v.x > Time.DateTimeToUnixTimeStamp(DateTime.UtcNow.AddDays(-2)) select v).ToList(); } } } Log.Debug("LiveTradingResultHandler.Update(): Finished trimming charts"); //Set the new update time after we've finished processing. // The processing can takes time depending on how large the packets are. _nextUpdate = DateTime.Now.AddSeconds(2); } // End Update Charts: } catch (Exception err) { Log.Error(err, "LiveTradingResultHandler().Update(): ", true); } }
/// <summary> /// Get a list of live running algorithms for user /// </summary> /// <param name="status">Filter the statuses of the algorithms returned from the api</param> /// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param> /// <param name="endTime">Latest launched time of the algorithms returned by the Api</param> /// <returns><see cref="LiveList"/></returns> public LiveList ListLiveAlgorithms(AlgorithmStatus?status = null, DateTime?startTime = null, DateTime?endTime = null) { // Only the following statuses are supported by the Api if (status.HasValue && status != AlgorithmStatus.Running && status != AlgorithmStatus.RuntimeError && status != AlgorithmStatus.Stopped && status != AlgorithmStatus.Liquidated) { throw new ArgumentException( "The Api only supports Algorithm Statuses of Running, Stopped, RuntimeError and Liquidated"); } var request = new RestRequest("live/read", Method.POST) { RequestFormat = DataFormat.Json }; var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value); var epochEndTime = endTime == null?Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value); JObject obj = new JObject { { "start", epochStartTime }, { "end", epochEndTime } }; if (status.HasValue) { obj.Add("status", status.ToString()); } request.AddParameter("application/json", JsonConvert.SerializeObject(obj), ParameterType.RequestBody); LiveList result; ApiConnection.TryRequest(request, out result); return(result); }
private void Awake() { instance = this; }
public IDisposable Run(Time parent) { _watch = parent._scheduler.StartStopwatch(); return(parent._source.SubscribeSafe(this)); }