in CLIPS, I have to use conflict resolution strategies, can someone help me add the strategies? - conflict

;;; ***************************
;;; *DEF TEMPLATES AND DEF FACTS *
;;; ***************************
(deftemplate UI-state
(slot id (default-dynamic (gensym*)))
(slot display)
(slot relation-asserted (default none))
(slot response (default none))
(multislot valid-answers)
(slot state (default middle)))
(deftemplate state-list
(slot current)
(multislot sequence))
(deffacts startup
(state-list))
;;;****************
;;;* STARTUP RULE *
;;;****************
(defrule system-banner ""
=>
(assert (UI-state (display WelcomeMessage)
(relation-asserted start)
(state initial)
(valid-answers))))
;;;***************
;;;* QUERY RULES *
;;;***************
(defrule determine-engine-state ""
(logical (start))
=>
(assert (UI-state (display StartQuestion)
(relation-asserted engine-starts)
(response No)
(valid-answers No Yes))))
(defrule determine-runs-normally ""
(logical (engine-starts Yes))
=>
(assert (UI-state (display RunQuestion)
(relation-asserted runs-normally)
(response No)
(valid-answers No Yes))))
(defrule determine-rotation-state ""
(logical (engine-starts No))
=>
(assert (UI-state (display RotateQuestion)
(relation-asserted engine-rotates)
(response No)
(valid-answers No Yes))))
(defrule determine-sluggishness ""
(logical (runs-normally No))
=>
(assert (UI-state (display SluggishQuestion)
(relation-asserted engine-sluggish)
(response No)
(valid-answers No Yes))))
(defrule determine-misfiring ""
(logical (runs-normally No))
=>
(assert (UI-state (display MisfireQuestion)
(relation-asserted engine-misfires)
(response No)
(valid-answers No Yes))))
(defrule determine-knocking ""
(logical (runs-normally No))
=>
(assert (UI-state (display KnockQuestion)
(relation-asserted engine-knocks)
(response No)
(valid-answers No Yes))))
(defrule determine-low-output ""
(logical (runs-normally No))
=>
(assert (UI-state (display OutputQuestion)
(relation-asserted engine-output-low)
(response No)
(valid-answers No Yes))))
(defrule determine-gas-level ""
(logical (engine-starts No)
(engine-rotates Yes))
=>
(assert (UI-state (display GasQuestion)
(relation-asserted tank-has-gas)
(response No)
(valid-answers No Yes))))
(defrule determine-battery-state ""
(logical (engine-rotates No))
=>
(assert (UI-state (display BatteryQuestion)
(relation-asserted battery-has-charge)
(response No)
(valid-answers No Yes))))
(defrule determine-point-surface-state ""
(or (logical (engine-starts No)
(engine-rotates Yes))
(logical (engine-output-low Yes)))
=>
(assert (UI-state (display PointsQuestion)
(relation-asserted point-surface-state)
(response Normal)
(valid-answers Normal Burned Contaminated))))
(defrule determine-conductivity-test ""
(logical (engine-starts No)
(engine-rotates No)
(battery-has-charge Yes))
=>
(assert (UI-state (display CoilQuestion)
(relation-asserted conductivity-test-positive)
(response No)
(valid-answers No Yes))))
;;;****************
;;;* REPAIR RULES *
;;;****************
(defrule normal-engine-state-conclusions ""
(logical (runs-normally Yes))
=>
(assert (UI-state (display NoRepair)
(state final))))
(defrule engine-sluggish ""
(logical (engine-sluggish Yes))
=>
(assert (UI-state (display FuelLineRepair)
(state final))))
(defrule engine-misfires ""
(logical (engine-misfires Yes))
=>
(assert (UI-state (display PointGapRepair)
(state final))))
(defrule engine-knocks ""
(logical (engine-knocks Yes))
=>
(assert (UI-state (display AdjustTimingRepair)
(state final))))
(defrule tank-out-of-gas ""
(logical (tank-has-gas No))
=>
(assert (UI-state (display AddGasRepair)
(state final))))
(defrule battery-dead ""
(logical (battery-has-charge No))
=>
(assert (UI-state (display ReplaceBatteryRepair)
(state final))))
(defrule point-surface-state-burned ""
(logical (point-surface-state Burned))
=>
(assert (UI-state (display ReplacePointsRepair)
(state final))))
(defrule point-surface-state-contaminated ""
(logical (point-surface-state Contaminated))
=>
(assert (UI-state (display CleanPointsRepair)
(state final))))
(defrule conductivity-test-positive-yes ""
(logical (conductivity-test-positive Yes))
=>
(assert (UI-state (display LeadWireRepair)
(state final))))
(defrule conductivity-test-positive-no ""
(logical (conductivity-test-positive No))
=>
(assert (UI-state (display CoilRepair)
(state final))))
(defrule no-repairs ""
(declare (salience -10))
(logical (UI-state (id ?id)))
(state-list (current ?id))
=>
(assert (UI-state (display MechanicRepair)
(state final))))
;;;*************************
;;;* GUI INTERACTION RULES *
;;;*************************
(defrule ask-question
(declare (salience 5))
(UI-state (id ?id))
?f <- (state-list (sequence $?s&:(not (member$ ?id ?s))))
=>
(modify ?f (current ?id)
(sequence ?id ?s))
(halt))
(defrule handle-next-no-change-none-middle-of-chain
(declare (salience 10))
?f1 <- (next ?id)
?f2 <- (state-list (current ?id) (sequence $? ?nid ?id $?))
=>
(retract ?f1)
(modify ?f2 (current ?nid))
(halt))
(defrule handle-next-response-none-end-of-chain
(declare (salience 10))
?f <- (next ?id)
(state-list (sequence ?id $?))
(UI-state (id ?id)
(relation-asserted ?relation))
=>
(retract ?f)
(assert (add-response ?id)))
(defrule handle-next-no-change-middle-of-chain
(declare (salience 10))
?f1 <- (next ?id ?response)
?f2 <- (state-list (current ?id) (sequence $? ?nid ?id $?))
(UI-state (id ?id) (response ?response))
=>
(retract ?f1)
(modify ?f2 (current ?nid))
(halt))
(defrule handle-next-change-middle-of-chain
(declare (salience 10))
(next ?id ?response)
?f1 <- (state-list (current ?id) (sequence ?nid $?b ?id $?e))
(UI-state (id ?id) (response ~?response))
?f2 <- (UI-state (id ?nid))
=>
(modify ?f1 (sequence ?b ?id ?e))
(retract ?f2))
(defrule handle-next-response-end-of-chain
(declare (salience 10))
?f1 <- (next ?id ?response)
(state-list (sequence ?id $?))
?f2 <- (UI-state (id ?id)
(response ?expected)
(relation-asserted ?relation))
=>
(retract ?f1)
(if (neq ?response ?expected)
then
(modify ?f2 (response ?response)))
(assert (add-response ?id ?response)))
(defrule handle-add-response
(declare (salience 10))
(logical (UI-state (id ?id)
(relation-asserted ?relation)))
?f1 <- (add-response ?id ?response)
=>
(str-assert (str-cat "(" ?relation " " ?response ")"))
(retract ?f1))
(defrule handle-add-response-none
(declare (salience 10))
(logical (UI-state (id ?id)
(relation-asserted ?relation)))
?f1 <- (add-response ?id)
=>
(str-assert (str-cat "(" ?relation ")"))
(retract ?f1))
(defrule handle-prev
(declare (salience 10))
?f1 <- (prev ?id)
?f2 <- (state-list (sequence $?b ?id ?p $?e))
=>
(retract ?f1)
(modify ?f2 (current ?p))
(halt))

Use the set-strategy command to change the conflict resolution strategy.
CLIPS (6.4 2/9/21)
CLIPS> (set-strategy breadth)
depth
CLIPS>
You can call this command anywhere you can normally call commands but typically you would call it either at the command prompt or from the actions of a rule.

Related

SQL query takes too long to execute. Need to improve performance of query

I'm using SQL Server, .NET 5 environment. This SQL query takes too long to execute. This query waiting time is almost 3 min but there are only 35 records. Are there better way to optimize this query ?
var allmeetings = await _context.MeetingMaster
.Where(x => x.IsActive == true &&
(x.MeetingParticipants.Any(y => y.ParticipantId == Convert.ToInt32(_currentUserService.CurrentUserId)) ||
x.OrganizedById == Convert.ToInt32(_currentUserService.CurrentUserId)))
.Include(a => a.MeetingParticipants)
.ThenInclude(b => b.Participant)
.Include(a => a.MeetingAgendaItems)
.ThenInclude(e => e.MeetingActionItems)
.ThenInclude(w => w.ActionItemLogs)
.Include(a => a.MeetingAgendaItems)
.ThenInclude(e => e.MeetingActionItems)
.ThenInclude(w => w.ActionItemResposibilities)
.Include(g => g.MeetingAgendaItems)
.ThenInclude(v => v.MeetingAgendaItemTypes)
.ThenInclude(j => j.AgendaItemRef)
.Include(w => w.MeetingAgendaItems)
.ThenInclude(d => d.RestrictedAgendaItemList)
.ThenInclude(s => s.ParticipantRef)
.Include(s => s.MeetingAgendaItems)
.ThenInclude(q => q.MeetingAgendaItemSupportiveDocuments)
.Include(c => c.MonthsRef)
.Include(z => z.YearsRef)
.Include(g => g.MeetingMinutesDoc)
.Include(c => c.Project)
.Include(c => c.Category)
.Include(l => l.MeetingSuggestions)
.Include(q => q.MeetingMattersArises)
.ThenInclude(i => i.MattersAriseResponsibilities)
.ThenInclude(s => s.ResponsiblePerson)
.Include(e => e.MeetingMattersArises)
.ThenInclude(w => w.MattersAriseReviewerComments)
.Include(s => s.MeetingMattersArises)
.ThenInclude(e => e.MattersAriseLogs)
.AsSplitQuery()
.ToListAsync(cancellationToken);
var result = allmeetings.Where(x => x.IsActive == true &&
x.isRecurringMeeting == false &&
(x.MeetingParticipants.Any(y => y.ParticipantId == Convert.ToInt32(_currentUserService.CurrentUserId)) || x.OrganizedById == Convert.ToInt32(_currentUserService.CurrentUserId))).ToList();
var RecMeetings = allmeetings.Where(x => x.IsActive == true &&
x.isRecurringMeeting == true &&
(x.MeetingParticipants.Any(y => y.ParticipantId == Convert.ToInt32(_currentUserService.CurrentUserId)) || x.OrganizedById == Convert.ToInt32(_currentUserService.CurrentUserId))).ToList();
var groupedRecMeetings = RecMeetings.GroupBy(u => u.MeetingRefId.Substring(0, u.MeetingRefId.LastIndexOf('-'))).Select(grp => grp.ToList()).ToList();
var GraeterMeetings = new List<MeetingMaster>();
foreach (var met in groupedRecMeetings)
{
result.AddRange(met.FindAll(x => x.MeetingStatus != "Initiated" ));
GraeterMeetings.AddRange(met.FindAll(x => x.MeetingStatus == "Initiated"));
if(GraeterMeetings.Count != 0)
{
result.Add(GraeterMeetings.OrderBy(x => x.MeetingDate).First());
}
GraeterMeetings.Clear();
}
return result.OrderByDescending(d => d.Id).ToList();
First of all you have so many Includes() and ThenIncludes(), this if really bad for your performance. Is there a way by any chance you can reduce these includes -> only use the necessary one's.
Then i would that you execute the .ToList() query at the end of the statement (befor your return)
Down below is an example how i've done it in the past (with pagination & filtration):
var context = _context.People
.Include(x => x.Parents)
.ThenInclude(x => x.Adress)
.Include(x => x.Job)
.Include(x => x.Hobbies);
var items = string.IsNullOrWhiteSpace(query)
? context
: context.Where(x => x.Name.Contains(query));
var filters = new List<int>();
if (filter != null)
{
filters = filter.Split(',').Select(int.Parse).ToList();
items = items.Where(x => x.Parents.Select(s => s.AdressId).Any(z => filters.Any(y => y == z)));
}
return await items.Skip(page * take).Take(take).ToListAsync();

The ExceptResultOperator result operator is not current supported

I want to exclude one resultset from another and I am using Except for that but it is giving error that "The ExceptResultOperator result operator is not current supported". I can not use all the conditions in where clause of a single query as it will give me unexcepted result.
//Sample code what I have tried
var result1 = Session.Query<Table>()
.Where(x => x.ColumnName != null && !x.active)
.Select(x => x)
var result2 = Session.Query<Table>()
.Where(x => x.Active)
.Except(result1)
.Select(x => x)
You can use Contains instead of Except:
var result1 = Session.Query<Table>()
.Where(x => x.ColumnName != null && !x.active)
.Select(x => x)
var result2 = Session.Query<Table>()
.Where(x => x.Active && !result1.Contains(x))
.Select(x => x)

NHibernate group by and order by division of two conditional sum

I have the following code:
var classAttendanceDetails =
Session.QueryOver<StudentClassAttendanceDetails>(() => scadAlias)
.JoinAlias(() => scadAlias.StudentClassAttendence, () => scaAlias)
.JoinAlias(() => scaAlias.Lecture, () => lAlias).JoinAlias(() => scaAlias.Teacher, () => tAlias).JoinAlias(() => scadAlias.StudentProgram, () => spAlias);
var queryover = classAttendanceDetails
.Select(
Projections.Group<StudentClassAttendanceDetails>(c => scaAlias.Lecture),
Projections.Group<StudentClassAttendanceDetails>(c => scaAlias.Teacher),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback == 1),
Projections.Constant(1),
Projections.Constant(0))),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback == 2),
Projections.Constant(1),
Projections.Constant(0))),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback == 3),
Projections.Constant(1),
Projections.Constant(0))),
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(
f => f.StudentFeedback.IsIn(new[] {1, 2, 3})),
Projections.Constant(1),
Projections.Constant(0))),
Projections.SqlFunction(
new VarArgsSQLFunction("(", "/", ")"),
NHibernateUtil.Int32,
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback == 1),
Projections.Constant(1),
Projections.Constant(0))),
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback.IsIn(new[] { 1, 2, 3 })),
Projections.Constant(1),
Projections.Constant(0)))
).OrderBy(Projections.SqlFunction(
new VarArgsSQLFunction("(", "/", ")"),
NHibernateUtil.Int32,
Projections.Sum(
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback == 1),
Projections.Constant(1),
Projections.Constant(0))),
Projections.Conditional(
Restrictions.Where<StudentClassAttendanceDetails>(f => f.StudentFeedback.IsIn(new[] { 1, 2, 3 })),
Projections.Constant(1),
Projections.Constant(0)))).Desc;
Here I am trying to order the result by number of results where feedback is 1 devided by no of results where feedback is 1/2/3.But i can not order by this because it is not included in the group by.How can i include it in group by

nHibernate - Adding aggregate functions in .select

I am trying to implement a business formula in QueryOver.
POorder.Estimate is a calculated field and I need to get
ToDateOrderAmount = POrder.Estimate - Sum(PODist.Field1) - Sum(PODisTaxRebate.Field1 + PODisTaxRebate.Field2)
So I need to write a query. What I have now is:
var reportModels =
Session.QueryOver<Domain.Model.Purchasing.Vendor>(() => v)
.Left.JoinQueryOver(() => v.Invoices, () => invoice)
.Left.JoinQueryOver(() => invoice.PurchaseOrder, () => poOrder)
.Left.JoinQueryOver(() => poOrder.PurchaseOrderDistributions, () => poDistribution)
.Left.JoinQueryOver(() => poDistribution.TaxRebate, () => poTaxRebate)
.SelectList(
list =>
list.Select(() => v.Number).WithAlias(() => varptModel.VendorNumber)
.Select(() => v.TypeCode.Code).WithAlias(() => varptModel.VendorType)
.Select(() => v.Name).WithAlias(() => varptModel.VendorName)
.Select(() => v.PurchasingContactPhoneNumber + "-Ext." + v.PurchasingContactPhoneNumberExt).WithAlias(() => varptModel.Phone)
.Select(() => v.Address).WithAlias(() => varptModel.Address)
.Select(() => invFiscalYear.Year).WithAlias(() => varptModel.Year)
.Select(() => invoice.TotalAmount).WithAlias(() => varptModel.InvoiceToDate)
.Select(() => invoice.AmountPaidToDate).WithAlias(() => varptModel.PaymentToDate)
.Select(() => poOrder.Estimate).WithAlias(() => varptModel.OrdersToDate)
.Select(() => poOrder.Estimate - Sum(poDistribution.Field1) - Sum(poTaxRebate.Discount1 + poTaxRebate.Discount2) )
).List();
But this is not right. What should I change it to?
I tried many things and found this working
.Select(Projections.SqlFunction(new VarArgsSQLFunction("", "+", ""),
NHibernateUtil.Double,
Projections.SqlFunction(new VarArgsSQLFunction("", "+", ""),
NHibernateUtil.Double,
Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invoiceLineItem.Expense), Projections.Constant(0))),
Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invitemTaxRebate.Rebate1Expense), Projections.Constant(0)))),
Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invitemTaxRebate.Rebate2Expense), Projections.Constant(0)))))
.WithAlias(() => varptModel.ToDateInvoices)
which gave me this in SQL
sum(coalesce(invoicelin8_.Expense, 0 )) + sum(coalesce(invitemtax9_.Rebate1Expense, 0 )) + sum(coalesce(invitemtax9_.Rebate2Expense, 0 ))
I added Coalesce as when we add or subtract values with null value, all values becomes null in result. Just a hint for new ones.

Nhibernate QueryOver: Count in where clause

Any tips on how to convert the following to QueryOver:
var widget = session.Query<Widget>()
.Fetch(x => x.NotificationJobs)
.Where(x =>
x.Status == Status.Active &&
!x.NotificationJobs.Any())
.OrderByDescending(x => x.DateCreated)
.Take(1)
.SingleOrDefault();
Want to get a widget that has no notification jobs.
var widgetWithNoNotificationJob = session.QueryOver<Widget>()
.Where( x => x.Status == Status.Active )
.OrderBy( x => x.DateCreated ).Desc
.Left.JoinQueryOver<NotificationJob>( x => x.NotificationJobs )
.Where( x => x.NotificationJobId == null )
.Take( 1 )
.SingleOrDefault();
This will produce SQL with a LEFT OUTER JOIN on the NotificationJob table and a WHERE clause with NotificationJob.NotificationJobId IS NULL.
Hopefully this will point you in the right direction.