public static Dictionary <string, Tuple <double, double, double> > start() { Console.WriteLine(Test.bayesianFormula(Tuple.Create(31.2298850574713, 567.819679755498), 0)); var stopwatch = new Stopwatch(); stopwatch.Start(); //------------ HashSet <string> classifierGrams = new HashSet <string>(); List <Document> documents = new List <Document>(); Dictionary <string, Tuple <double, double, double> > valuesForEachClass = new Dictionary <string, Tuple <double, double, double> >(); prepareDocuments(documents, classifierGrams); Tuple <List <Document>, List <Document> > datas = Likelihood.splitTrainingTestData(documents); Console.WriteLine(classifierGrams.Count); var meanAndVariances = Likelihood.training(datas.Item1, classifierGrams); valuesForEachClass = Test.test(datas.Item2, meanAndVariances, classifierGrams); //------------ stopwatch.Stop(); var elapsed_time = stopwatch.ElapsedMilliseconds; Console.WriteLine(elapsed_time); return(valuesForEachClass); }
public override void Setup(IEvolutionState state, IParameter paramBase) { base.Setup(state, paramBase); IParameter def = DefaultBase; _generateMax = state.Parameters.GetBoolean(paramBase.Push(P_GEN_MAX), def.Push(P_GEN_MAX), false); if (!Likelihood.Equals(1.0)) { state.Output.Warning( "UniquePipeline given a likelihood other than 1.0. This is nonsensical and will be ignored.", paramBase.Push(P_LIKELIHOOD), def.Push(P_LIKELIHOOD)); } // How often do we retry if we find a duplicate? NumDuplicateRetries = state.Parameters.GetInt( paramBase.Push(P_RETRIES), def.Push(P_RETRIES), 0); if (NumDuplicateRetries < 0) { state.Output.Fatal( "The number of retries for duplicates must be an integer >= 0.\n", paramBase.Push(P_RETRIES), def.Push(P_RETRIES)); } }
private static float ConvertLikelyhood(Likelihood likelihood) { switch (likelihood) { case Likelihood.Unknown: return(0); case Likelihood.VeryLikely: return(1); case Likelihood.Likely: return(.80F); case Likelihood.Possible: return(.60F); case Likelihood.Unlikely: return(.40F); case Likelihood.VeryUnlikely: return(.20F); default: return(0); } }
public void bTest() { int[] o = { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }; HMM_QPN model = new HMM_QPN("G:/аспирантура/Programs/10.12.12/HSMPQApplication/m_1.txt"); Likelihood target = new Likelihood(o, model); int i = 0; // TODO: инициализация подходящего значения int d = 10; // TODO: инициализация подходящего значения int t = 8; // TODO: инициализация подходящего значения double expected = 0.03774874F; // TODO: инициализация подходящего значения double actual; //actual = target.b(i, d, t); //Assert.AreEqual(expected, actual); i = 0; // TODO: инициализация подходящего значения d = 10; // TODO: инициализация подходящего значения t = 13; // TODO: инициализация подходящего значения expected = 0.2097152F; // TODO: инициализация подходящего значения actual = 0; //actual = target.b(i, d, t); //Assert.AreEqual(expected, actual); // Assert.Inconclusive("Проверьте правильность этого метода теста."); int[] o1 = { 0, 0 }; Likelihood target1 = new Likelihood(o1, model); i = 0; // TODO: инициализация подходящего значения d = 10; // TODO: инициализация подходящего значения t = 2; // TODO: инициализация подходящего значения expected = 0.2097152F; // TODO: инициализация подходящего значения actual = 0; actual = target1.b(i, d, t); Assert.AreEqual(expected, actual); Assert.Inconclusive("Проверьте правильность этого метода теста."); }
public void LikelihoodConstructorTest() { int[] o = null; // TODO: инициализация подходящего значения HMM_QPN model = null; // TODO: инициализация подходящего значения Likelihood target = new Likelihood(o, model); Assert.Inconclusive("TODO: реализуйте код для проверки целевого объекта"); }
public ActionResult RemoveLikelihood(ADDB context, int id) { Likelihood likelihoodToRemove = context.Likelihoods.Find(id); context.Likelihoods.Remove(likelihoodToRemove); return(RedirectToAction("Index")); }
public void CreateLikelihood(ADDB context, Likelihood likelihood) { //deal with duplicate entries var duplicates = context.Likelihoods.Where(m => m.AnimalId == likelihood.AnimalId && m.DiseaseId == likelihood.DiseaseId && m.SignId == likelihood.SignId); if (duplicates.Count() > 0) { return; // do not add anything if we already have a likelihood for the same animal, disease and sign } context.Likelihoods.Add(likelihood); context.SaveChanges(); }
public override void Setup(IEvolutionState state, IParameter paramBase) { base.Setup(state, paramBase); IParameter def = DefaultBase; if (!Likelihood.Equals(1.0)) { state.Output.Warning("ReproductionPipeline given a likelihood other than 1.0. This is nonsensical and will be ignored.", paramBase.Push(P_LIKELIHOOD), def.Push(P_LIKELIHOOD)); } }
public List <double> compute() { List <double> result = new List <double>(); for (int i = step; i <= maxSize; i += step) { Likelihood ls = new Likelihood(SequenceUtils <int> .getSubsequence(sequence.Sequence, 0, i), model.Model); double value = ls.FullProbability(i); result.Add(value); } return(result); }
public void FullProbabilityTest() { int[] o = null; // TODO: инициализация подходящего значения HMM_QPN model = null; // TODO: инициализация подходящего значения Likelihood target = new Likelihood(o, model); // TODO: инициализация подходящего значения int t = 0; // TODO: инициализация подходящего значения double expected = 0F; // TODO: инициализация подходящего значения double actual; actual = target.FullProbability(t); Assert.AreEqual(expected, actual); Assert.Inconclusive("Проверьте правильность этого метода теста."); }
public override void Setup(IEvolutionState state, IParameter paramBase) { base.Setup(state, paramBase); IParameter def = DefaultBase; _numTimes = state.Parameters.GetInt(paramBase.Push(P_NUMTIMES), def.Push(P_NUMTIMES), 1); if (_numTimes < 1) { state.Output.Fatal("CheckingPipeline must have a num-times value >= 1.", paramBase.Push(P_NUMTIMES), def.Push(P_NUMTIMES)); } if (!Likelihood.Equals(1.0)) { state.Output.Warning( "CheckingPipeline given a likelihood other than 1.0. This is nonsensical and will be ignored.", paramBase.Push(P_LIKELIHOOD), def.Push(P_LIKELIHOOD)); } }
public static Windows.UI.Color GetColor(this Likelihood likelihood) { switch (likelihood) { case Likelihood.VERY_LIKELY: return(Colors.Crimson); case Likelihood.LIKELY: return(Colors.Red); case Likelihood.POSSIBLE: return(Colors.LightCoral); case Likelihood.UNLIKELY: return(Colors.Green); case Likelihood.VERY_UNLIKELY: return(Colors.Lime); default: return(Colors.White); } }
public static InspectTemplate Create( string projectId, string templateId, string displayName, string description, Likelihood likelihood, int maxFindings, bool includeQuote) { var client = DlpServiceClient.Create(); var request = new CreateInspectTemplateRequest { ParentAsProjectName = new ProjectName(projectId), InspectTemplate = new InspectTemplate { DisplayName = displayName, Description = description, InspectConfig = new InspectConfig { MinLikelihood = likelihood, Limits = new InspectConfig.Types.FindingLimits { MaxFindingsPerRequest = maxFindings }, IncludeQuote = includeQuote }, }, TemplateId = templateId }; var response = client.CreateInspectTemplate(request); Console.WriteLine($"Successfully created template {response.Name}."); return(response); }
public static DlpJob InspectGCS( string projectId, Likelihood minLikelihood, int maxFindings, bool includeQuote, IEnumerable <InfoType> infoTypes, IEnumerable <CustomInfoType> customInfoTypes, string bucketName, string topicId, string subscriptionId) { var inspectJob = new InspectJobConfig { StorageConfig = new StorageConfig { CloudStorageOptions = new CloudStorageOptions { FileSet = new CloudStorageOptions.Types.FileSet { Url = $"gs://{bucketName}/*.txt" }, BytesLimitPerFile = 1073741824 }, }, InspectConfig = new InspectConfig { InfoTypes = { infoTypes }, CustomInfoTypes = { customInfoTypes }, ExcludeInfoTypes = false, IncludeQuote = includeQuote, Limits = new FindingLimits { MaxFindingsPerRequest = maxFindings }, MinLikelihood = minLikelihood }, Actions = { new Google.Cloud.Dlp.V2.Action { // Send results to Pub/Sub topic PubSub = new Google.Cloud.Dlp.V2.Action.Types.PublishToPubSub { Topic = topicId, } } } }; // Issue Create Dlp Job Request var client = DlpServiceClient.Create(); var request = new CreateDlpJobRequest { InspectJob = inspectJob, Parent = new LocationName(projectId, "global").ToString(), }; // We need created job name var dlpJob = client.CreateDlpJob(request); // Get a pub/sub subscription and listen for DLP results var fireEvent = new ManualResetEventSlim(); var subscriptionName = new SubscriptionName(projectId, subscriptionId); var subscriber = SubscriberClient.CreateAsync(subscriptionName).Result; subscriber.StartAsync( (pubSubMessage, cancellationToken) => { // Given a message that we receive on this subscription, we should either acknowledge or decline it if (pubSubMessage.Attributes["DlpJobName"] == dlpJob.Name) { fireEvent.Set(); return(Task.FromResult(SubscriberClient.Reply.Ack)); } return(Task.FromResult(SubscriberClient.Reply.Nack)); }); // We block here until receiving a signal from a separate thread that is waiting on a message indicating receiving a result of Dlp job if (fireEvent.Wait(TimeSpan.FromMinutes(1))) { // Stop the thread that is listening to messages as a result of StartAsync call earlier subscriber.StopAsync(CancellationToken.None).Wait(); // Now we can inspect full job results var job = client.GetDlpJob(new GetDlpJobRequest { DlpJobName = new DlpJobName(projectId, dlpJob.Name) }); // Inspect Job details Console.WriteLine($"Processed bytes: {job.InspectDetails.Result.ProcessedBytes}"); Console.WriteLine($"Total estimated bytes: {job.InspectDetails.Result.TotalEstimatedBytes}"); var stats = job.InspectDetails.Result.InfoTypeStats; Console.WriteLine("Found stats:"); foreach (var stat in stats) { Console.WriteLine($"{stat.InfoType.Name}"); } return(job); } throw new InvalidOperationException("The wait failed on timeout"); }
public static JobTrigger Create( string projectId, string bucketName, Likelihood minLikelihood, int maxFindings, bool autoPopulateTimespan, int scanPeriod, IEnumerable <InfoType> infoTypes, string triggerId, string displayName, string description) { var dlp = DlpServiceClient.Create(); var jobConfig = new InspectJobConfig { InspectConfig = new InspectConfig { MinLikelihood = minLikelihood, Limits = new FindingLimits { MaxFindingsPerRequest = maxFindings }, InfoTypes = { infoTypes } }, StorageConfig = new StorageConfig { CloudStorageOptions = new CloudStorageOptions { FileSet = new FileSet { Url = $"gs://{bucketName}/*" } }, TimespanConfig = new TimespanConfig { EnableAutoPopulationOfTimespanConfig = autoPopulateTimespan } } }; var jobTrigger = new JobTrigger { Triggers = { new Trigger { Schedule = new Schedule { RecurrencePeriodDuration = new Google.Protobuf.WellKnownTypes.Duration { Seconds = scanPeriod * 60 * 60 * 24 } } } }, InspectJob = jobConfig, Status = Status.Healthy, DisplayName = displayName, Description = description }; var response = dlp.CreateJobTrigger( new CreateJobTriggerRequest { ParentAsProjectName = new ProjectName(projectId), JobTrigger = jobTrigger, TriggerId = triggerId }); Console.WriteLine($"Successfully created trigger {response.Name}"); return(response); }
private void CountProbBtn_Click(object sender, EventArgs e) { HMM_QPN Model = new HMM_QPN(label1.Text); if (Model.IsCorrect() == 1) { int smbnubmer = 10; if (textBox2.Text != "") { try { smbnubmer = int.Parse(textBox2.Text); } catch (Exception) { } } ; int[] res = new int[smbnubmer + 1]; try { res = HMM_PSM.GetOutputSequence(label2.Text, smbnubmer); } catch (Exception) { MessageBox.Show("Желаемая длина последовательности превышает размер файла"); return; } panel3.Enabled = false; if (radioButton1.Checked) { //try //{ Likelihood lk = new Likelihood(res, Model); //label3.Text = lk.Probability(res.Length - 1).ToString(); label3.Text = lk.FullProbability(res.Length - 1).ToString(); //} //catch (Exception) // { MessageBox.Show("В процессе расчета возникла ошибка!"); }; panel3.Enabled = true; } else { if (radioButton2.Checked) { LikelihoodSimple lk = new LikelihoodSimple(res, Model); //label3.Text = lk.Probability(res.Length - 1).ToString(); label3.Text = lk.Probability(res.Length - 1).ToString(); panel3.Enabled = true; } else { if (tbSegmentNumber.Text != "") { int segment_size = 0; if (Int32.TryParse(tbSegmentNumber.Text, out segment_size)) { LikelihoodSplit ls = new LikelihoodSplit(segment_size); double [] result = ls.calculateSplitedLikelihood(Model, res); double total = 0; tbSplitResultDetails.Text = ""; for (int i = 0; i < result.Length; i++) { tbSplitResultDetails.Text += "P[O(" + i * segment_size + "," + ((i + 1) * segment_size) + ")] = " + result[i] + "\r\n"; total += result[i]; } label3.Text = (total / result.Length).ToString(); panel3.Enabled = true; } else { MessageBox.Show("Размер сегмента разбиения должен быть целым"); } } else { MessageBox.Show("Задайте размер сегмента разбиения"); } } } } else { MessageBox.Show("Модель задана некорректно"); } }
public static bool MeetsThreshold(this Likelihood input, Likelihood minThreshold) { return((int)input >= (int)minThreshold); }
public ActionResult InsertNewLikelihood(ADDB context, Likelihood likelihood) { CreateLikelihood(context, likelihood); return(RedirectToAction("Index")); }
public static object Inspect( string projectId, Likelihood minLikelihood, int maxFindings, bool includeQuote, IEnumerable <FieldId> identifyingFields, IEnumerable <InfoType> infoTypes, IEnumerable <CustomInfoType> customInfoTypes, string datasetId, string tableId) { var inspectJob = new InspectJobConfig { StorageConfig = new StorageConfig { BigQueryOptions = new BigQueryOptions { TableReference = new Google.Cloud.Dlp.V2.BigQueryTable { ProjectId = projectId, DatasetId = datasetId, TableId = tableId, }, IdentifyingFields = { identifyingFields } }, TimespanConfig = new StorageConfig.Types.TimespanConfig { StartTime = Timestamp.FromDateTime(System.DateTime.UtcNow.AddYears(-1)), EndTime = Timestamp.FromDateTime(System.DateTime.UtcNow) } }, InspectConfig = new InspectConfig { InfoTypes = { infoTypes }, CustomInfoTypes = { customInfoTypes }, Limits = new FindingLimits { MaxFindingsPerRequest = maxFindings }, ExcludeInfoTypes = false, IncludeQuote = includeQuote, MinLikelihood = minLikelihood }, Actions = { new Google.Cloud.Dlp.V2.Action { // Save results in BigQuery Table SaveFindings = new Google.Cloud.Dlp.V2.Action.Types.SaveFindings { OutputConfig = new OutputStorageConfig { Table = new Google.Cloud.Dlp.V2.BigQueryTable { ProjectId = projectId, DatasetId = datasetId, TableId = tableId } } }, } } }; // Issue Create Dlp Job Request var client = DlpServiceClient.Create(); var request = new CreateDlpJobRequest { InspectJob = inspectJob, ParentAsProjectName = new ProjectName(projectId), }; // We need created job name var dlpJob = client.CreateDlpJob(request); var jobName = dlpJob.Name; // Make sure the job finishes before inspecting the results. // Alternatively, we can inspect results opportunistically, but // for testing purposes, we want consistent outcome var finishedJob = EnsureJobFinishes(projectId, jobName); var bigQueryClient = BigQueryClient.Create(projectId); var table = bigQueryClient.GetTable(datasetId, tableId); // Return only first page of 10 rows Console.WriteLine("DLP v2 Results:"); var firstPage = table.ListRows(new ListRowsOptions { StartIndex = 0, PageSize = 10 }); foreach (var item in firstPage) { Console.WriteLine($"\t {item[""]}"); } return(finishedJob); }
private void saveDocument() { newRiskPlanModel.ProjectName = Project_Name_tbx.Text; List <Information> informations = new List <Information>(); Information information = new Information(); var DocumentID = Document_Information_dgv.Rows[0].Cells[1].Value.ToString(); var DocumentOwner = Document_Information_dgv.Rows[1].Cells[1].Value.ToString(); var IssueDate = Document_Information_dgv.Rows[2].Cells[1].Value.ToString(); var LastSavedDate = Document_Information_dgv.Rows[3].Cells[1].Value.ToString(); var FileName = Document_Information_dgv.Rows[4].Cells[1].Value.ToString(); information.DocumentID = DocumentID; information.DocumentOwner = DocumentOwner; information.IssueDate = IssueDate; information.LastSavedDate = LastSavedDate; information.FileName = FileName; newRiskPlanModel.Information = information; List <History> histories = new List <History>(); int Document_HistoryRowCount = Document_History_dgv.RowCount; for (int i = 0; i < Document_HistoryRowCount - 1; i++) { History history = new History(); var Version = Document_History_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var IsDate = Document_History_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var Changes = Document_History_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; history.Version = Version; history.IssueDate = IsDate; history.Changes = Changes; histories.Add(history); } newRiskPlanModel.Histories = histories; List <Approval> approvals = new List <Approval>(); int approvalCount = Document_Approvals_dgv.RowCount; for (int i = 0; i < Document_HistoryRowCount - 1; i++) { Approval approval = new Approval(); var Role = Document_Approvals_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var Name = Document_Approvals_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var Signature = Document_Approvals_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; var Date = Document_Approvals_dgv.Rows[i].Cells[3].Value?.ToString() ?? ""; approval.Name = Name; approval.Role = Role; approval.Signature = Signature; approval.Date = Date; approvals.Add(approval); } newRiskPlanModel.Approvals = approvals; newRiskPlanModel.Categories = Categories_tbx.Text; List <Risk> risks = new List <Risk>(); int riskCount = Risks_dgv.RowCount; for (int i = 0; i < riskCount - 1; i++) { Risk risk = new Risk(); var RiskCategory = Risks_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var RiskDescription = Risks_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var ID = Risks_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; risk.RiskCategory = RiskCategory; risk.RiskDescription = RiskDescription; risk.ID = ID; risks.Add(risk); } newRiskPlanModel.Risks = risks; List <Likelihood> likelihoods = new List <Likelihood>(); int LikelihoodrowCount = Likelihood_dgv.RowCount; for (int i = 0; i < LikelihoodrowCount - 1; i++) { Likelihood likelihood = new Likelihood(); var Title = Likelihood_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var Score = Likelihood_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var Description = Likelihood_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; likelihood.Title = Title; likelihood.Score = Score; likelihood.Description = Description; likelihoods.Add(likelihood); } newRiskPlanModel.Likelihoods = likelihoods; List <Impact> impacts = new List <Impact>(); int impactrowCount = Impact_dgv.RowCount; for (int i = 0; i < impactrowCount - 1; i++) { Impact impact = new Impact(); var Title = Impact_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var Score = Impact_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var Description = Impact_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; impact.Title = Title; impact.Score = Score; impact.Description = Description; impacts.Add(impact); } newRiskPlanModel.Impacts = impacts; List <Priority> priorities = new List <Priority>(); int PriorityrowCount = Priority_dgv.RowCount; for (int i = 0; i < PriorityrowCount - 1; i++) { Priority priority = new Priority(); var ID = Priority_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var LikelihoodScore = Priority_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var ImpactScore = Priority_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; var PriorityScore = Priority_dgv.Rows[i].Cells[3].Value?.ToString() ?? ""; var PriorityRating = Priority_dgv.Rows[i].Cells[4].Value?.ToString() ?? ""; priority.ID = ID; priority.LikelihoodScore = LikelihoodScore; priority.ImpactScore = ImpactScore; priority.PriorityScore = PriorityScore; priority.PriorityRating = PriorityRating; priorities.Add(priority); } newRiskPlanModel.Priorities = priorities; List <Schedule> schedules = new List <Schedule>(); int SchedulerowCount = Schedule_dgv.RowCount; for (int i = 0; i < SchedulerowCount - 1; i++) { Schedule schedule = new Schedule(); var Rating = Schedule_dgv.Rows[i].Cells[0].Value?.ToString() ?? ""; var ID = Schedule_dgv.Rows[i].Cells[1].Value?.ToString() ?? ""; var PrevalantiveActions = Schedule_dgv.Rows[i].Cells[2].Value?.ToString() ?? ""; var ActionResource1 = Schedule_dgv.Rows[i].Cells[3].Value?.ToString() ?? ""; var ActionDate1 = Schedule_dgv.Rows[i].Cells[4].Value?.ToString() ?? ""; var ContingentActions = Schedule_dgv.Rows[i].Cells[5].Value?.ToString() ?? ""; var ActionResource2 = Schedule_dgv.Rows[i].Cells[6].Value?.ToString() ?? ""; var ActionDate2 = Schedule_dgv.Rows[i].Cells[7].Value?.ToString() ?? ""; schedule.Rating = Rating; schedule.ID = ID; schedule.PrevalantiveActions = PrevalantiveActions; schedule.ActionResource1 = ActionResource1; schedule.ActionDate1 = ActionDate1; schedule.ContingentActions = ContingentActions; schedule.ActionResource2 = ActionResource2; schedule.ActionDate2 = ActionDate2; schedules.Add(schedule); } newRiskPlanModel.Schedules = schedules; newRiskPlanModel.Assumptions = Assumptions_tbx.Text; newRiskPlanModel.Constraints = Constraints_tbx.Text; newRiskPlanModel.Activities = Activities_tbx.Text; newRiskPlanModel.Roles = Roles_tbx.Text; newRiskPlanModel.Documents = Documents_tbx.Text; newRiskPlanModel.Appendix = Appendix_tbx.Text; List <VersionControl <RiskPlanModel> .DocumentModel> documentModels = versionControl.DocumentModels; //MessageBox.Show(JsonConvert.SerializeObject(newRiskPlanModel), "save", MessageBoxButtons.OK); if (!versionControl.isEqual(currentRiskPlanModel, newRiskPlanModel)) { VersionControl <RiskPlanModel> .DocumentModel documentModel = new VersionControl <RiskPlanModel> .DocumentModel(newRiskPlanModel, DateTime.Now, VersionControl <RiskPlanModel> .generateID()); documentModels.Add(documentModel); versionControl.DocumentModels = documentModels; string json = JsonConvert.SerializeObject(versionControl); currentRiskPlanModel = JsonConvert.DeserializeObject <RiskPlanModel>(JsonConvert.SerializeObject(newRiskPlanModel)); JsonHelper.saveDocument(json, Settings.Default.ProjectID, "RiskPlan"); MessageBox.Show("Risk plan saved successfully", "save", MessageBoxButtons.OK); } }