public ContentRepairSuggestion AlternateFix(string name, Func <IProgress <AsyncProgressEntry>, CancellationToken, Task <bool> > fix, bool affectsData = true,
                                             bool showProgressDialog = true)
 {
     Fixes.Add(new ContentRepairSuggestionFix(this, name, fix)
     {
         AffectsData        = affectsData,
         ShowProgressDialog = showProgressDialog
     });
     return(this);
 }
示例#2
0
        private NoxMemoryHack()
        {
            threads.Add(new Thread(new ThreadStart(RefreshThreadStart)));
            foreach (Thread thread in threads)
            {
                thread.Start();
            }

            //TODO: make this optional
            Fixes.ApplyFixes();
        }
示例#3
0
        /// <summary>
        ///     Show the tooltip with the TrayIcon
        /// </summary>
        public void SetIconText()
        {
            var tooltipInfo = _tooltipInfoFactory.Get(CurrentTooltipInfo);
            var text        = tooltipInfo.TextToDisplay();

            if (text == null)
            {
                return;
            }
            Fixes.SetNotifyIconText(_icon, $"{Application.ProductName}\n{text}");
        }
示例#4
0
 /*
  * Used for the breakable objects on the table - boosts is
  * in the format [hygeine, sanity, energy, foodness].
  *
  * isGlobal corresponds to these, and is whether the boost is applied to
  * the single player, or to all players.
  */
 public Task(string label, int length, List <int> boosts, List <bool> boostsGlobal, Fixes fixes)
 {
     this.label        = label;
     this.length       = length;
     this.progress     = 0;
     this.boosts       = boosts;
     this.boostsGlobal = boostsGlobal;
     this.isMilestone  = false;
     this.nextTasks    = null;
     this.special      = true;
     this.fixes        = fixes;
 }
示例#5
0
    public Player(int id)
    {
        this.id = id;

        this.hygeine  = 1000000;
        this.sanity   = 1000000;
        this.energy   = 1000000;
        this.foodness = 1000000;

        this.current = null;

        this.boosts       = null;
        this.boostsGlobal = null;

        this.justCompleted = null;
        this.fixes         = Fixes.None;
    }
示例#6
0
        /// <summary>
        ///     Show the tooltip with the TrayIcon
        /// </summary>
        public void ShowTooltipInfo()
        {
            if (IsBallontipVisible)
            {
                return;
            }

            var tooltipInfo = _tooltipInfoFactory.Get(CurrentTooltipInfo);
            var text        = tooltipInfo.TextToDisplay();

            if (text == null)
            {
                return;
            }
            Fixes.SetNotifyIconText(_icon, $"{Application.ProductName}\n{text}");

            //_icon.ShowBalloonTip(1000, $"{Application.ProductName}: {TooltipInfo.titleTooltip}", text, ToolTipIcon.Info)
        }
示例#7
0
        /// <inheritdoc/>
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            return(textControl =>
            {
                using (solution.GetComponent <DocumentTransactionManager>()
                       .CreateTransactionCookie(DefaultAction.Commit, "action name"))
                {
                    var services = solution.GetPsiServices();
                    services.Transactions.Execute(
                        "Code cleanup",
                        () => services.Locks.ExecuteWithWriteLock(() =>
                    {
                        ICSharpTypeAndNamespaceHolderDeclaration holder = _highlighting.TypeAndNamespaceHolder;

                        Fixes.FixOrder(holder, _highlighting.Config);
                        Fixes.FixSpacing(holder, _highlighting.Config);
                    }));
                }
            });
        }
示例#8
0
        public void TestAutoWeight()
        {
            // We take as dataset the two-dimensional projection of iris so
            // that it is not separable and remove half of predictors from
            // class 1.
            // We add one to the targets as a non-regression test: class_weight="auto"
            // used to work only when the labels where a range [0..K).
            var x = iris.Data.SubMatrix(0, iris.Data.RowCount, 0, 2);
            var y = iris.Target.Select(v => v + 1).ToArray();

            var indToDelete       = y.Indices(v => v > 2).Where((v, i) => i % 2 == 0).ToList();
            var unbalancedIndices = Enumerable.Range(0, y.Length).Where(v => !indToDelete.Contains(v)).ToList();

            int[] yInd;
            int[] classes = Fixes.Unique(y.ElementsAt(unbalancedIndices), out yInd);

            var classWeights = ClassWeightEstimator <int> .Auto.ComputeWeights(classes, yInd);

            Assert.AreEqual(2, classWeights.MaximumIndex());

            foreach (var clf in new IClassifier <int>[]
            {
                new Svc <int>(kernel: Kernel.Linear, classWeightEstimator:ClassWeightEstimator <int> .Auto),
                //svm.LinearSVC(random_state=0),
                new LogisticRegression <int>(classWeightEstimator : ClassWeightEstimator <int> .Auto)
            })
            {
                // check that score is better when class='auto' is set.
                clf.Fit(x.RowsAt(unbalancedIndices), y.ElementsAt(unbalancedIndices));
                var y_pred = clf.Predict(x);
                clf.Fit(x.RowsAt(unbalancedIndices), y.ElementsAt(unbalancedIndices));
                var yPredBalanced = clf.Predict(x);
                var a             = Learn.Metrics.Metrics.F1Score(y, y_pred);
                var b             = Learn.Metrics.Metrics.F1Score(y, yPredBalanced);
                Assert.IsTrue(a.Zip(b, Tuple.Create).All(t => t.Item1 <= t.Item2));
            }
        }
示例#9
0
        public SarifErrorListItem(Run run, Result result, string logFilePath, ProjectNameCache projectNameCache) : this()
        {
            IRule rule;

            run.TryGetRule(result.RuleId, result.RuleKey, out rule);
            Message           = result.GetMessageText(rule, concise: false);
            ShortMessage      = result.GetMessageText(rule, concise: true);
            FileName          = result.GetPrimaryTargetFile();
            ProjectName       = projectNameCache.GetName(FileName);
            Category          = result.GetCategory();
            Region            = result.GetPrimaryTargetRegion();
            Level             = result.Level;
            SuppressionStates = result.SuppressionStates;
            LogFilePath       = logFilePath;

            if (Region != null)
            {
                LineNumber   = Region.StartLine;
                ColumnNumber = Region.StartColumn;
            }

            Tool       = run.Tool.ToToolModel();
            Rule       = rule.ToRuleModel(result.RuleId);
            Invocation = run.Invocation.ToInvocationModel();

            if (string.IsNullOrWhiteSpace(run.Id))
            {
                WorkingDirectory = Path.Combine(Path.GetTempPath(), run.GetHashCode().ToString());
            }
            else
            {
                WorkingDirectory = Path.Combine(Path.GetTempPath(), run.Id);
            }

            if (result.Locations != null)
            {
                foreach (Location location in result.Locations)
                {
                    Locations.Add(location.ToAnnotatedCodeLocationModel());
                }
            }

            if (result.RelatedLocations != null)
            {
                foreach (AnnotatedCodeLocation annotatedCodeLocation in result.RelatedLocations)
                {
                    RelatedLocations.Add(annotatedCodeLocation.ToAnnotatedCodeLocationModel());
                }
            }

            if (result.CodeFlows != null)
            {
                foreach (CodeFlow codeFlow in result.CodeFlows)
                {
                    CallTrees.Add(codeFlow.ToCallTree());
                }

                CallTrees.Verbosity = 100;
                CallTrees.IntelligentExpand();
            }

            if (result.Stacks != null)
            {
                foreach (Stack stack in result.Stacks)
                {
                    Stacks.Add(stack.ToStackCollection());
                }
            }

            if (result.Fixes != null)
            {
                foreach (Fix fix in result.Fixes)
                {
                    Fixes.Add(fix.ToFixModel());
                }
            }
        }
示例#10
0
        public SarifErrorListItem(Run run, Result result, string logFilePath, ProjectNameCache projectNameCache) : this()
        {
            if (!SarifViewerPackage.IsUnitTesting)
            {
#pragma warning disable VSTHRD108 // Assert thread affinity unconditionally
                ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning restore VSTHRD108 // Assert thread affinity unconditionally
            }
            _runId = CodeAnalysisResultManager.Instance.CurrentRunId;
            ReportingDescriptor rule = result.GetRule(run);
            Tool         = run.Tool.ToToolModel();
            Rule         = rule.ToRuleModel(result.RuleId);
            Invocation   = run.Invocations?[0]?.ToInvocationModel();
            Message      = result.GetMessageText(rule, concise: false).Trim();
            ShortMessage = result.GetMessageText(rule, concise: true).Trim();
            if (!Message.EndsWith("."))
            {
                ShortMessage = ShortMessage.TrimEnd('.');
            }
            FileName    = result.GetPrimaryTargetFile(run);
            ProjectName = projectNameCache.GetName(FileName);
            Category    = result.GetCategory();
            Region      = result.GetPrimaryTargetRegion();
            Level       = result.Level != FailureLevel.Warning ? result.Level : Rule.FailureLevel;

            if (result.Suppressions?.Count > 0)
            {
                VSSuppressionState = VSSuppressionState.Suppressed;
            }

            LogFilePath = logFilePath;

            if (Region != null)
            {
                LineNumber   = Region.StartLine;
                ColumnNumber = Region.StartColumn;
            }

            Tool             = run.Tool.ToToolModel();
            Rule             = rule.ToRuleModel(result.RuleId);
            Invocation       = run.Invocations?[0]?.ToInvocationModel();
            WorkingDirectory = Path.Combine(Path.GetTempPath(), _runId.ToString());

            if (result.Locations?.Any() == true)
            {
                // Adding in reverse order will make them display in the correct order in the UI.
                for (int i = result.Locations.Count - 1; i >= 0; --i)
                {
                    Locations.Add(result.Locations[i].ToLocationModel(run));
                }
            }

            if (result.RelatedLocations?.Any() == true)
            {
                for (int i = result.RelatedLocations.Count - 1; i >= 0; --i)
                {
                    RelatedLocations.Add(result.RelatedLocations[i].ToLocationModel(run));
                }
            }

            if (result.CodeFlows != null)
            {
                foreach (CodeFlow codeFlow in result.CodeFlows)
                {
                    CallTree callTree = codeFlow.ToCallTree(run);
                    if (callTree != null)
                    {
                        CallTrees.Add(callTree);
                    }
                }

                CallTrees.Verbosity = 100;
                CallTrees.IntelligentExpand();
            }

            if (result.Stacks != null)
            {
                foreach (Stack stack in result.Stacks)
                {
                    Stacks.Add(stack.ToStackCollection());
                }
            }

            if (result.Fixes != null)
            {
                foreach (Fix fix in result.Fixes)
                {
                    Fixes.Add(fix.ToFixModel());
                }
            }
        }
示例#11
0
        public bool Equals(Result other)
        {
            if (other == null)
            {
                return(false);
            }

            if (RuleId != other.RuleId)
            {
                return(false);
            }

            if (Kind != other.Kind)
            {
                return(false);
            }

            if (Message != other.Message)
            {
                return(false);
            }

            if (!Object.Equals(FormattedRuleMessage, other.FormattedRuleMessage))
            {
                return(false);
            }

            if (!Object.ReferenceEquals(Locations, other.Locations))
            {
                if (Locations == null || other.Locations == null)
                {
                    return(false);
                }

                if (!Locations.SetEquals(other.Locations))
                {
                    return(false);
                }
            }

            if (CodeSnippet != other.CodeSnippet)
            {
                return(false);
            }

            if (ToolFingerprint != other.ToolFingerprint)
            {
                return(false);
            }

            if (!Object.ReferenceEquals(Stacks, other.Stacks))
            {
                if (Stacks == null || other.Stacks == null)
                {
                    return(false);
                }

                if (!Stacks.SetEquals(other.Stacks))
                {
                    return(false);
                }
            }

            if (!Object.ReferenceEquals(CodeFlows, other.CodeFlows))
            {
                if (CodeFlows == null || other.CodeFlows == null)
                {
                    return(false);
                }

                if (!CodeFlows.SetEquals(other.CodeFlows))
                {
                    return(false);
                }
            }

            if (!Object.ReferenceEquals(RelatedLocations, other.RelatedLocations))
            {
                if (RelatedLocations == null || other.RelatedLocations == null)
                {
                    return(false);
                }

                if (!RelatedLocations.SetEquals(other.RelatedLocations))
                {
                    return(false);
                }
            }

            if (IsSuppressedInSource != other.IsSuppressedInSource)
            {
                return(false);
            }

            if (!Object.ReferenceEquals(Fixes, other.Fixes))
            {
                if (Fixes == null || other.Fixes == null)
                {
                    return(false);
                }

                if (!Fixes.SetEquals(other.Fixes))
                {
                    return(false);
                }
            }

            if (!Object.ReferenceEquals(Properties, other.Properties))
            {
                if (Properties == null || other.Properties == null || Properties.Count != other.Properties.Count)
                {
                    return(false);
                }

                foreach (var value_0 in Properties)
                {
                    string value_1;
                    if (!other.Properties.TryGetValue(value_0.Key, out value_1))
                    {
                        return(false);
                    }

                    if (value_0.Value != value_1)
                    {
                        return(false);
                    }
                }
            }

            if (!Object.ReferenceEquals(Tags, other.Tags))
            {
                if (Tags == null || other.Tags == null)
                {
                    return(false);
                }

                if (!Tags.SetEquals(other.Tags))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#12
0
        public override string Execute(EventEntry evtlog)
        {
            string strAddress = evtlog.GetProcData <string>(address);

            if (string.IsNullOrEmpty(strAddress))
            {
                Log.Info("Fail2ban[" + Name
                         + "]: empty address attribute: " + address);

                return(goto_error);
            }

            IPAddress addr = null;

            try
            {
                addr = IPAddress.Parse(strAddress.Trim()).MapToIPv6();
            }
            catch (FormatException ex)
            {
                Log.Info("Fail2ban[" + Name
                         + "]: invalid address " + address
                         + "[" + strAddress + "]: " + ex.Message);

                return(goto_error);
            }

            // get fail2ban network address for given IP and prefix
            int prefix = ipv6_prefix;

            if (addr.IsIPv4MappedToIPv6)
            {
                prefix = ipv4_prefix;
                if (prefix <= 32)
                {
                    prefix += 96;
                }
            }
            if (prefix != 128)
            {
                addr = Utils.GetNetwork(addr, prefix);
            }

            // fix log event that came from future(?!), _we_ have correct time!
            long now     = DateTime.Now.Ticks;
            long logtime = evtlog.Created.Ticks;

            if (logtime > now)
            {
                // is clock skew too hight!? occasionally log warning
                if (logtime > now + 300 * TimeSpan.TicksPerSecond)
                {
                    if (clockskew + 60 * TimeSpan.TicksPerSecond < now)
                    {
                        clockskew = now;

                        Log.Warn("Fail2ban[" + Name + "]: logtime from future ("
                                 + ((logtime - now) / TimeSpan.TicksPerSecond) + " seconds) for "
                                 + evtlog.Input + "/" + evtlog.Input.SelectorName
                                 + " from " + evtlog.Machine);
                    }
                }

                logtime = now;
            }

            int failcnt = 0;

            bool[] tresholdCheck = new bool[tresholds.Count];

            lock (thisLock)
            {
                // update failed login fail2ban data
                IFail fail;
                if (!data.TryGetValue(addr, out fail))
                {
                    switch (history)
                    {
                    case HistoryType.ALL: fail = new FailAll(findtime * TimeSpan.TicksPerSecond); break;

                    case HistoryType.ONE: fail = new FailOne(findtime * TimeSpan.TicksPerSecond); break;

                    case HistoryType.FIXED: fail = new FailFixed(findtime * TimeSpan.TicksPerSecond, history_fixed_count, history_fixed_decay); break;

                    case HistoryType.RRD: fail = new FailRRD(findtime * TimeSpan.TicksPerSecond, history_rrd_count, history_rrd_repeat); break;
                    }

                    data[addr] = fail;
                }
                failcnt = fail.Add(logtime);

                for (int i = 0; i < tresholds.Count; i++)
                {
                    tresholdCheck[i] = Check(addr, tresholds[i], failcnt);
                }
            }

            // evaluate all defined tresholds
            for (int i = 0; i < tresholds.Count; i++)
            {
                if (!tresholdCheck[i])
                {
                    continue;
                }

                Treshold  treshold   = tresholds[i];
                int       tmpPrefix  = prefix;
                IPAddress tmpAddr    = addr;
                long      expiration = now + TimeSpan.FromSeconds(treshold.Bantime).Ticks;

                if (addr.IsIPv4MappedToIPv6)
                {
                    // workaround for buggy MapToIPv4 implementation
                    tmpAddr   = Fixes.MapToIPv4(addr);
                    tmpPrefix = prefix - 96;
                }

                Log.Info("Fail2ban[" + Name + "]: reached treshold "
                         + treshold.Name + " (" + treshold.MaxRetry + "&"
                         + failcnt + ") for " + tmpAddr + "/" + tmpPrefix);

                if (evtlog.HasProcData("Fail2ban.All"))
                {
                    string all = evtlog.GetProcData <string>("Fail2ban.All");
                    evtlog.SetProcData("Fail2ban.All", all + "," + Name);
                }
                else
                {
                    evtlog.SetProcData("Fail2ban.All", Name);
                }
                evtlog.SetProcData("Fail2ban.Last", Name);

                evtlog.SetProcData(Name + ".Address", tmpAddr);
                evtlog.SetProcData(Name + ".Prefix", tmpPrefix);
                evtlog.SetProcData(Name + ".FailCnt", failcnt);
                evtlog.SetProcData(Name + ".Bantime", treshold.Bantime);
                evtlog.SetProcData(Name + ".Expiration", expiration);
                evtlog.SetProcData(Name + ".Treshold", treshold.Name);

                // Add to "action" queue
                Produce(new EventEntry(evtlog), treshold.Action, EventQueue.Priority.High);
            }

            return(goto_next);
        }
示例#13
0
    public void Update(int tickSize)
    {
        this.sanity   -= tickSize;
        this.hygeine  -= tickSize * 4;
        this.energy   -= tickSize * 8;
        this.foodness -= tickSize * 16;

        if (hygeine < 0)
        {
            hygeine = 0;
        }
        if (energy < 0)
        {
            energy = 0;
        }
        if (foodness < 0)
        {
            foodness = 0;
        }
        if (sanity < 0)
        {
            sanity = 0;
        }

        if (hygeine > 1000000)
        {
            hygeine = 1000000;
        }
        if (energy > 1000000)
        {
            energy = 1000000;
        }
        if (foodness > 1000000)
        {
            foodness = 1000000;
        }
        if (sanity > 1000000)
        {
            sanity = 1000000;
        }

        if (this.current == null)
        {
            return;
        }

        // Player works slower based on their values.
        this.current.Update((int)(tickSize * PerformanceMultiplier()));
        if (!this.current.IsComplete())
        {
            return;
        }

        if (this.current.special)
        {
            this.boosts       = this.current.boosts;
            this.boostsGlobal = this.current.boostsGlobal;
            this.fixes        = this.current.fixes;
        }

        this.justCompleted = current;
        this.current       = null;

        // TODO: should we notify the players with some SFX or something?
    }
示例#14
0
 /// <summary>
 /// Fixes the order and spacing for the using blocks in a file or namespace declaration block.
 /// </summary>
 /// <param name="holder">The file or namespace declaration blocks to check.</param>
 /// <param name="configuration">The configuration defining the correct order
 /// and spacing.</param>
 private void CleanUsings(
     ICSharpTypeAndNamespaceHolderDeclaration holder, OrderUsingsConfiguration configuration)
 {
     Fixes.FixOrder(holder, configuration);
     Fixes.FixSpacing(holder, configuration);
 }