/// <summary>
        /// Adds a log to the <see cref="Occurrences"/> at the top of the list.
        /// </summary>
        /// <param name="log">The log to add to the occurrences.</param>
        /// <param name="maxLogs">The maximum number of logs to store in this structured log. If exceeded, the oldest log will be removed from this structured log.</param>
        public void AddLog(Log log, int maxLogs = 20)
        {
            if (FirstOccurrence == default)
            {
                FirstOccurrence = DateTimeOffset.UtcNow;
            }

            Occurrences.Insert(0, log);
            LastOccurrence = DateTimeOffset.UtcNow;
            OccurrenceCount++;
            Level = log.Level;

            if (string.IsNullOrEmpty(MessageTemplate))
            {
                MessageTemplate = log.Template ?? log.Message ?? string.Empty;
            }

            Function   = log.Function;
            File       = log.File;
            LineNumber = log.LineNumber;

            // We don't store an infinite number of logs inside Occurrences. Trim them down as configured.
            if (Occurrences.Count > maxLogs)
            {
                Occurrences.RemoveAt(Occurrences.Count - 1);
            }
        }
        /// <summary>
        /// Jumps to previous occurrence.
        /// </summary>
        internal void GotoPreviousOccurrence()
        {
            if (Occurrences == null)
            {
                return;
            }
            var count = Occurrences.Count();

            if (count == 0)
            {
                return;
            }

            if (mCurrentOccurrenceIndex >= 0)
            {
                --mCurrentOccurrenceIndex;
                if (mCurrentOccurrenceIndex < 0)
                {
                    mCurrentOccurrenceIndex = count - 1;
                }
            }
            else
            {
                mCurrentOccurrenceIndex = count - 1;
            }
            CurrentOccurrence = Occurrences.ElementAt(mCurrentOccurrenceIndex);
        }
Exemple #3
0
        private static IEnumerable <Words> SentenceAnagramsIter(Occurrences occurrences)
        {
            var occurrencesAsList = occurrences.ToList();

            if (!occurrencesAsList.Any())
            {
                yield return(new List <Word>());

                yield break;
            }

            foreach (var combination in Combinations(occurrencesAsList))
            {
                var combinationAsList    = combination.ToList();
                var remainingOccurrences = Subtract(occurrencesAsList, combinationAsList).ToList();
                foreach (var word in WordsForCombination(combinationAsList))
                {
                    foreach (var innerSentence in _sentenceAnagramsIterFunc(remainingOccurrences))
                    {
                        var sentence = new List <Word> {
                            word
                        };
                        sentence.AddRange(innerSentence);
                        yield return(sentence);
                    }
                }
            }
        }
        /// <summary>
        /// Jumps to next occurrence.
        /// </summary>
        internal void GotoNextOccurrence()
        {
            if (Occurrences == null)
            {
                return;
            }
            var count = Occurrences.Count();

            if (count == 0)
            {
                return;
            }
            if (mCurrentOccurrenceIndex >= 0)
            {
                ++mCurrentOccurrenceIndex;
                if (mCurrentOccurrenceIndex >= count)
                {
                    mCurrentOccurrenceIndex = 0;
                }
            }
            else
            {
                mCurrentOccurrenceIndex = 0;
            }
            CurrentOccurrence = Occurrences.ElementAt(mCurrentOccurrenceIndex);
        }
Exemple #5
0
        private static IEnumerable <Occurrences> Combinations(Occurrences occurrences)
        {
            var occurrencesAsList = occurrences.ToList();

            if (!occurrencesAsList.Any())
            {
                yield return(new List <Tuple <char, int> >());

                yield break;
            }

            var hd             = occurrencesAsList.First();
            var tl             = occurrencesAsList.Skip(1);
            var c              = hd.Item1;
            var n              = hd.Item2;
            var tlCombinations = Combinations(tl).ToList();

            foreach (var x in Enumerable.Range(0, n + 1))
            {
                var first = (x > 0) ? Tuple.Create(c, x) : null;
                foreach (var others in tlCombinations)
                {
                    var y = new List <Tuple <char, int> >();
                    if (first != null)
                    {
                        y.Add(first);
                    }
                    y.AddRange(others);
                    yield return(y);
                }
            }
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(TextApplicationScope.ParentContainerPropertyTag);

            // Inputs
            string inputText = objectContainer.Get <string>();

            // Inputs
            var wordsCol         = Words.Get(context);
            var occurrencesText  = Occurrences.Get(context);
            var occurrenceNumber = OccurrenceNumber.Get(context);
            var displayLog       = DisplayLog;

            //Convert Collection to Array
            string[] words = Utils.ConvertCollectionToArray(wordsCol);

            ///////////////////////////
            // Add execution logic HERE
            string OuputString = Utils.RemoveWordsFromText(inputText, words, occurrencesText, occurrenceNumber, displayLog);

            ///////////////////////////

            // Outputs
            return((ctx) =>
            {
                AdjustText.Set(ctx, OuputString);
            });
        }
Exemple #7
0
        void IStatCruncher.TryEnqueueMessage(string message)
        {
            int numberOfOccurrences = MessageParser.NumberOfOccurences(message, StringOfInterest);

            for (int i = 0; i < numberOfOccurrences; i++)
            {
                Occurrences.Enqueue(DateTime.Now);
            }
        }
Exemple #8
0
        /// <summary>
        /// Add an occurrence
        /// </summary>
        /// <param name="occurrence"></param>
        public void AddOccurrence(Occurrence occurrence)
        {
            if (IsSetupFinalised)
            {
                throw new InvalidOperationException("Cannot add occurrences after game setup is finalised");
            }

            Occurrences.Add(occurrence.Name, occurrence);
        }
Exemple #9
0
        private void GetOccurrences(ProdactObject selectedItem)
        {
            Occurrences.Clear();
            var Structures = AppService.StaticStoredObjs.ObjStructures.ToList().Where(e => e.LinkToObj.ProdactObj == selectedItem);

            foreach (var str in Structures)
            {
                Occurrences.Add(str.ProdactObject);
            }
        }
Exemple #10
0
        public override int GetHashCode()
        {
            unchecked {
                int hash = 17;
                if (Status != default(ScheduleStatus))
                {
                    hash = hash * 23 + Status.GetHashCode();
                }
                if (Every != default(int))
                {
                    hash = hash * 23 + Every.GetHashCode();
                }
                if (Period != default(SchedulePeriod))
                {
                    hash = hash * 23 + Period.GetHashCode();
                }
                if (On != default(ScheduleOn))
                {
                    hash = hash * 23 + On.GetHashCode();
                }
                if (InWords != default(String))
                {
                    hash = hash * 23 + InWords.GetHashCode();
                }
                if (StartDate != default(DateTime))
                {
                    hash = hash * 23 + StartDate.GetHashCode();
                }
                if (EndDate != default(DateTime))
                {
                    hash = hash * 23 + EndDate.GetHashCode();
                }
                if (Charge != default(ChargeScheduling))
                {
                    hash = hash * 23 + Charge.GetHashCode();
                }
                if (Transfer != default(TransferScheduling))
                {
                    hash = hash * 23 + Transfer.GetHashCode();
                }
                if (Occurrences != default(ScopedList <Occurrence>))
                {
                    hash = hash * 23 + Occurrences.GetHashCode();
                }
                if (NextOccurrences != default(ScopedList <Occurrence>))
                {
                    hash = hash * 23 + NextOccurrences.GetHashCode();
                }

                return(hash);
            }
        }
Exemple #11
0
        void RefreshStatistics()
        {
            DateTime frontOfQueue = DateTime.MinValue;

            if (Occurrences.TryPeek(out frontOfQueue))
            {
                if (DateTime.Now.Subtract(frontOfQueue).TotalSeconds > 60)
                {
                    Occurrences.TryDequeue(out frontOfQueue);
                    RefreshStatistics();
                }
            }
        }
Exemple #12
0
    private static double Calculate_odds(int trials, int max_agree, int runs, Occurrences o)
    {
        int    i    = trials;
        double odds = 0.0;

        while ((i >= max_agree))
        {
            double odds_i = o.occurrences[i] / (double)runs;
            odds += odds_i;
            i--;
        }
        return(1 - odds);
    }
Exemple #13
0
    //returns -1 if not enough trials exist to reach desired confidence
    //otherwise, returns minimum number of trials such that agreement is with specified confidence
    public static int RequiredForAgreement(int choices, int trials, double confidence, int iterations)
    {
        // array to track max result of each test
        Occurrences o = new Occurrences(trials + 1);

        // Spin up a bunch of runs.
        for (int i = 0; i < iterations; i++)
        {
            Iteration(choices, trials, o);
        }

        // Calculate and return minimum number of trials
        return(Calculate_min_agreement(trials, confidence, iterations, o));
    }
Exemple #14
0
    public static double ConfidenceOfOutcome(int choices, int trials, int max_agree, int iterations)
    {
        // array to track max result of each test
        Occurrences o = new Occurrences(trials + 1);

        // Spin up a bunch of runs.
        for (int i = 0; i < iterations; i++)
        {
            Iteration(choices, trials, o);
        }

        // Calculate and return odds
        return(Calculate_odds(trials, max_agree, iterations, o));
    }
Exemple #15
0
        public override string GetStepParameters()
        {
            var parameters = new List <string>();

            parameters.Add(RecurrenceType.ToStepValue());
            parameters.Add(DayComponent != null ? DayComponent.ToStepValue() : "$");
            parameters.Add(WeekdayComponent != null ? WeekdayComponent.ToStepValue() : "$");
            parameters.Add(MonthComponent != null ? MonthComponent.ToStepValue() : "$");
            parameters.Add(Position != null ? Position.ToStepValue() : "$");
            parameters.Add(Interval != null ? Interval.ToStepValue() : "$");
            parameters.Add(Occurrences != null ? Occurrences.ToStepValue() : "$");
            parameters.Add(TimePeriods != null ? TimePeriods.ToStepValue() : "$");

            return(string.Join(", ", parameters.ToArray()));
        }
Exemple #16
0
        /// <summary>
        /// Evaluates <see cref="Alarm"/>s for the given recurring component, <paramref name="rc"/>.
        /// This evaluation is based on the evaluation period for the <see cref="RecurringComponent"/>.
        /// </summary>
        /// <param name="rc">The </param>
        /// <returns></returns>
        virtual public List <AlarmOccurrence> Evaluate(RecurringComponent rc)
        {
            Occurrences.Clear();

            // If the trigger is relative, it can recur right along with
            // the recurring items, otherwise, it happens once and
            // only once (at a precise time).
            if (Trigger.IsRelative)
            {
                Duration d = null;
                foreach (Period p in rc.Periods)
                {
                    Date_Time dt = p.StartTime;
                    if (Trigger.Related == Trigger.TriggerRelation.END)
                    {
                        if (p.EndTime != null)
                        {
                            dt = p.EndTime;
                            if (d == null)
                            {
                                d = p.Duration;
                            }
                        }
                        // Use the "last-found" duration as a reference point
                        else if (d != null)
                        {
                            dt = p.StartTime + d;
                        }
                        else
                        {
                            throw new ArgumentException("Alarm trigger is relative to the END of the occurrence; however, the occurence has no discernible end.");
                        }
                    }

                    Occurrences.Add(new AlarmOccurrence(this, dt + Trigger.Duration, rc));
                }
            }
            else
            {
                Occurrences.Add(new AlarmOccurrence(this, Trigger.DateTime.Copy(), rc));
            }

            // If a REPEAT and DURATION value were specified,
            // then handle those repetitions here.
            AddRepeatedItems();

            return(Occurrences);
        }
        /// <summary>
        /// Jumps to last occurrence.
        /// </summary>
        internal void GotoLastOccurrence()
        {
            if (Occurrences == null)
            {
                return;
            }
            var count = Occurrences.Count();

            if (count == 0)
            {
                return;
            }

            mCurrentOccurrenceIndex = count - 1;

            CurrentOccurrence = Occurrences.ElementAt(mCurrentOccurrenceIndex);
        }
Exemple #18
0
 public void CountSpen()
 {
     foreach (int lineIndex in Lines)
     {
         int    occurrencesInLine = 0;
         Word[] words             = Data.Code[lineIndex];
         foreach (Word word in words)
         {
             if (word.Text == Name.Text)
             {
                 occurrencesInLine++;
                 Spen++;
             }
         }
         Occurrences.Add(occurrencesInLine);
     }
     Spen--;
 }
Exemple #19
0
        /// <summary>
        /// Handles the repetitions that occur from the <c>REPEAT</c> and
        /// <c>DURATION</c> properties.  Each recurrence of the alarm will
        /// have its own set of generated repetitions.
        /// </summary>
        virtual protected void AddRepeatedItems()
        {
            if (Repeat != null)
            {
                int len = Occurrences.Count;
                for (int i = 0; i < len; i++)
                {
                    AlarmOccurrence ao        = Occurrences[i];
                    Date_Time       AlarmTime = ao.DateTime.Copy();

                    for (int j = 0; j < Repeat; j++)
                    {
                        AlarmTime += Duration;
                        Occurrences.Add(new AlarmOccurrence(this, AlarmTime.Copy(), ao.Component));
                    }
                }
            }
        }
        /// <summary>
        /// 获取当前SolidEdge活动文档
        /// <para>
        /// 注:如果传入ASM文档名称,则寻找当前活动文档下的Occurrence为当前活动文档
        /// </para>
        /// </summary>
        /// <param name="ASMDocumentName">ASM文档名称</param>
        /// <returns></returns>
        private SolidEdgeDocument GetActiveObjectDocument(string ASMDocumentName = null)
        {
            if (SolidEdgeApplication.Instance == null)
            {
                throw new NullReferenceException("SolidEdgew程序对象获取失败!");
            }

            object objDoc = SolidEdgeApplication.Instance.ActiveDocument;

            if (objDoc == null)
            {
                throw new NullReferenceException("SolidEdge程序当前活动文档不存在!");
            }

            //查找Occurrence
            if (!string.IsNullOrEmpty(ASMDocumentName))
            {
                AssemblyDocument ObjAsm = (AssemblyDocument)objDoc;

                if (ObjAsm.Name.Equals(ASMDocumentName, StringComparison.OrdinalIgnoreCase))
                {
                    return((SolidEdgeDocument)objDoc);
                }

                //工作站环境
                Occurrences occurrences = ObjAsm.Occurrences;
                var         tor         = occurrences.GetEnumerator();

                while (tor.MoveNext())
                {
                    Occurrence occurrence = (Occurrence)tor.Current;
                    if (ASMDocumentName.Equals(occurrence.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        return((SolidEdgeDocument)occurrence.OccurrenceDocument);
                    }
                }
                throw new NullReferenceException($"SolidEdge程序当前活动文档{ASMDocumentName}不存在!");
            }
            //直接返回
            else
            {
                return((SolidEdgeDocument)objDoc);
            }
        }
Exemple #21
0
        private static Occurrences Subtract(Occurrences x, Occurrences y)
        {
            var xm = x.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
            var ym = y.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
            var zm = new Dictionary <char, int>();

            foreach (var kvp in xm)
            {
                var c  = kvp.Key;
                var nx = kvp.Value;
                int ny;
                zm[c] = (ym.TryGetValue(c, out ny)) ? nx - ny : nx;
            }

            return(zm
                   .Where(kvp => kvp.Value > 0)
                   .Select(kvp => Tuple.Create(kvp.Key, kvp.Value))
                   .OrderBy(tuple => tuple.Item1));
        }
Exemple #22
0
    private static void Iteration(int choices, int trials, Occurrences o)
    {
        System.Random r      = new System.Random();
        int[]         choice = new int[trials];
        // {[0..choices-1], [0..choices-1], ...} // # = trials

        // make a choice for every trial
        for (int j = 0; j < trials; j++)
        {
            choice[j] = Math.Abs(r.Next(int.MaxValue)) % choices;
        }

        // Make a histogram, adding up occurrences of each choice.
        int[] counter = new int[choices];
        for (int k = 0; k < choices; k++)
        {
            counter[k] = 0;
        }
        for (int z = 0; z < trials; z++)
        {
            counter[choice[z]] += 1;
        }

        // Find the biggest choice
        int max = 0;

        for (int k = 0; k < choices; k++)
        {
            if (counter[k] > max)
            {
                max = counter[k];
            }
        }

        // Return the number of votes that the biggest choice got
        if (max > trials)
        {
            UnityEngine.Debug.LogError("Max votes is > #trials, which is impossible.");
        }
        o.occurrences[max]++;
    }
Exemple #23
0
        public void SetRoomCap(int locationId, int occurrenceId, int roomCap, bool includeLeaders)
        {
            /// save room cap
            var l = new Arena.Organization.Location(locationId);

            l.MaxPeople = roomCap;
            l.IncludeLeadersForMaxPeople = includeLeaders;
            l.Save("ArenaOz");

            /// Check if we need to close/open the locations occurrences
            ///
            List <Occurrence> locationOccurences = new List <Occurrence>();

            locationOccurences.AddRange(Occurrences.Where(x => x.LocationId == locationId));

            foreach (Occurrence o in locationOccurences)
            {
                var occurrence = new Arena.Core.Occurrence(o.Id);
                var occtype    = occurrence.OccurrenceType;

                if (occtype.UseRoomRatios)
                {
                    if (occtype.MinLeaders != 0 || occtype.PeoplePerLeader != 0)
                    {
                        occurrence.PerformRoomRatioActions(Arena.Enums.CheckInAction.CheckIn, "ArenaOz");
                    }
                    else
                    {
                        if (OccurrenceShouldBeClosed(roomCap, includeLeaders, occurrence.GetCurrentCount(Enums.OccurrenceAttendanceType.Person), occurrence.GetCurrentCount(Enums.OccurrenceAttendanceType.Leader)))
                        {
                            occurrence.OccurrenceClosed = true;
                        }
                        else
                        {
                            occurrence.OccurrenceClosed = false;
                        }
                        occurrence.Save("ArenaOz", false);
                    }
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// Adds a log to the <see cref="Occurrences"/> at the top of the list.
        /// </summary>
        /// <param name="log">The log to add to the occurrences.</param>
        public void AddLog(Log log)
        {
            if (FirstOccurrence == default(DateTimeOffset))
            {
                FirstOccurrence = DateTimeOffset.UtcNow;
            }

            Occurrences.Insert(0, log);
            LastOccurrence = DateTimeOffset.UtcNow;
            OccurrenceCount++;
            Level           = log.Level;
            MessageTemplate = log.Template ?? log.Message ?? string.Empty;
            Function        = log.Function;
            File            = log.File;
            LineNumber      = log.LineNumber;

            // We don't store an infinite number of logs inside Occurrences. Trim them down as configured.
            if (Occurrences.Count > RavenStructuredLoggerProvider.MaxStructuredLogOccurrences)
            {
                Occurrences.RemoveAt(Occurrences.Count - 1);
            }
        }
Exemple #25
0
        public List <Error> Consult(int ambiente, int campoOrdenacao, int campoBuscado, string textoBuscado)
        {
            // Campo buscado
            // 1 - Level
            // 2 - Descrição
            // 3 - Origem

            // Ambiente
            // 1 - Produção
            // 2 - Homologação
            // 3 - Desenvolvimento

            List <Error> errorsSearchList = new List <Error>();
            List <Error> errorsList       = new List <Error>();

            if (textoBuscado != "" && campoBuscado != 0)
            {
                if (campoBuscado == 1)
                {
                    errorsSearchList = _context.Errors.Where(x => x.LevelId == _levelService.ConsultLevelByName(textoBuscado).LevelId).ToList();
                }
                else if (campoBuscado == 2)
                {
                    errorsSearchList = _context.Errors.Where(x => x.Description.Contains(textoBuscado)).ToList();
                }
                else if (campoBuscado == 3)
                {
                    errorsSearchList = _context.ErrorOccurrences.Where(x => x.Origin == textoBuscado).Select(x => x.Error).ToList();
                }

                errorsSearchList = errorsSearchList.Where(x => x.EnvironmentId == ambiente || ambiente <= 0).ToList();
            }
            else
            {
                errorsSearchList = _context.Errors.Where(x => x.EnvironmentId == ambiente || ambiente <= 0).ToList();
            }

            // Campo ordenação
            // 1 - Level
            // 2 - Frequência

            if (campoOrdenacao == 1)
            {
                errorsSearchList = errorsSearchList.OrderBy(x => x.LevelId).ToList();
            }
            else if (campoOrdenacao == 2)
            {
                List <Occurrences> listOcc = new List <Occurrences>();

                foreach (var item in errorsSearchList)
                {
                    var occ = new Occurrences();

                    occ.ErrorId  = item.ErrorId;
                    occ.Quantity = _context.ErrorOccurrences.Where(x => x.ErrorId == item.ErrorId).Count();
                    listOcc.Add(occ);
                }

                listOcc = listOcc.OrderByDescending(x => x.Quantity).ToList();

                foreach (var item in listOcc)
                {
                    errorsList.Add(_context.Errors.Where(x => x.ErrorId == item.ErrorId).FirstOrDefault());
                }

                errorsSearchList = errorsList;
            }

            return(errorsSearchList);
        }
Exemple #26
0
 /// <summary>
 /// Registers occurrence of a code smell at a given position. Note: both lines and columns are counted from 1
 /// </summary>
 /// <param name="LineStart">Line at which the occurrence started</param>
 /// <param name="ColStart">Column at which the occurrence started</param>
 /// <param name="LineEnd">Line at which the occurrence ended</param>
 /// <param name="ColEnd">Column at which the occurrence ended</param>
 public void RegisterOccurrence(int LineStart, int ColStart, int LineEnd, int ColEnd)
 {
     Occurrences.Add(new Occurrence {
         LineStart = LineStart, ColStart = ColStart, LineEnd = LineEnd, ColEnd = ColEnd
     });
 }
Exemple #27
0
 /// <summary>
 /// Returns all occurrences registered during the detector's lifecycle
 /// </summary>
 /// <returns></returns>
 public Occurrence[] GetOccurrences()
 {
     return(Occurrences.ToArray());
 }
Exemple #28
0
    private static int Calculate_min_agreement(int trials, double confidence, int iterations, Occurrences o)
    {
        // Determine the number of trials in order for the odds
        // to drop below alpha (i.e., 1 - confidence).
        // This is done by subtracting the area under the histogram for each trial
        // from 1.0 until the answer is less than alpha.
        int    i     = 1;
        double odds  = 1.0;
        double alpha = 1.0 - confidence;

        while ((i <= trials) && (odds > alpha))
        {
            double odds_i = o.occurrences[i] / (double)iterations;
            odds -= odds_i;
            i++;
        }

        // If we found an answer, then return # of trials
        if ((i <= trials) && (odds <= alpha))
        {
            UnityEngine.Debug.Log("DEBUG: MONTECARLO: " + i + " identical answers required for " + trials + " HITs.");
            return(i);
            // Otherwise
        }
        else
        {
            // Error condition: not enough trials to achieve the desired confidence.
            return(-1);
        }
    }
 public override string ToString()
 {
     return($"[{Occurrences.Count()}]: {Text}");
 }
        public string CreateCsvRow(char separator)
        {
            var parts = new[] { OrderNumber.ToString(), Character.ToString(), Occurrences.ToString(), CodeWord };

            return(string.Join(separator, parts));
        }