///// <summary>
        ///// Create a new, ephermal metric to watch
        ///// </summary>
        ///// <param name="pipeline"></param>
        ///// <param name="jsAggregator"></param>
        ///// <param name="name"></param>
        ///// <param name="connection"></param>
        ///// <param name="connectionId"></param>
        //public JavascriptMetricConnection(EventPipeline pipeline, string jsAggregator, string name, IConnection connection, string connectionId, string javascriptId) {
        //    _connection = connection;
        //    _javascriptId = javascriptId;
        //    _connectionId = connectionId;
        //    var jsMetric = new JavascriptMetric(name, jsAggregator);
        //    jsMetric.Updated(connectionId, Updated);
        //    pipeline.AddProcessor(jsMetric);
        //    SendUpdates();
        //}
        /// <summary>
        /// Bind to an existing metric given by "name"
        /// </summary>
        /// <param name="pipeline"></param>
        /// <param name="name"></param>
        /// <param name="connection"></param>
        /// <param name="connectionId"></param>
        public JavascriptMetricConnection(EventPipeline pipeline, string name, IConnection connection, string connectionId, string javascriptId, string keyFilter, TimePeriod period)
        {
            _connection = connection;
            _connectionId = connectionId;
            _javascriptId = javascriptId;
            _timePeriod = period;
            _keyFilter = PeriodMetric.BaseKey(name, _timePeriod, keyFilter);

            if (string.IsNullOrEmpty(_keyFilter)) {
                _keyFilter = "*";
            }

            // Try to find the metric, and add a watcher
            var processor = pipeline.GetProcessor(name);

            if (processor == null) {
                throw new Exception(string.Format("Unable to find metric with name {0}", name));
            }

            var jsMetric = processor as JavascriptMetric;
            if (jsMetric == null) {
                throw new Exception(string.Format("Found metric with name {0}, but its not a JavascriptMetric", name));
            }

            jsMetric.Updated(_connectionId, Updated);

            SendUpdates();
        }
    public void Create(IList<BondAnalysisLine> lines_, BondField field_, TimePeriod period_)
    {
      setupStuff();

      BoxSetSeries series = (BoxSetSeries)ultraChart1.CompositeChart.Series[0];

      series.BoxSets.Clear();
      m_lineData_dt.Rows.Clear();

      foreach (var bondstats in lines_)
      {
        var fieldValues = bondstats.GetHistoricValuesForField(field_, period_);
        if (fieldValues == null || fieldValues.Length==0)
          continue;

        var last = fieldValues.Data.Last();

        QuickSort.Sort(fieldValues.Data);

        series.BoxSets.Add(new BoxSet()
        {
          Label = bondstats.Bond,
          Min = fieldValues.Data[0],
          Max = fieldValues.Data.Last(),
          Q1 = fieldValues.Data[(int) fieldValues.Length/4],
          Q2 = fieldValues.Data.Average(),
          Q3 = fieldValues.Data[(int) fieldValues.Length/4*3]
        });

        m_lineData_dt.LoadDataRow(new object[] {bondstats.Bond, last},true);
      }


    }
Exemple #3
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Server.ScriptTimeout = PageTimeout;

                WebUtil.TryEnableCompression(context);
                context.Response.ContentType = "text/plain";

                var requestParams = context.Request.Params;

                var appKey = requestParams.Get("Application") ?? "";

                var period = new TimePeriod(requestParams);

                var sessions = DataReader.GetSessions(appKey, period);

                foreach (var session in sessions)
                {
                    context.Response.Write(session.Serialize());
                    context.Response.Write(Environment.NewLine);
                }
            }
            catch (Exception exc)
            {
                WebLogger.Report(exc);
                context.Response.Write(exc.ToString());
            }
        }
Exemple #4
0
 /// <summary>
 /// </summary>
 /// <param name="name">Name of the maintenance.</param>
 /// <param name="groupids">IDs of the host groups that will undergo maintenance.</param>
 /// <param name="hostids">IDs of the hosts that will undergo maintenance.</param>
 /// <param name="timeperiods">Maintenance time periods.</param>
 public Create(string name, int[] groupids, int[] hostids, TimePeriod[] timeperiods)
     : base(name)
 {
     this.groupids = groupids;
     this.hostids = hostids;
     this.timeperiods = timeperiods;
 }
        public List<TimePeriod> generateCalendar1()
        {
            List<TimePeriod> list = new List<TimePeriod>();

            TimePeriod tp1 = new TimePeriod();
            tp1.Start = new DateTime(2015, 12, 12, 9, 30, 0);
            tp1.End = new DateTime(2015, 12, 12, 11, 30, 0);
            list.Add(tp1);

            TimePeriod tp2 = new TimePeriod();
            tp2.Start = new DateTime(2015, 12, 12, 12, 30, 0);
            tp2.End = new DateTime(2015, 12, 12, 13, 30, 0);
            list.Add(tp2);

            TimePeriod tp3 = new TimePeriod();
            tp3.Start = new DateTime(2015, 12, 12, 15, 00, 0);
            tp3.End = new DateTime(2015, 12, 12, 18, 30, 0);
            list.Add(tp3);

            TimePeriod tp4 = new TimePeriod();
            tp4.Start = new DateTime(2015, 12, 12, 21, 20, 0);
            tp4.End = new DateTime(2015, 12, 12, 22, 00, 0);
            list.Add(tp4);

            return list;
        }
 /// <summary>
 /// Get the data from the specified time period, if available.  If no data are available, NULL is returned.
 /// </summary>
 /// <param name="timePeriod"></param>
 /// <returns></returns>
 public SoundSpeedField this[TimePeriod timePeriod]
 {
     get
     {
         return SoundSpeedFields.Find(t => t.TimePeriod == timePeriod);
     }
 }
Exemple #7
0
 //present past constructor
 public Portrait(string saveString, TimePeriod period)
 {
     this.sheet = sheetMan.getSheet("portrait");
     wasMoved = false;
     if (period == TimePeriod.Present)
     {
         parseString(saveString, "EndPresentPortrait");
         wasMoved = true;
         inTime = TimePeriod.Present;
         sendTime = TimePeriod.Past;
     }
     else if (period == TimePeriod.Past)
     {
         parseString(saveString, "EndPastPortrait");
         wasMoved = true;
         inTime = TimePeriod.Past;
         sendTime = TimePeriod.Past;
     }
     else if (period == TimePeriod.FarPast)
     {
         parseString(saveString, "EndOldPortrait");
         sendTime = TimePeriod.FarPast;
         sheet = sheetMan.getSheet("oldportrait");
     }
 }
 private string PretendToGetDataFromHttp(TimePeriod time)
 {
     Thread.Sleep(5000);
     //In the real implementation, use the TimePeriod in the http call
     var asStrings = data.Select(committer => new[] { committer.Name, committer.Commits.ToString(), committer.ImageUri.ToString() });
     return Csv.ToCsv(asStrings);
 }
Exemple #9
0
 public Portrait(string saveString, string str)
 {
     this.sheet = sheetMan.getSheet("portrait");
     sendTime = TimePeriod.Past;
     wasMoved = false;
     parseString(saveString, str);
 }
        public static void addEvent(CalendarService service, string email, string summary, string[] participants, TimePeriod timePeriod)
        {
            Event myEvent = new Event
            {
                Summary = summary,
                //Location = "Somewhere",
                Start = new EventDateTime()
                {
                    DateTime = timePeriod.Start.Value,
                    TimeZone = "Europe/London"
                },
                End = new EventDateTime()
                {
                    DateTime = timePeriod.End.Value,
                    TimeZone = "Europe/London"
                },
                /*Recurrence = new String[] {
                            "RRULE:FREQ=WEEKLY;BYDAY=MO"
                },*/

                //Attendees = getAttendees(participants)
            };

            //or Insert(myEvent, "primary")
            Event recurringEvent = service.Events.Insert(myEvent, email).Execute();
        }
 public static string FindTemperatureFile(TimePeriod monthIndex, string gdemDirectory)
 {
     var files = Directory.GetFiles(gdemDirectory, GDEMTemperatureFileName(monthIndex), SearchOption.AllDirectories);
     if (files.Length > 0) return files[0];
     files = Directory.GetFiles(gdemDirectory, NUWCTemperatureFileName(monthIndex), SearchOption.AllDirectories);
     if (files.Length > 0) return files[0];
     throw new FileNotFoundException(string.Format("Could not find requested temperature file, tried {0} and {1}", GDEMTemperatureFileName(monthIndex), NUWCTemperatureFileName(monthIndex)));
 }
        private TimePeriodModel mapTimePeriodToTimePeriodModel(TimePeriod timePeriod)
        {
            TimePeriodModel tpm = new TimePeriodModel();
            tpm.TimePeriodId = timePeriod.timeperiodid;
            tpm.Type = timePeriod.type;

            return tpm;
        }
 protected GameController()
 {
     updatableObjs = new List<Updatable>();
     drawableObjs = new List<Drawable>();
     collideableObjs = new List<Collideable>();
     levels = new Dictionary<string, Level>();
     state = GameState.Game;
     timePeriod = TimePeriod.Present;
 }
        public IncomeExpenseGraph(List<IGraphable> list, TimePeriod group, DateTime start, DateTime finish)
        {
            List = list;
            Group = group;
            Start = start;
            Finish = finish;

            InitialiseChart();
        }
Exemple #15
0
 public Level(int Width, int Height, int playerX, int playerY, Color wallpaperColor, TimePeriod startTime)
 {
     this.Width = Width;
     this.Height = Height;
     this.playerX = playerX;
     this.playerY = playerY;
     this.startTime = startTime;
     this.wallpaperColor = wallpaperColor;
     savedObjs = new List<Saveable>();
 }
Exemple #16
0
 public Level()
 {
     Width = 640;
     Height = 360;
     playerX = 38;
     playerY = 58;
     savedObjs = new List<Saveable>();
     startTime = TimePeriod.Present;
     wallpaperColor = Color.White;
 }
    static void Main()
    {
        TimePeriod t = new TimePeriod();

                // Assigning the Hours property causes the 'set' accessor to be called.
                t.Hours = 24;

                // Evaluating the Hours property causes the 'get' accessor to be called.
                System.Console.WriteLine("Time in hours: " + t.Hours);
    }
 public void SetValues(ITimeSeries series_, TimePeriod initialPeriod_ = TimePeriod.None)
 {
   if (series_ == null) return;
   m_allValues = new[] {series_};
   lblTitle.Text = series_.Name;
   if (initialPeriod_ != TimePeriod.None)
     periodButtons1.SetPeriod(initialPeriod_,true);
   else
     apply();
 }
 private string GetDataFromHttp(TimePeriod time)
 {
     var login = new Login();
     var url = login.Url +
               ServiceConstants.MOBILE_SERVICES_RELATIVE_PATH +
               ServiceConstants.TOP_COMMITTERS_SERVICE_URL +
               "?days=" + (int)time +
               "&apiKey=" + login.Key;
     return http.DownloadString(url);
 }
Exemple #20
0
        public static List<Record> GetRecordsFromSession(Session session, TimePeriod period, bool filterRecords = true)
        {
            var res = new List<Record>();

            using (var mutex = Utils.TryLockFile(session.FileName))
            using (var stream = new FileStream(session.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var encoding = DetectEncoding(stream);

                if (filterRecords)
                {
                    while (true)
                    {
                        var startPos = stream.Position;
                        var line = ReadLine(stream, encoding);
                        if (line == null)
                            break;

                        var record = ParseLine(line);
                        if (!IsServiceMessage(record.Name))
                        {
                            stream.Position = startPos;
                            break;
                        }

                        record.SessionId = session.Id;
                        res.Add(record);
                    }

                    SkipOutdatedRecords(stream, encoding, period.StartTime);
                }

                using (var reader = new StreamReader(stream, encoding, true))
                {
                    while (true)
                    {
                        var line = reader.ReadLine();
                        if (line == null)
                            break;

                        var record = ParseLine(line);

                        if (filterRecords && record.Time > period.EndTime)
                            break;
                        if (filterRecords && record.Time < period.StartTime)
                            continue;

                        record.SessionId = session.Id;
                        res.Add(record);
                    }
                }
            }

            return res;
        }
Exemple #21
0
        public PeriodMetric(string name, string jsAggregator, string filter, TimePeriod period)
        {
            _name = name;
            _filter = filter;
            _period = period;

            var javascriptErrorMessageContext = string.Format("{0} ({1})", _name, "Metric Aggregator");

            _context = new JavascriptContext(jsAggregator, javascriptErrorMessageContext);

            Initialize();
        }
 public void LoadTopCommiters(TimePeriod time, Action<IEnumerable<Committer>> callback)
 {
     switch (time)
     {
         case TimePeriod.PastDay:
             callback(PastDayData);
             break;
         default:
             callback(DefaultData);
             break;
     }
 }
Exemple #23
0
    /* Handle whatever logic this object needs to do when changing eras. */
    public override void HandleChangeEra(TimePeriod eraChangingTo)
    {
        base.HandleChangeEra(eraChangingTo);

        /* Switch eras I'm in if player takes me through a portal. */
        if (this.transform.parent) {
            currentEraExistingIn = eraChangingTo;
        }

        /* If player is going to the future... */
        if (eraChangingTo == TimePeriod.FUTURE) {

            /* And I'm in the past... */
            if (currentEraExistingIn == TimePeriod.PAST) {
                //Debug.Log("1");
                /* Deactivate Power. */
                activePlatform.SetActive(false);
                //activePlatform.GetComponent<BouncyPlatform>().enabled = false;
                inactivePlatform.SetActive(true);
            }

            /* And I'm in the future... */
            else {
                //Debug.Log("2");
                /* Currently Deactivated */
                activePlatform.SetActive(true);
                //activePlatform.GetComponent<BouncyPlatform>().enabled = false;
                inactivePlatform.SetActive(false);
            }

        }
        /* Else if player is going to the past.. */
        else {

            /* And I'm in the past... */
            if (currentEraExistingIn == TimePeriod.PAST) {
                //Debug.Log("3");
                /* Activate Power */
                activePlatform.SetActive(true);
                //activePlatform.GetComponent<BouncyPlatform>().enabled = true;
                inactivePlatform.SetActive(false);
            }
            /* And I'm in the future... */
            else {
                //Debug.Log("4");
                /* Currently Deactivated */
                activePlatform.SetActive(false);
                //activePlatform.GetComponent<BouncyPlatform>().enabled = false;
                inactivePlatform.SetActive(false);
            }

        }
    }
        public static Statistics GetStatistics(IList<PlayTime> playTimes, IList<Program> programs, TimePeriod timePeriod)
        {
            var helper = new DateTimeHelper();
            List<PlayTime> times;
            switch (timePeriod)
            {
                case TimePeriod.Day:
                    times = playTimes.Where(x => helper.IsToday(x.Timestamp)).ToList();
                    break;
                case TimePeriod.Week:
                    times = playTimes.Where(x => helper.IsCurrentWeek(x.Timestamp)).ToList();
                    break;
                case TimePeriod.Month:
                    times = playTimes.Where(x => helper.IsCurrentMonth(x.Timestamp)).ToList();
                    break;
                case TimePeriod.Year:
                    times = playTimes.Where(x => helper.IsCurrentYear(x.Timestamp)).ToList();
                    break;
                case TimePeriod.Ever:
                    times = playTimes.ToList();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(timePeriod), timePeriod, null);
            }

            var statistic = new Statistics
            {
                TimePeriod = timePeriod,
                TimePlayed = TimeSpan.FromMilliseconds(times.Select(x => x.Duration.TotalMilliseconds).Sum())
            };

            var games = new List<GameStatistic>();
            foreach (var gameId in times.Select(x => x.Program).Distinct())
            {
                var game = programs.FirstOrDefault(x => x.Guid == gameId);
                if (game == null)
                    continue;

                games.Add(new GameStatistic
                {
                    Name = game.Name,
                    Icon = game.Icon,
                    Guid = game.Guid,
                    ChartColor = GetColor(game),
                    TimePlayed =
                        TimeSpan.FromMilliseconds(
                            times.Where(x => x.Program == game.Guid).Select(x => x.Duration.TotalMilliseconds).Sum())
                });
            }

            statistic.Games = games.OrderByDescending(x => x.TimePlayed).ToList();
            return statistic;
        }
        public static void ParseQuery(string period, string arg, out TimePeriod pd, out DateTime start, out DateTime end)
        {
            pd = TimePeriod.Auto;;

            if (period == "last") {
                int num = int.Parse (arg.Substring (0, arg.Length - 1));
                if (arg.EndsWith ("d")) {
                    end = DateTime.Now;
                    start = end.AddDays (-num);
                }
                else if (arg.EndsWith ("w")) {
                    end = DateTime.Now;
                    start = end.AddDays (-num*7);
                }
                else if (arg.EndsWith ("m")) {
                    end = DateTime.Now;
                    start = end.AddMonths (-num);
                }
                else if (arg.EndsWith ("y")) {
                    end = DateTime.Now;
                    start = end.AddYears (-num);
                }
                else
                    throw new Exception ("Invalid period specified");
            }
            else if (period == "period") {
                string[] range = arg.Split ('.');
                start = DateTime.Parse (range[0]);
                end = DateTime.Parse (range[1]);
            }
            else if (period == "month") {
                string[] m = arg.Split ('-');
                start = new DateTime (int.Parse (m[1]), int.Parse (m[0]), 1);
                end = start.AddMonths (1);
            }
            else if (period == "year") {
                start = new DateTime (int.Parse (arg), 1, 1);
                end = start.AddYears (1);
            }
            else
                throw new Exception ("Invalid period specified");

            if (pd == TimePeriod.Auto) {
                int nd = (int)(end - start).TotalDays;
                if (nd <= 60)
                    pd = TimePeriod.Day;
                else if (nd <= 30*6)
                    pd = TimePeriod.Week;
                else
                    pd = TimePeriod.Month;
            }
        }
Exemple #26
0
        public static List<Record> GetRecordsFromPath(string dataPath, TimePeriod period)
        {
            var res = new List<Record>();

            var sessions = GetSessionsFromPath(dataPath, period);

            foreach (var session in sessions)
            {
                var tmp = GetRecordsFromSession(session, period);
                res.AddRange(tmp);
            }

            return res;
        }
Exemple #27
0
        public BudgetItem(int id, Budget b, Tag t, string name, double amount, TimePeriod p, 
						  int timePeriodCount, DateTime scheduledDate, bool recur, int dayCount)
        {
            ID = id;
            Budget = b;
            Tag = t;
            Name = name;
            Amount = amount;
            TimePeriod = p;
            TimePeriodCount = timePeriodCount;
            ScheduledDate = scheduledDate;
            Recur = recur;
            DayCount = dayCount;
        }
 public TimePeriodValue(TimePeriod period, Number value)
 {
   base.\u002Ector();
   TimePeriodValue timePeriodValue = this;
   if (period == null)
   {
     string str = "Null 'period' argument.";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
   else
   {
     this.period = period;
     this.value = value;
   }
 }
 public static void ToneEx(this GpioApi gpio, int frequency, int duration)
 {
     gpio.DigitalWrite(PinState.Low);
     var waitTimeMicroS = (1000.0*1000.0/frequency);
     var sw = Stopwatch.StartNew();
     using (var tp = new TimePeriod((int)waitTimeMicroS))
     {
         while (sw.ElapsedMilliseconds < duration)
         {
             gpio.DigitalWrite(PinState.High);
             TimePeriod.Sleep((int)(waitTimeMicroS/1000.0));
             gpio.DigitalWrite(PinState.Low);
             TimePeriod.Sleep((int)(waitTimeMicroS/1000.0));
         }
     }
     sw.Stop();
 }
Exemple #30
0
 public Task(string description, TimePeriod duration)
 {
   base.\u002Ector();
   Task task = this;
   if (description == null)
   {
     string str = "Null 'description' argument.";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
   else
   {
     this.description = description;
     this.duration = duration;
     this.percentComplete = (Double) null;
     this.subtasks = (List) new ArrayList();
   }
 }
Exemple #31
0
 public TimePeriodDateTimeCheck(TimePeriod timePeriod)
 {
     this._timePeriod = timePeriod;
 }
Exemple #32
0
 public void Constructor_Invalid_Hours_Minutes(long a, byte b)
 {
     TimePeriod t = new TimePeriod(a, b);
 }
Exemple #33
0
 public DownloadStats GetProjectDownloadStats(int projectId, TimePeriod period, DateTime startDate, DateTime endDate)
 {
     return(GetDownloadStats(period, startDate, endDate, ", Release E", "R.ReleaseId = E.Id AND E.ProjectId={0}", projectId));
 }
Exemple #34
0
        public void ToString_Valid_Format(long a, string expected)
        {
            TimePeriod t = new TimePeriod(a, TimeUnit.Second);

            Assert.AreEqual(expected, t.ToString());
        }
Exemple #35
0
 public void TimePeriod_Substract_ArgumentException(long a, long b)
 {
     TimePeriod t1     = new TimePeriod(a);
     TimePeriod t2     = new TimePeriod(b);
     TimePeriod result = t1 - t2;
 }
Exemple #36
0
        /***************************************************************************
         *  Parses the class time periods out of the "Day/Time" table column.
         *
         *  We know which days are selected because their li tag will have the
         *  "meet hidden-xs" class.
         *
         *  Note: Would break this class into smaller, testable, pieces
         *        in a production situation and more defensive coding against
         *        html anomolies.
         ****************************************************************************/
        private List <TimePeriod> ParseTimePeriods(HtmlNode node)
        {
            List <TimePeriod> result = new List <TimePeriod>();

            string startTime = string.Empty;
            string endTime   = string.Empty;
            bool   isTBD     = false;
            bool   isUnknown = false;

            string time = string.Empty;

            if (node.InnerHtml.ToUpper() == "TBD")
            {
                time  = node.InnerHtml.ToUpper();
                isTBD = true;
            }
            else
            {
                time = node.InnerHtml.Substring(node.InnerHtml.IndexOf("</ul>") + 5).Trim(); // In this format 8:30 AM  - 9:20 AM or possibly TBD
            }

            TimeSpan tStart = new TimeSpan();
            TimeSpan tEnd   = new TimeSpan();

            string notes        = time;
            double?totalMinutes = null;

            if (time.Contains("-") && time != "-")
            {
                startTime = time.Substring(0, time.IndexOf("-")).Trim();
                endTime   = time.Substring(time.IndexOf("-") + 1).Trim();

                DateTime dateTime = DateTime.ParseExact(startTime,
                                                        "h:mm tt", CultureInfo.InvariantCulture);
                tStart = dateTime.TimeOfDay;

                if (endTime.Contains("<"))
                {
                    endTime = endTime.Substring(0, endTime.IndexOf("<")).Trim();
                }

                dateTime = DateTime.ParseExact(endTime, "h:mm tt", CultureInfo.InvariantCulture);

                tEnd = dateTime.TimeOfDay;

                totalMinutes = tEnd.Subtract(tStart).TotalMinutes;
            }
            else
            {
                isTBD     = (time.ToUpper() == "TBD");
                isUnknown = (time.ToUpper() != "TBD");
            }

            var days = from day in node.Descendants("li")
                       where day.Attributes["class"].Value == "meet hidden-xs"
                       select day;

            if (days.Count() > 0)
            {
                foreach (var day in days)
                {
                    string    dayName = day.Descendants("abbr").ElementAt(0).Attributes["title"].Value.Replace(" - meet", ""); // Returns the day name in readable format
                    DayOfWeek dow     = ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), dayName, true));

                    TimePeriod timePeriod = new TimePeriod()
                    {
                        Day          = dow,
                        EndTime      = tEnd,
                        IsTBD        = isTBD,
                        IsUnknown    = isUnknown,
                        Notes        = notes,
                        StartTime    = tStart,
                        TotalMinutes = totalMinutes
                    };

                    result.Add(timePeriod);
                }
            }
            else
            {
                TimePeriod timePeriod = new TimePeriod()
                {
                    Day       = null,
                    EndTime   = null,
                    IsTBD     = isTBD,
                    IsUnknown = isUnknown,
                    Notes     = notes,
                    StartTime = null
                };

                result.Add(timePeriod);
            }

            return(result);
        }
Exemple #37
0
        public void Constructor_Valid_Seconds_TimeUnit(long a, TimeUnit timeUnit, long expected)
        {
            TimePeriod t = new TimePeriod(a, timeUnit);

            Assert.AreEqual(expected, t.Seconds);
        }
Exemple #38
0
 public DownloadStats GetTotalDownloadStats(TimePeriod period, DateTime startDate, DateTime endDate)
 {
     return(GetDownloadStats(period, startDate, endDate, "", "1=1", null));
 }
Exemple #39
0
 public bool RuleCheckTimePeriod(TimePeriod timePeriod, object[] timePeriods)
 {
     //Check timePeriod 时间是否重复, 连续
     return(true);
 }
Exemple #40
0
 /// <summary>
 /// ** nunit
 /// </summary>
 /// <param name="timePeriod"></param>
 public void DeleteTimePeriod(TimePeriod timePeriod)
 {
     this._helper.DeleteDomainObject(timePeriod, new ICheck[] { new TimePeriodDeleteCheck(new TimePeriod[] { timePeriod }, this.DataProvider) });
 }
 public Guid CreateCompetition(string name, TimePeriod timePeriod) => _competitionRepository.Create(name, timePeriod);
 public override IEnumerable <Instructor> GetInstructors(TimePeriod timePeriod, Course course)
 {
     return(base.GetInstructors(timePeriod, course)
            .Where(instructor => instructor.CourseInstructors.Any(ci => ci.CourceId == course.Id)));
 }
Exemple #43
0
        private Domain.TS.TS GetNewTS(string runningCard, string partItemCode, string partRunningCard, string userCode)
        {
            SystemSettingFacade systemSettingFacade = new SystemSettingFacade(this.DataProvider);
            ShiftModelFacade    shiftModelFacade    = new ShiftModelFacade(this.DataProvider);
            ModelFacade         modelFacade         = new ModelFacade(this.DataProvider);
            TSFacade            tsFacade            = new TSFacade(this.DataProvider);
            DataCollectFacade   dataCollectFacade   = new DataCollectFacade(this.DataProvider);

            string sourceRCard = dataCollectFacade.GetSourceCard(runningCard.Trim().ToUpper(), string.Empty);

            DBDateTime       dbDateTime     = FormatHelper.GetNowDBDateTime(this.DataProvider);
            SimulationReport lastSimulation = dataCollectFacade.GetLastSimulationReport(sourceRCard);

            if (lastSimulation == null)
            {
                return(null);
            }

            Domain.TS.TS newTS = tsFacade.CreateNewTS();

            newTS.TSId                  = Guid.NewGuid().ToString();
            newTS.RunningCard           = partRunningCard;
            newTS.RunningCardSequence   = dataCollectFacade.GetMaxRCardSequenceFromTS(partRunningCard) + 100;
            newTS.TranslateCard         = partRunningCard;
            newTS.TranslateCardSequence = newTS.RunningCardSequence;
            newTS.SourceCard            = partRunningCard;
            newTS.SourceCardSequence    = newTS.RunningCardSequence;
            newTS.CardType              = CardType.CardType_Part;
            newTS.ReplacedRunningCard   = " ";

            newTS.ItemCode = partItemCode;
            Model model = (Model)modelFacade.GetModelByItemCode(partItemCode);

            if (model == null)
            {
                Parameter parameter = (Parameter)systemSettingFacade.GetParameter("PING", "DEFAULT_MODEL_CODE");
                if (parameter != null)
                {
                    newTS.ModelCode = parameter.ParameterAlias.Trim().ToUpper();
                }
            }
            else
            {
                newTS.ModelCode = model.ModelCode;
            }

            newTS.MOCode               = lastSimulation.MOCode;
            newTS.FromRouteCode        = lastSimulation.RouteCode;
            newTS.FromOPCode           = lastSimulation.OPCode;
            newTS.FromResourceCode     = lastSimulation.ResourceCode;
            newTS.FromSegmentCode      = lastSimulation.SegmentCode;
            newTS.FromStepSequenceCode = lastSimulation.StepSequenceCode;
            newTS.FromShiftTypeCode    = lastSimulation.ShiftTypeCode;
            newTS.MOSeq = lastSimulation.MOSeq;

            TimePeriod tp = (TimePeriod)shiftModelFacade.GetTimePeriod(newTS.FromShiftTypeCode, dbDateTime.DBTime);

            if (tp != null)
            {
                newTS.FromTimePeriodCode = tp.TimePeriodCode;
                newTS.FromShiftCode      = tp.ShiftCode;
                newTS.FromShiftDay       = shiftModelFacade.GetShiftDay(tp, dbDateTime.DateTime);
            }

            newTS.FromUser = userCode;
            newTS.FromDate = dbDateTime.DBDate;
            newTS.FormTime = dbDateTime.DBTime;

            newTS.MaintainUser = userCode;
            newTS.MaintainDate = dbDateTime.DBDate;
            newTS.MaintainTime = dbDateTime.DBTime;

            newTS.TSTimes           = tsFacade.GetMaxTSTimes(partRunningCard) + 1;
            newTS.FromInputType     = TSSource.TSSource_TS;
            newTS.TSStatus          = TSStatus.TSStatus_New;
            newTS.TransactionStatus = TransactionStatus.TransactionStatus_NO;

            return(newTS);
        }
Exemple #44
0
 public TimePeriodDateTimeCheck(TimePeriod timePeriod, IDomainDataProvider domainDataProvider)
 {
     this._domainDataProvider = domainDataProvider;
     this._timePeriod         = timePeriod;
 }
Exemple #45
0
        public void Constructor_Valid_Miliseconds(long a, long expected)
        {
            TimePeriod t = new TimePeriod(a);

            Assert.AreEqual(expected, t.Miliseconds);
        }
Exemple #46
0
        /// <summary>
        /// 1.sequence must greater than exsited ones
        /// 2.start datetime must greater than the last timeperiod which sequence
        ///	  equals to the this sequence - 1
        ///	3.this datetime must connected to the end date time of last one.
        ///	  eg.last one is 11:59:59,the start of the this one must be 12:00:00
        /// </summary>
        /// <returns></returns>
        bool BenQGuru.eMES.Web.Helper.ICheck.Check()
        {
            DBDateTime currentDateTime = FormatHelper.GetNowDBDateTime(this.DataProvider);

            #region TimePeriod本身的时间检查
            TimePeriod currTimePeriod = new TimePeriod();

            currTimePeriod.TimePeriodSequence  = this._timePeriod.TimePeriodSequence;
            currTimePeriod.TimePeriodBeginTime = this._timePeriod.TimePeriodBeginTime;
            currTimePeriod.TimePeriodEndTime   = this._timePeriod.TimePeriodEndTime;
            currTimePeriod.IsOverDate          = this._timePeriod.IsOverDate;

            this.adjustTimePeriodTime(currTimePeriod);

            // 起始时间应小于结束时间
            if (currTimePeriod.TimePeriodBeginTime >= currTimePeriod.TimePeriodEndTime)
            {
                ExceptionManager.Raise(this.GetType(), "$Error_TimePeriod_BeginTime_Greater_Than_EndTime");
                return(false);
            }
            #endregion

            #region 取出同一Shift下的所有TimePeriod,并按Sequence排序
            object obj = new ShiftModelFacade(this.DataProvider).GetShift(this._timePeriod.ShiftCode);

            if (obj == null)
            {
                ExceptionManager.Raise(this.GetType(), "$Error_TimePeriod_Shift_Not_Exist");
                return(false);
            }

            int shiftBeginTime = ((Shift)obj).ShiftBeginTime;
            int shiftEndTime   = ((Shift)obj).ShiftEndTime;

            if (((Shift)obj).IsOverDate == FormatHelper.TRUE_STRING)
            {
                if (shiftEndTime < shiftBeginTime)
                {
                    shiftEndTime = shiftEndTime + 240000;
                }
                else
                {
                    shiftBeginTime = shiftBeginTime + 240000;
                    shiftEndTime   = shiftEndTime + 240000;
                }
            }

            //从数据库中取出同一Shift下,当前TimePeriod之前的所有TimePeriod
            object[] prevTimePeriods = this.DataProvider.CustomQuery(
                typeof(TimePeriod),
                new SQLCondition(string.Format("select {0} from tbltp where shiftcode= '{1}' and tpseq <= {2} and tpcode <> '{3}' order by tpseq",
                                               DomainObjectUtility.GetDomainObjectFieldsString(typeof(TimePeriod)),
                                               this._timePeriod.ShiftCode,
                                               this._timePeriod.TimePeriodSequence,
                                               this._timePeriod.TimePeriodCode)));

            //从数据库中取出同一Shift下,当前TimePeriod之后的所有TimePeriod
            object[] nextTimePeriods = this.DataProvider.CustomQuery(
                typeof(TimePeriod),
                new SQLCondition(string.Format("select {0} from tbltp where shiftcode= '{1}' and tpseq >= {2} and tpcode <> '{3}' order by tpseq",
                                               DomainObjectUtility.GetDomainObjectFieldsString(typeof(TimePeriod)),
                                               this._timePeriod.ShiftCode,
                                               this._timePeriod.TimePeriodSequence,
                                               this._timePeriod.TimePeriodCode)));
            #endregion

            #region 将跨日期后的TimePeriod的时间加24小时
            if (prevTimePeriods != null)
            {
                foreach (TimePeriod timePeriod in prevTimePeriods)
                {
                    this.adjustTimePeriodTime(timePeriod);
                }
            }

            if (nextTimePeriods != null)
            {
                foreach (TimePeriod timePeriod in nextTimePeriods)
                {
                    this.adjustTimePeriodTime(timePeriod);
                }
            }
            #endregion

            #region 时间交叉判断
            // 当前TimePeriod是第一个
            if (prevTimePeriods == null || prevTimePeriods.Length == 0)
            {
                // TimePeriod起始时间不能小于Shift的起始时间
                if (currTimePeriod.TimePeriodBeginTime != shiftBeginTime)
                {
                    ExceptionManager.Raise(this.GetType(), "$Error_First_TimePeriod_Should_Be_Shift_BeginTime");
                    return(false);
                }
            }
            else
            {
                //DateTime temp = FormatHelper.ToDateTime(currentDateTime.DBDate, ((TimePeriod)prevTimePeriods[prevTimePeriods.Length - 1]).TimePeriodEndTime);
                //int tempEndTime = FormatHelper.TOTimeInt(temp.AddSeconds(1));
                int tempEndTime = FormatHelper.TimeAddSeconds(((TimePeriod)prevTimePeriods[prevTimePeriods.Length - 1]).TimePeriodEndTime, 1);


                // TimePeriod的起始时间必须与上一个TimePeriod的结束时间连续
                if (tempEndTime != currTimePeriod.TimePeriodBeginTime)
                {
                    ExceptionManager.Raise(this.GetType(), "$Error_TimePeriod_Time_Should_Be_Continuous");
                    return(false);
                }
            }

            if (nextTimePeriods == null || nextTimePeriods.Length == 0)
            {
                // TimePeriod的结束时间不能大于Shift的结束时间
                if (currTimePeriod.TimePeriodEndTime > shiftEndTime)
                {
                    ExceptionManager.Raise(this.GetType(), "$Error_TimePeriod_EndTime_Greater_Than_Shift_EndTime");
                    return(false);
                }
            }
            else
            {
                //DateTime temp = FormatHelper.ToDateTime(currentDateTime.DBDate, currTimePeriod.TimePeriodEndTime);
                //int tempEndTime = FormatHelper.TOTimeInt(temp.AddSeconds(1));
                int tempEndTime = FormatHelper.TimeAddSeconds(currTimePeriod.TimePeriodEndTime, 1);

                // TimePeriod的结束时间必须与下一个TimePeriod的起始时间连续
                if (tempEndTime != ((TimePeriod)nextTimePeriods[0]).TimePeriodBeginTime)
                {
                    ExceptionManager.Raise(this.GetType(), "$Error_TimePeriod_Time_Should_Be_Continuous");
                    return(false);
                }
            }
            #endregion

            return(true);
        }
Exemple #47
0
        public void Constructor_Valid_Hours_Minutes_Seconds(long a, byte b, byte c, long expected)
        {
            TimePeriod t = new TimePeriod(a, b, c);

            Assert.AreEqual(expected, t.Seconds);
        }
Exemple #48
0
 public async Task <List <Reposit> > GetRepos(string language, TimePeriod since) =>
 new JsonDeserializer().Deserialize <List <Reposit> >
     (await new DownloadManager().DownloadNewsFeedDataAsync
         (ApiManager.Instance.TrendingReposEndpoint(language, since)));
Exemple #49
0
 public void Constructor_Negative_Seconds_ArgumentOutOfRangeException(long a)
 {
     TimePeriod t = new TimePeriod(a);
 }
Exemple #50
0
        public async Task <Repository <Candle> > GetCandleRepositoryAsync(string exchangeName, Instrument instrument, TimePeriod period)
        {
            var repo = new Repository <Candle>(_logger);

            var tableName = ExchangeUtils.GetCandleDataKey(exchangeName, instrument, period);

            if (_availableTables.All(x => x != tableName))
            {
                throw new IndexOutOfRangeException();
            }

            await repo.CreateTable(GetConnectionString(), ExchangeUtils.GetCandleDataKey(exchangeName, instrument, period));

            return(repo);
        }
Exemple #51
0
 public void Constructor_Invalid_String_ArgumentException(string a)
 {
     TimePeriod t = new TimePeriod(a);
 }
Exemple #52
0
 public void InitTimePeriod()
 {
     _timePeriod = new TimePeriod(new TimeSpan(12, 0, 0));
 }
Exemple #53
0
 public void Constructor_Invalid_Hours_Minutes_Seconds(long a, byte b, byte c)
 {
     TimePeriod t = new TimePeriod(a, b, c);
 }
 public void Visit(TimePeriod period)
 {
     Console.WriteLine("Visit period {0}", period);
 }
Exemple #55
0
            public TimerScheduleSpec Compute(
                MatchedEventConvertor convertor,
                MatchedEventMap beginState,
                ExprEvaluatorContext exprEvaluatorContext,
                TimeZoneInfo timeZone,
                TimeAbacus timeAbacus)
            {
                DateTimeEx optionalDate = null;
                long? optionalRemainder = null;
                if (_dateNode != null)
                {
                    Object param = PatternExpressionUtil.Evaluate(
                        NAME_OBSERVER, beginState, _dateNode, convertor, exprEvaluatorContext);
                    if (param is string)
                    {
                        optionalDate = TimerScheduleISO8601Parser.ParseDate((string) param);
                    }
                    else if (param.IsLong() || param.IsInt())
                    {
                        long msec = param.AsLong();
                        optionalDate = DateTimeEx.GetInstance(timeZone);
                        timeAbacus.CalendarSet(msec, optionalDate);
                        //optionalDate = new DateTimeEx(msec.AsDateTimeOffset(timeZone), timeZone);
                        optionalRemainder = timeAbacus.CalendarSet(msec, optionalDate);
                    }
                    else if (param is DateTimeOffset || param is DateTime)
                    {
                        optionalDate = new DateTimeEx(param.AsDateTimeOffset(timeZone), timeZone);
                    }
                    else if (param is DateTimeEx)
                    {
                        optionalDate = (DateTimeEx) param;
                    }
                    else if (param == null)
                    {
                        throw new EPException(
                            "Null date-time value returned from " +
                            ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(_dateNode));
                    }
                    else
                    {
                        throw new EPException("Unrecognized date-time value " + param.GetType());
                    }
                }

                TimePeriod optionalTimePeriod = null;
                if (_periodNode != null)
                {
                    object param = PatternExpressionUtil.EvaluateTimePeriod(
                        NAME_OBSERVER, beginState, _periodNode, convertor, exprEvaluatorContext);
                    optionalTimePeriod = (TimePeriod) param;
                }

                long? optionalRepeatCount = null;
                if (_repetitionsNode != null)
                {
                    object param = PatternExpressionUtil.Evaluate(
                        NAME_OBSERVER, beginState, _repetitionsNode, convertor, exprEvaluatorContext);
                    if (param != null)
                    {
                        optionalRepeatCount = param.AsLong();
                    }
                }

                if (optionalDate == null && optionalTimePeriod == null)
                {
                    throw new EPException("Required date or time period are both null for " + NAME_OBSERVER);
                }

                return new TimerScheduleSpec(optionalDate, optionalRemainder, optionalRepeatCount, optionalTimePeriod);
            }
Exemple #56
0
        public void ExtendingTimePeriod_WhenExtendingWithNegativeTime_ThenExceptionIsThrown()
        {
            var timePeriod = new TimePeriod(TimeSpan.FromHours(14), TimeSpan.FromHours(15));

            Should.Throw <ArgumentException>(() => timePeriod.ExtendWith(TimeSpan.FromHours(-3)));
        }
        public static void ApiDemo(ILiquidCrystal lc)
        {
            ApiDemoDisplay(lc, 0, 0, " -- Api Demo --");

            // Display text
            ApiDemoDisplay(lc, 0, 0, "Display text on line 0 and 1");
            ApiDemoDisplay(lc, 0, 0, DateTime.Now.ToString("d"), waitTime: 0);
            ApiDemoDisplay(lc, 0, 1, DateTime.Now.ToString("T"), clear: false);
            if (lc.NumLines > 2)
            {
                ApiDemoDisplay(lc, 0, 2, DateTime.Now.ToString("dddd"), clear: false);
            }
            if (lc.NumLines > 3)
            {
                ApiDemoDisplay(lc, 0, 3, CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month), clear: false);
            }

            // Turn  display on / off
            ApiDemoDisplay(lc, 0, 0, "About to turn the display off", waitTime: 2000);
            lc.NoDisplay();
            TimePeriod.Sleep(1000);
            lc.Display();
            ApiDemoDisplay(lc, 0, 0, "Display turned on");

            // Flash Screen
            ApiDemoDisplay(lc, 0, 0, "About to flash the screen ...", waitTime: 2000);
            ApiDemoDisplay(lc, 0, 0, "Flashing the screen ...", waitTime: 0);
            lc.Flash(10);
            TimePeriod.Sleep(1000);

            // Cursor Blink Demo
            ApiDemoDisplay(lc, 0, 0, "Cursor blink mode on");
            lc.Blink();
            TimePeriod.Sleep(1000 * 4);
            ApiDemoDisplay(lc, 0, 0, "Cursor blink mode off");
            lc.NoBlink();

            // Cursor Demo
            ApiDemoDisplay(lc, 0, 0, "Display Cursor");
            lc.Cursor();
            TimePeriod.Sleep(1000);
            for (var i = 0; i < 15; i++)
            {
                lc.SetCursor(i, 0); TimePeriod.Sleep(300);
            }
            for (var i = 15; i >= 0; i--)
            {
                lc.SetCursor(i, 0); TimePeriod.Sleep(300);
            }
            TimePeriod.Sleep(1000 * 1);
            lc.NoCursor();
            ApiDemoDisplay(lc, 0, 0, "Cursor off");

            // Autoscroll demo
            ApiDemoDisplay(lc, 0, 0, "Autoscroll Demo", waitTime: 2000);
            NusbioRocks(lc);

            // Progress Bar Demo
            ApiDemoDisplay(lc, 0, 0, "Progress Bar Demo");
            ProgressBarDemo(lc);

            ApiDemoDisplay(lc, 0, 0, "-- Demo Done --");
        }
Exemple #58
0
        public static async Task <OrderHistoryResponse> QueryOrderHistoryAsync(CurrencyType type, TimePeriod period)
        {
            var param = new Dictionary <string, object>()
            {
                { "currency_pair", type.ToCurrencyPair() },
                { "time", period.ToPeriodString() }
            };

            var response = await KorbitCall.GetAsync <OrderHistoryResponse>("v1/transactions", param);

            return(response);
        }
        /// <inheritdoc />
        public Task <StationDisease> GetLast(string stationId, DataGroup dataGroup, int numberOfEvents, TimePeriod timePeriod, IEnumerable <string> diseasesFilter = null)
        {
            var time = $"{numberOfEvents}{timePeriod.GetDescription()}";

            var requestUri = $"/data/{stationId}/{dataGroup.GetDescription()}/last/{time}";

            var body = new
            {
                diseases = diseasesFilter
            };

            return(PostAsync <StationDisease>(requestUri, body));
        }
Exemple #60
0
 public DownloadStats GetReleaseDownloadStats(int releaseId, TimePeriod period, DateTime startDate, DateTime endDate)
 {
     return(GetDownloadStats(period, startDate, endDate, "", "R.ReleaseId={0}", releaseId));
 }