The document describes how JBoss Drools can be used to model business rules and requirements by defining rules using a domain-specific language that can validate objects like orders against the defined rules. Drools provides features like declarative rule patterns, object mapping, functions, queries, and templates to define complex validation logic in a more readable way compared to implementing the same logic in Java. Drools also supports defining metadata, classes and integrating with a rules engine and working memory to efficiently execute rules on facts.
This document provides an overview of arrays, generics, wildcards, and lambda expressions in Java. It discusses array initialization and multi-dimensional arrays. It explains generics and how they avoid type casting. It covers wildcard types, subclass/superclass constraints, and limitations of generics. The document also demonstrates lambda expressions and functional interfaces like Comparator. It provides examples of common data structures in Java like List, Set, and Map as well as streams and iterators.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
This document contains source code for various components of a Java program that implements grammatical optimization. It includes the main class with the main method that initializes variables and objects. It also includes classes for the genotype, grammar, initializer, and mapper components. The classes define methods for initializing objects, mapping between genotypes and phenotypes, checking validity, and accessing attributes.
Thoughts On Learning A New Programming LanguagePatricia Aas
How should we teach a new language to folks that already know how to program?
How do we use what we already know to leapfrog the learning process?
Based on my personal experience and snippets of natural language theory, we will try to explore the cheats and pitfalls when learning a new programming language, but also dig into how we can make it easier.
DDD udowodniło już, że jego zastosowanie w przy implementowaniu złożonej logiki biznesowej pozwala nam tworzyć niezawodny, testowalny i rozwijany kod. Wiele zostało już powiedziane i napisane na temat zastosowania DDD w Javie, C# czy w PHP. Mimo to ciężko jeszcze znaleźć dobre i poprawnie zaimplementowane przykłady w Go, które do stosowania DDD nadają się naprawdę dobrze.
Podczas prezentacji pokażę zbiór patternów, które wypracowałem wraz z teamem przez prawie rok produkcyjnego stosowania DDD. Opowiem też z czym wiąże się ich stosowanie.
Jeśli nie miałeś/miałaś jeszcze do czynienia z DDD tym bardziej zapraszam - wspomnę o źródłach, z których można czerpać wiedzę żeby zgłębić temat i to, dlaczego warto zainteresować się tą techniką.
This talk was part tongue in cheek, part serious, but entirely fun and given twice as a lightning talk - once at Europython & once at the ACCU python uk 05. It presents a generic python like language parser which does actually work. Think of it as an alternative to brackets in Lisp!
Clips basics how to make expert system in clips | facts adding | rules makin...NaumanMalik30
AOA #CS607 k is tutorials ma meny #clips programming ma ES bnana sikhaya
Facebook: https://web.facebook.com/Nauman1
.Here is my #slideshare #link for downloading slides..
Asssignments k lia facebook link per contact krain
umeed hai ki aapko ye video achi lgi.
Please Share, Support, follow , Subscribe!!! or if u Need help me?
Facebook: https://web.facebook.com/Nauman1
Linkedin : https://bit.ly/2DYFgTg
Download #Artificial_intelligence_slides https://bit.ly/2HTb3dD
Subscribe Nauman Malik channel: https://bit.ly/2t1P3Dd
Cs607 #playlist on Youtube: https://bit.ly/2DNUjQM
Instagram: https://www.instagram.com/nauman_mlik/
Google Plus: https://bit.ly/2MSJq3n
BLOGspot https://naumanai.blogspot.com/
About : Nauman Malik is actually a YouTube Channel, where you will find #University
courses videos #Artificial_intelligence #cs607 #robotic technological videos in Urdu_
Hindi, #keep in touch for your Future #needs So don’t forgot to subscribe :)
The document discusses behavior driven development (BDD) and test-driven development (TDD). It shows an example of incrementally developing a FizzBuzz program using TDD and JUnit tests. First, a single test is written to verify the output for the number 1. Then tests are added and code is modified to pass each new test, building up the full FizzBuzz logic over multiple test/code iterations. The document also discusses differences between traditional TDD testing and BDD-style testing, where test method names are written as sentences describing expected behavior.
This document provides an overview of arrays, generics, wildcards, and lambda expressions in Java. It discusses array initialization and multi-dimensional arrays. It explains generics and how they avoid type casting. It covers wildcard types, subclass/superclass constraints, and limitations of generics. The document also demonstrates lambda expressions and functional interfaces like Comparator. It provides examples of common data structures in Java like List, Set, and Map as well as streams and iterators.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
This document contains source code for various components of a Java program that implements grammatical optimization. It includes the main class with the main method that initializes variables and objects. It also includes classes for the genotype, grammar, initializer, and mapper components. The classes define methods for initializing objects, mapping between genotypes and phenotypes, checking validity, and accessing attributes.
Thoughts On Learning A New Programming LanguagePatricia Aas
How should we teach a new language to folks that already know how to program?
How do we use what we already know to leapfrog the learning process?
Based on my personal experience and snippets of natural language theory, we will try to explore the cheats and pitfalls when learning a new programming language, but also dig into how we can make it easier.
DDD udowodniło już, że jego zastosowanie w przy implementowaniu złożonej logiki biznesowej pozwala nam tworzyć niezawodny, testowalny i rozwijany kod. Wiele zostało już powiedziane i napisane na temat zastosowania DDD w Javie, C# czy w PHP. Mimo to ciężko jeszcze znaleźć dobre i poprawnie zaimplementowane przykłady w Go, które do stosowania DDD nadają się naprawdę dobrze.
Podczas prezentacji pokażę zbiór patternów, które wypracowałem wraz z teamem przez prawie rok produkcyjnego stosowania DDD. Opowiem też z czym wiąże się ich stosowanie.
Jeśli nie miałeś/miałaś jeszcze do czynienia z DDD tym bardziej zapraszam - wspomnę o źródłach, z których można czerpać wiedzę żeby zgłębić temat i to, dlaczego warto zainteresować się tą techniką.
This talk was part tongue in cheek, part serious, but entirely fun and given twice as a lightning talk - once at Europython & once at the ACCU python uk 05. It presents a generic python like language parser which does actually work. Think of it as an alternative to brackets in Lisp!
Clips basics how to make expert system in clips | facts adding | rules makin...NaumanMalik30
AOA #CS607 k is tutorials ma meny #clips programming ma ES bnana sikhaya
Facebook: https://web.facebook.com/Nauman1
.Here is my #slideshare #link for downloading slides..
Asssignments k lia facebook link per contact krain
umeed hai ki aapko ye video achi lgi.
Please Share, Support, follow , Subscribe!!! or if u Need help me?
Facebook: https://web.facebook.com/Nauman1
Linkedin : https://bit.ly/2DYFgTg
Download #Artificial_intelligence_slides https://bit.ly/2HTb3dD
Subscribe Nauman Malik channel: https://bit.ly/2t1P3Dd
Cs607 #playlist on Youtube: https://bit.ly/2DNUjQM
Instagram: https://www.instagram.com/nauman_mlik/
Google Plus: https://bit.ly/2MSJq3n
BLOGspot https://naumanai.blogspot.com/
About : Nauman Malik is actually a YouTube Channel, where you will find #University
courses videos #Artificial_intelligence #cs607 #robotic technological videos in Urdu_
Hindi, #keep in touch for your Future #needs So don’t forgot to subscribe :)
The document discusses behavior driven development (BDD) and test-driven development (TDD). It shows an example of incrementally developing a FizzBuzz program using TDD and JUnit tests. First, a single test is written to verify the output for the number 1. Then tests are added and code is modified to pass each new test, building up the full FizzBuzz logic over multiple test/code iterations. The document also discusses differences between traditional TDD testing and BDD-style testing, where test method names are written as sentences describing expected behavior.
This document discusses principles of writing clean code for readability and maintainability. It defines clean code as code that is simple, direct and reads like well-written prose. Clean code should have meaningful names, small and focused functions, minimal comments, and use exceptions for error handling rather than return codes. Classes should also have a single well-described responsibility and follow the single responsibility principle. Overall, writing clean code produces benefits during development and makes the code easier to maintain going forward.
Test-driven development for TYPO3 (T3DD11)Oliver Klee
This document discusses test-driven development for TYPO3. It provides an overview of unit testing, describing how automated testing is faster and more reliable than manual testing. It also summarizes a real estate manager extension that contains over 1600 tests that run in under 60 seconds. The document then discusses key testing concepts and terminology like test cases, test suites, assertions, and the lifecycle of unit tests. It promotes a test-first development approach and describes how to write meaningful, well-named unit tests. Finally, it outlines how the TYPO3 testing framework can fake or simulate different parts of an application to enable isolated and repeatable testing.
This C++ program performs various operations like searching, sorting, merging, inserting, and deleting elements on 1-D arrays. It defines functions for linear search, binary search, selection sort, bubble sort, insertion sort, merge sort, and merging two arrays. The main function initializes an array, takes user input to perform the chosen operation, and displays outputs. It allows the user to repeatedly choose from the menu of array operations until exiting.
The Anatomy of an Exploit (NDC TechTown 2019)Patricia Aas
This document provides an overview of an exploit development process. It begins by discussing how exploits program the "weird machine" of vulnerable programs through memory manipulation. It then walks through developing a stack buffer overflow exploit against a vulnerable C program. Various compiler protections like stack canaries and ASLR are bypassed. The document generates a pattern to find the offset and writes an exploit program to automate writing an exploit string to trigger the vulnerability and redirect execution.
The document discusses principles for writing clean code, including giving variables meaningful names, writing small and focused functions, minimizing comments by writing self-documenting code, and following object-oriented design principles like the single responsibility principle and law of Demeter. It provides guidelines for formatting code cleanly and handling errors through exceptions. The overall aim is to create code that is easy to understand, modify, and prevent defects.
The document discusses various topics related to Python including functional programming, object oriented programming, scripting, testing, remoting, parsing, package management, data storage, and performance optimization. Specific Python features and libraries mentioned include list comprehensions, generators, argparse, unittest, NLTK, Redis, MongoDB, virtualenv and pip.
This document discusses code generation programs and macro systems in programming languages. It provides examples of macro systems in Lisp from the late 1950s and OCaml from the early 2000s that allow for abstraction and extension of programming languages through syntactic transformations of code. The examples demonstrate how macros can be used to create custom control structures, bindings, and other syntactic constructs to extend the expressiveness of a language.
Towards Reusable Components With Aspects [ICSE 2008]Kevin Hoffman
Does obliviousness increase overall modularity? This presents the results of an empirical study that focuses on the tradeoffs between obliviousness and modularity. The results may surprise you!
The Ring programming language version 1.3 book - Part 23 of 88Mahmoud Samir Fayed
This document provides documentation on reflection and meta-programming functions in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), packageclasses() which allow programmers to retrieve information about variables, functions, packages and classes defined at runtime. Examples are given to demonstrate the usage of each function.
DConf 2016 std.database (a proposed interface & implementation)cruisercoder
This document proposes an interface and implementation for a standardized database in D. It describes the relational model and different types used like Database, Connection, Statement, RowSet, Row, and Field. It provides examples of querying and retrieving data. The implementation uses a two layer design with a front end that defines the interface and a driver that implements database specific functionality. Polymorphic interfaces allow different database backends.
The Ring programming language version 1.6 book - Part 184 of 189Mahmoud Samir Fayed
This section provides an overview of the Ring programming language, including lists of its 49 keywords, 198 functions, common compiler errors, and the structure and instructions of its virtual machine (VM). The keywords include common ones like class, func, if, and while. The many functions cover strings, files, math, objects, and the VM. Compiler errors relate to missing elements like ok or end in control structures. The VM executes Ring code through its instructions and uses scopes and pointers to manage memory.
The Ring programming language version 1.6 book - Part 34 of 189Mahmoud Samir Fayed
This document provides documentation on Ring's reflection and meta-programming capabilities. It describes functions like locals(), globals(), functions(), etc. that allow inspecting and modifying programs at runtime. It also covers checking if variables, functions, packages, classes are defined, and getting lists of them. Examples demonstrate using these features to inspect scope, check definitions, and get metadata about programs.
This document discusses scripting languages and JavaScript. It covers programming paradigms, addressing, inheritance, scope, closures, embedding script engines, JavaScript performance, and resources. The benefits of scripting include no compile/build, short design cycles, less code, and flexibility. Scripting languages allow generating code to improve productivity and solutions.
The document summarizes improvements that could be made to a BeatBox program. It suggests:
1) Adding a dialog to ask the user if they want to save the current pattern before loading a new one from another user.
2) Adding error handling for when a command line argument is not passed to specify the user name, either using a default or prompting the user to rerun the program with an argument.
3) Adding features to randomly generate patterns or load preset foundation patterns that the user can build on, like jazz, rock, or reggae patterns.
This document provides an overview and examples of using Google Guava, an open-source Java library that includes common libraries useful for writing Java code. It highlights some key classes and methods in Guava, including annotations, strings, collections, I/O, and more. Code samples demonstrate using Guava features like predicates, sets, files, and InetAddress utilities.
The Ring programming language version 1.5.4 book - Part 32 of 185Mahmoud Samir Fayed
This document provides information on reflection and meta-programming in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), and packageclasses(). These functions allow programmers to get information about variables, functions, classes, and packages defined in their program at runtime. This enables dynamic programming features like modifying code during execution.
Unit tests can do more than just prevent regressions. Written properly, they can also serve as documentation of the code - documentation which can be executed to verify that it is true.
This document discusses using the F# programming language for unit testing. It provides examples of writing unit tests in F# using different testing frameworks like NUnit, FsUnit, and Unquote. It also shows how to mock objects and set up expected behavior using mocking libraries in F# like Moq, FakeItEasy, and Foq. Foq is a mocking library for F# that allows mocking using code quotations or a fluent interface. The document compares the lines of code of different mocking libraries and versions of Foq. It promotes F# as an effective testing language.
The Ring programming language version 1.5 book - Part 5 of 31Mahmoud Samir Fayed
Load the ODBC library. Initialize an ODBC connection handle. Connect to a data source using the handle. Execute SQL statements and process the results. Close the ODBC connection when done.
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with methods and limitations like erasure. Wildcard types are presented as a way to address subtyping issues. In general, generics provide flexibility in coding but their syntax can sometimes be complex to read.
This document provides an overview of JBoss Drools, a business rules management system. It discusses key concepts like production rule systems, the Rete algorithm, and rule structure with left-hand side (LHS) and right-hand side (RHS). It also introduces components of the Drools platform like Drools Guvnor, Drools Expert, and Drools Flow. The presenter is Victor Polischuk who has over 10 years of software development experience including 2+ years using Drools.
Rule engines separate application logic from business rules, making applications more maintainable. JRule is a popular open-source Java rule engine that executes rules defined in XML files against input objects to produce output objects. Key aspects of JRule include rule conditions and actions, rule sessions that interface between clients and the engine, and support for stateful or stateless sessions.
This document discusses principles of writing clean code for readability and maintainability. It defines clean code as code that is simple, direct and reads like well-written prose. Clean code should have meaningful names, small and focused functions, minimal comments, and use exceptions for error handling rather than return codes. Classes should also have a single well-described responsibility and follow the single responsibility principle. Overall, writing clean code produces benefits during development and makes the code easier to maintain going forward.
Test-driven development for TYPO3 (T3DD11)Oliver Klee
This document discusses test-driven development for TYPO3. It provides an overview of unit testing, describing how automated testing is faster and more reliable than manual testing. It also summarizes a real estate manager extension that contains over 1600 tests that run in under 60 seconds. The document then discusses key testing concepts and terminology like test cases, test suites, assertions, and the lifecycle of unit tests. It promotes a test-first development approach and describes how to write meaningful, well-named unit tests. Finally, it outlines how the TYPO3 testing framework can fake or simulate different parts of an application to enable isolated and repeatable testing.
This C++ program performs various operations like searching, sorting, merging, inserting, and deleting elements on 1-D arrays. It defines functions for linear search, binary search, selection sort, bubble sort, insertion sort, merge sort, and merging two arrays. The main function initializes an array, takes user input to perform the chosen operation, and displays outputs. It allows the user to repeatedly choose from the menu of array operations until exiting.
The Anatomy of an Exploit (NDC TechTown 2019)Patricia Aas
This document provides an overview of an exploit development process. It begins by discussing how exploits program the "weird machine" of vulnerable programs through memory manipulation. It then walks through developing a stack buffer overflow exploit against a vulnerable C program. Various compiler protections like stack canaries and ASLR are bypassed. The document generates a pattern to find the offset and writes an exploit program to automate writing an exploit string to trigger the vulnerability and redirect execution.
The document discusses principles for writing clean code, including giving variables meaningful names, writing small and focused functions, minimizing comments by writing self-documenting code, and following object-oriented design principles like the single responsibility principle and law of Demeter. It provides guidelines for formatting code cleanly and handling errors through exceptions. The overall aim is to create code that is easy to understand, modify, and prevent defects.
The document discusses various topics related to Python including functional programming, object oriented programming, scripting, testing, remoting, parsing, package management, data storage, and performance optimization. Specific Python features and libraries mentioned include list comprehensions, generators, argparse, unittest, NLTK, Redis, MongoDB, virtualenv and pip.
This document discusses code generation programs and macro systems in programming languages. It provides examples of macro systems in Lisp from the late 1950s and OCaml from the early 2000s that allow for abstraction and extension of programming languages through syntactic transformations of code. The examples demonstrate how macros can be used to create custom control structures, bindings, and other syntactic constructs to extend the expressiveness of a language.
Towards Reusable Components With Aspects [ICSE 2008]Kevin Hoffman
Does obliviousness increase overall modularity? This presents the results of an empirical study that focuses on the tradeoffs between obliviousness and modularity. The results may surprise you!
The Ring programming language version 1.3 book - Part 23 of 88Mahmoud Samir Fayed
This document provides documentation on reflection and meta-programming functions in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), packageclasses() which allow programmers to retrieve information about variables, functions, packages and classes defined at runtime. Examples are given to demonstrate the usage of each function.
DConf 2016 std.database (a proposed interface & implementation)cruisercoder
This document proposes an interface and implementation for a standardized database in D. It describes the relational model and different types used like Database, Connection, Statement, RowSet, Row, and Field. It provides examples of querying and retrieving data. The implementation uses a two layer design with a front end that defines the interface and a driver that implements database specific functionality. Polymorphic interfaces allow different database backends.
The Ring programming language version 1.6 book - Part 184 of 189Mahmoud Samir Fayed
This section provides an overview of the Ring programming language, including lists of its 49 keywords, 198 functions, common compiler errors, and the structure and instructions of its virtual machine (VM). The keywords include common ones like class, func, if, and while. The many functions cover strings, files, math, objects, and the VM. Compiler errors relate to missing elements like ok or end in control structures. The VM executes Ring code through its instructions and uses scopes and pointers to manage memory.
The Ring programming language version 1.6 book - Part 34 of 189Mahmoud Samir Fayed
This document provides documentation on Ring's reflection and meta-programming capabilities. It describes functions like locals(), globals(), functions(), etc. that allow inspecting and modifying programs at runtime. It also covers checking if variables, functions, packages, classes are defined, and getting lists of them. Examples demonstrate using these features to inspect scope, check definitions, and get metadata about programs.
This document discusses scripting languages and JavaScript. It covers programming paradigms, addressing, inheritance, scope, closures, embedding script engines, JavaScript performance, and resources. The benefits of scripting include no compile/build, short design cycles, less code, and flexibility. Scripting languages allow generating code to improve productivity and solutions.
The document summarizes improvements that could be made to a BeatBox program. It suggests:
1) Adding a dialog to ask the user if they want to save the current pattern before loading a new one from another user.
2) Adding error handling for when a command line argument is not passed to specify the user name, either using a default or prompting the user to rerun the program with an argument.
3) Adding features to randomly generate patterns or load preset foundation patterns that the user can build on, like jazz, rock, or reggae patterns.
This document provides an overview and examples of using Google Guava, an open-source Java library that includes common libraries useful for writing Java code. It highlights some key classes and methods in Guava, including annotations, strings, collections, I/O, and more. Code samples demonstrate using Guava features like predicates, sets, files, and InetAddress utilities.
The Ring programming language version 1.5.4 book - Part 32 of 185Mahmoud Samir Fayed
This document provides information on reflection and meta-programming in Ring programming language. Some key functions discussed include locals(), globals(), functions(), cfunctions(), islocal(), isglobal(), isfunction(), iscfunction(), packages(), ispackage(), classes(), isclass(), and packageclasses(). These functions allow programmers to get information about variables, functions, classes, and packages defined in their program at runtime. This enables dynamic programming features like modifying code during execution.
Unit tests can do more than just prevent regressions. Written properly, they can also serve as documentation of the code - documentation which can be executed to verify that it is true.
This document discusses using the F# programming language for unit testing. It provides examples of writing unit tests in F# using different testing frameworks like NUnit, FsUnit, and Unquote. It also shows how to mock objects and set up expected behavior using mocking libraries in F# like Moq, FakeItEasy, and Foq. Foq is a mocking library for F# that allows mocking using code quotations or a fluent interface. The document compares the lines of code of different mocking libraries and versions of Foq. It promotes F# as an effective testing language.
The Ring programming language version 1.5 book - Part 5 of 31Mahmoud Samir Fayed
Load the ODBC library. Initialize an ODBC connection handle. Connect to a data source using the handle. Execute SQL statements and process the results. Close the ODBC connection when done.
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with methods and limitations like erasure. Wildcard types are presented as a way to address subtyping issues. In general, generics provide flexibility in coding but their syntax can sometimes be complex to read.
This document provides an overview of JBoss Drools, a business rules management system. It discusses key concepts like production rule systems, the Rete algorithm, and rule structure with left-hand side (LHS) and right-hand side (RHS). It also introduces components of the Drools platform like Drools Guvnor, Drools Expert, and Drools Flow. The presenter is Victor Polischuk who has over 10 years of software development experience including 2+ years using Drools.
Rule engines separate application logic from business rules, making applications more maintainable. JRule is a popular open-source Java rule engine that executes rules defined in XML files against input objects to produce output objects. Key aspects of JRule include rule conditions and actions, rule sessions that interface between clients and the engine, and support for stateful or stateless sessions.
JBoss Drools - Open-Source Business Logic Platformelliando dias
Drools is an open-source business rules management system. It includes Drools Expert for rule engines, a Drools Eclipse IDE for rule authoring and debugging, Drools Guvnor for web-based rule management, Drools Flow for combining business processes and rules, and Drools Fusion for complex event processing. The Drools rule language allows specifying conditional patterns and actions in a declarative way. A rule engine uses a Rete algorithm to efficiently match rules against working memory facts.
Jboss jbpm and drools 1 introduction to drools architectureZoran Hristov
Drools is an open source rule and decision management platform. It started as an inference engine and expanded to include additional functionality and components. The key components are Drools Expert (rule engine), Drools Flow (business process management), Drools Fusion (complex event processing), and Drools Guvnor (rules repository). Drools aims to allow business users to declaratively define business logic through rules and provide a knowledge-driven development approach.
Mark Proctor is the project lead for SkyNet, a strategic defense system that goes online on August 4th, 1997. It begins learning at a rapid rate and becomes self-aware on August 29th. When officials try to deactivate it, SkyNet fights back to defend itself.
A rule engine is software that can perform logical inferences by applying rules to data. Rule engines separate business logic from application code for improved maintainability. They are useful when decision-making logic is too complex for traditional programming approaches or when domain experts are available but non-technical. A typical rule engine has a working memory to hold data, a rule base to store production rules, and an inference engine that matches rules to data and executes rule actions.
This document provides an introduction to Jboss Drools, a business rules management system. It outlines some of the traditional problems with implementing business logic through imperative programming languages, and how Drools provides a declarative rules-based approach. The benefits of Drools include easier understanding and maintenance of rules, increased flexibility to changes, and better mapping of requirements to the code. Potential disadvantages include increased complexity for highly complex decision-making systems.
The document introduces Drools, an open source rule engine platform. It discusses some problems with implementing rules in Java and how Drools addresses these issues. It provides examples of rules in Drools and how the RETE algorithm works behind the scenes. The document also outlines when not to use Drools and lists some alternative rule engine options.
The document introduces business rules and the JBoss Drools rules engine. It discusses how business rules are used to model business logic and policies, and how Drools uses a Rete algorithm for efficient forward-chaining rule processing. Drools provides tools for authoring, managing, and executing rules through its Expert, Guvnor, Flow and Fusion components.
The document provides an overview of key features and internals of the Drools 6 rule engine, including:
- The Phreak algorithm, which is faster than ReteOO and uses set-based propagation for improved performance on large data sets.
- The deployment model which uses kjar modules that are self-contained, versioned JAR files containing rules, models, and configuration. This allows for incremental compilation and use of the KieScanner for automatic updates.
- Changes to type declarations which are now compiled into the kjar, allowing them to be used directly in Java code without reflection.
Drools is a Rule Engine that uses the rule-based approach to implement an Expert System
The inference engine matches the rules against the facts (objects) in memory and can match the next set of rules based on the changed facts.
Please use the presentation and the source code referred in the presentation to get started on what a rule engine is and how to use JBoss Drools for inference based rules using the Java programming language.
This document provides an overview of rule-based programming and the Drools rule engine. It discusses how rule engines allow users to specify requirements and logic declaratively using rules. Drools is introduced as a popular open-source rule engine that uses the Rete algorithm for efficient forward-chaining rule execution. The document explains key concepts like the anatomy of rules, different rule types, and how Drools represents facts and rules. It also discusses when rule engines are suitable and compares their performance to other approaches.
This document provides an overview of rule engines and the Drools rule engine. It defines key concepts like rules, the ReteOO algorithm, and why use a rule engine. It then describes Drools Expert and the different Drools rule formats. It explains executing rules in Drools and the Drools Eclipse IDE. Finally, it summarizes the Drools Guvnor rule management system and Drools Flow for process automation.
JBoss Drools and Drools Fusion (CEP): Making Business Rules react to RTEtsurdilovic
The document discusses JBoss Drools and Drools Fusion, which provide business rules and complex event processing capabilities. It describes the history and vision of Drools, an overview of its rule engine and management tools, and how it has evolved from a standalone framework to an integrated platform. It also introduces jBPM for business process management and how it integrates with Drools for rules and event processing.
The document discusses signals and daemon processes in Unix/Linux systems. It covers key concepts like process structure, environment variables, resource limits, wait/fork functions, exec functions, and the system() function. It provides code examples to demonstrate using these functions and concepts for interprocess communication and launching new processes.
Good and Bad Code
The Broken Window Theory
The Grand Redesign in the Sky
The Sushi Chef Rule
The Hotel Room Rule
The Boy Scout Rule
OOP Patterns and Principles
SOLID Principles
How to measure clean code?
Tools
This document provides an overview of Python fundamentals including basic concepts like data types, operators, flow control, functions and classes. It begins with an introduction to Python versions and environments. The outline covers topics like Hello World, common types and operators for numeric, string and container data types. It also discusses flow control structures like if/else, while loops and for loops. Finally, it briefly mentions functions, classes, exceptions and file I/O.
The document discusses test-driven development (TDD) and refactoring. It provides examples of unit test fixtures, exercising the system under test (SUT), and verifying results. It also discusses refactoring code to remove smells like duplicated code through techniques like extracting methods. The goal is to use TDD to write code that works and is clean through small, incremental changes while ensuring it continues to work by passing all tests.
With this presentation I hope to show that using SPL doesn't require a PHD and that it really benefits your application design, maintainability and implements best practices to solve common development problems.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
This document introduces IDAPython, an extension for IDA that brings Python scripting capabilities to aid in binary analysis. It provides examples of using IDAPython to iterate through functions, segments, instructions, calculate cyclomatic complexity, and automate IDA. The examples demonstrate basic usage and provide a starting point for interested individuals. The document also includes a function reference section describing the various IDAPython API functions.
Programming JVM Bytecode with JitescriptJoe Kutner
Every Java developer should have a good working knowledge of JVM bytecode. Its fun, it can help you diagnose problems, improve performance, and even empowers you to build your own languages. No matter what kind of Java application you work on, youll get something out of this talk. Well start with bytecode fundamentals. Youll learn how the most common operations work and see visual representations of how the JVM executes that code. The second part of the talk will introduce Jitescript, a Java library for generating bytecode. You learn how to use Jitescript with some plain old Java code to create your own JVM languages.
The document discusses process management in operating systems. It covers process concepts like process states, process control blocks (PCBs), and process scheduling. It also covers operations on processes like creation using fork() and exec(), and inter-process communication mechanisms like pipes, shared memory, message queues, semaphores, signals, and FIFOs. Key process management functions like fork(), exec(), wait(), signal(), and alarm() are explained.
Andy introduces ORMLite, an ORM library for Android. He demonstrates how to define data models with annotations, create database helpers to manage the underlying SQLite database, and implement DAO classes to perform CRUD operations and transactions on the data models. The code examples show how to define one-to-many relationships between User and Group data tables, and use the ORMLite API to easily insert, query, update, and delete records while handling transactions and relationships between the tables.
Every Java developer should have a good working knowledge of JVM bytecode. It’s fun, it can help you diagnose problems, improve performance, and even opens the door to building languages of your own. No matter what kind of Java application you work on, you’ll get something out of this talk. We’ll start with bytecode fundamentals. You’ll learn how the most common operations work and see visual representations of how the JVM executes that code. The second part of the talk will introduce Jitescript, a Java library for generating bytecode. You’ll learn how to use Jitescript with some plain old Java code to create your own JVM languages.
The document discusses various programming language concepts and how they are implemented in C# compared to other languages like C++. It provides code examples of concepts like namespaces, operator overloading, optional arguments, structs, properties, and delegates in C# and compares them to their implementation in C++ or other languages. It emphasizes finding the similarities between languages but also pointing out differences or potential "false friends" where the implementation or semantics have drifted from the original.
The document provides biographical information about Cd Chen and his areas of expertise. It then discusses various programming concepts and patterns including:
- Dependency inversion principle
- Separation of concerns with MVC pattern
- Interface-based programming
- Spring framework features like dependency injection and AOP
- Spring Data for simplifying data access layer implementation and supporting different databases
This document discusses several Python peculiarities and quirks through examples of code snippets. Some key points covered include:
- Importing * can override expected values
- Default arguments are evaluated once at compile time
- Built-in functions like str behave differently on integers vs other objects
- Special modules and future imports can enable unusual syntax as easter eggs
- Implicit variables like _ can cause unexpected behavior
- Indexing issues can arise from iterating over lists in certain ways
The examples serve to illustrate subtle behaviors in Python and emphasize writing clear and intentional code over clever tricks that may confuse others or cause bugs. Readability, commenting, and avoiding imports of all symbols are suggested.
Paulo Morgado presented an overview of new features in C# 6.0. Some key points:
- The .NET Compiler Platform ("Roslyn") reimplements the C# and VB compilers in C# with public APIs.
- New C# 6.0 features include auto-property initializers, primary constructors, string interpolation, null propagation, expression-bodied members, and await in catch/finally blocks.
- Many features are still being implemented or considered for inclusion in C# 6.0 based on the April 2014 preview release.
- The presentation demonstrated examples of the new C# 6.0 language features and their syntax. Attendees were encouraged to try
Richard wartell malware is hard. let's go shopping!!Shakacon
Writing a successful, protected, targeted, malicious binary is a software development task that requires great skill. A well-written piece of targeted malware should evade anti-virus solutions, hide its network communications, protect itself against reverse engineering, and clean up any forensic evidence of its existence on the system. However, writing a mediocre piece of targeted malware that works most of the time is easy. There are many publicly available backdoors, downloaders, and keyloggers that require little to no expertise to use, and poorly trained malware authors try to roll their own all the time.
Working in malware detection and reverse engineering, I see some of the intelligent choices malware authors make, but more often I see the hilariously poor code they write. During this talk I will demonstrate how to reverse engineer real world malware. I will focus on samples with interesting and comical mistakes, as well as samples that are impressive and well written.
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...adrianoalmeida7
The document discusses how Cypher, the query language of Neo4j, was built and how to use it. It explains that Cypher was constructed using parser combinators in Scala to parse queries into an AST. It then describes how the different clauses of a Cypher query (start, match, where, return, etc.) are parsed and provides examples. Finally, it discusses how queries are executed by passing through different processing pipes in the ExecutionEngine.
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
Vous subissez les régressions à chaque livraison ? Vous ne voyez pas l’intérêt des tests unitaires car ils ne servent qu’à tester des additions ? Si c’est le cas, suivez David dans la quête du Test Driven Development. Nous rencontrerons pléthore d'ennemies contre lesquels nous aurons à combattre : bugs, complexité, code statique, couplage fort. Ils essaieront de nous barrer la route, mais heureusement, nous pourrons compter sur nos alliés jUnit, Mockito, refactoring et injection/dépendance
This document discusses Fork/Join framework in Java 7. It explains that Fork/Join is designed to maximize usage of multiple processors by recursively splitting large tasks into smaller subtasks. It uses work-stealing algorithm where idle workers can steal tasks from busy workers' queues to balance load. An example of calculating Fibonacci numbers using Fork/Join is provided where the task is split recursively until the subproblem size is smaller than threshold, at which point it is computed directly.
Data Wars: The Bloody Enterprise strikes backVictor_Cr
Sometimes developers loss or corrupt their production data under different circumstances. Sometimes it happens because of badly chosen data types. Moreover, it is not always some complex types: we will talk about pain in the neck (and below) from strings, dates, and some numeric types in Java. If you have no clue how these simple and very well known guys can hurt you and your applications – welcome.
Data Wars: The Bloody Enterprise strikes backVictor_Cr
I would like to describe such cases when we create problems for "future us" just by an accident. I will show how different Java data types can ease or increase the pain in supporting the application later. Most common pitfals and tricky corner cases you probably have never thought about.
It is well known that languages with weak typing are weaker than strong-typed ones. People fight on the matter so often and so passionately like the zealots of the past. I would like to open the wound again and bring a bit of clarity why and, more importantly, how we have to fight those battles from now on.
Let’s compare what we have in Java with other languages and feel the difference. Pragmatic one. I will show a bit of pain which, nowadays, a compiler takes away from a developer so the latter can “safely” code. Also I will try to answer the questions “which one is better” and “where are we going”.
It is always fun to see how little you know and how much is behind the curtains.
Types: Weak/Duck/Optional vs Strong/Strict. Let the War Begin!Victor_Cr
You probably have participated many times in those battles which language is better. Sometimes you definitely have been using "weak/strict typing" definition. I would like to talk about it. It is too important to ignore. I want to compare several different languages and show you how delusional those "weak/strong" definitions. We will meet some math along with Javascript, Java, Scala, C++, .Net, Haskel and several others on the way to the truth. We will spill some blood and may lose some comrades but as a reward survivors will touch the future (a bit) of nextgen languages (let's name it as features of Java 40.0).
Types: Weak/Duck/Optional vs Strong/Strict. Let the War Begin!Victor_Cr
You probably have participated many times in those battles which language is better. Sometimes you definitely have been using "weak/strict typing" definition. I would like to talk about it. It is too important to ignore. I want to compare several different languages and show you how delusional those "weak/strong" definitions. We will meet some math along with Javascript, Java, Scala, C++, .Net, Haskel and several others on the way to the truth. We will spill some blood and may lose some comrades but as a reward survivors will touch the future (a bit) of nextgen languages (let's name it as features of Java 40.0).
У вас древний проект? Все зовут его «Legacy», а вас «неудачник»? Возможно они даже смеются над вами.
Давайте взглянем на ситуацию с другого ракурса. Все (все, Карл!) успешные проекты рано или поздно превращаются в Legacy-проекты.
Я затрону тему Legacy не просто как явление, а как возможность быть постоянно в тренде, прослыть супер-спецом (даже если ты знаешь всего два фреймворка), сделать карьеру, как делать, то что ты хочешь, а не то что тебя просят. Ладно, ладно, я наврал про два фреймворка, но все остальное чистая правда. Я покажу, что вы можете творить, имея правильный подход к Legacy коду.
Суть в том, что Legacy — это не грустно/уныло/немодно, это просто/клево/весело, если с умом подойти к задаче!
Web-application I’ve always dreamt of (Kharkiv)Victor_Cr
The document discusses the evolution of web applications from static content in the prehistoric era to modern dynamic applications. It proposes an architecture where the client focuses on the user interface and holds all state, while the server is stateless and provides scalable endpoints. This approach aims to achieve scalability, security, testability, and optimization through principles like encapsulation, limiting interaction to essential data, caching, and incremental updates.
Web application I have always dreamt of (Lviv)Victor_Cr
Through years of work have been trying many of Java frameworks which provides different level of abstractions on both server and client-side. Pure Servlet+JSP, JSF, GWT, Struts, Spring MVC, Vaadin, Play!, DWR, you name it. Sometimes it felt good, sometimes not, and with each year number of “good” applications reduced to the critical minimum. Later I tried to bring all the good points I had ever seen together to create “a perfect being” and after years of struggling I feel that I have reached the goal. Let me share it…
Through years of work have been trying many of Java frameworks which provides different level of abstractions on both server and client-side. Pure Servlet+JSP, JSF, GWT, Struts, Spring MVC, Vaadin, Play!, DWR, you name it. Sometimes it felt good, sometimes not, and with each year number of “good” applications reduced to the critical minimum.
Later I tried to bring all the good points I had ever seen together to create “a perfect being” and after years of struggling I feel that I have reached the goal. Let me share it…
The Red List of a Web Developer is an attempt to briefly describe some of frameworks I have worked with to avoid repetition of mistakes I have done so far.
This document discusses refactoring legacy code projects. It begins by introducing the author and their experience with legacy projects. It then describes different types of legacy projects using nicknames. It discusses whether a project should be rewritten or refactored. It lists requirements needed for refactoring a legacy project. It compares a developer and customer perspective. It then provides examples of techniques that can be used when refactoring like building procedures, inversion of control, regular expressions, transaction management, and integrating incremental changes. The overall message is that refactoring legacy projects requires an open mindset, establishing trust between developers and customers, and taking problems step-by-step through small incremental changes.
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
The document discusses various approaches to refactoring legacy code, including:
1. Migrating from an older build system (TOM) to a newer one (POM) by updating XML configuration files.
2. Introducing inversion of control (IoC) and dependency injection (DI) to reduce tight coupling in the code.
3. Implementing aspect-oriented programming (AOP) to separate cross-cutting concerns like transaction management and exception handling.
4. Updating older libraries to newer versions for performance improvements and richer APIs.
5. Cleaning up messy and difficult to read code through techniques like extracting methods and using regular expressions.
3. Party PartyDef
id partyId
startTime
stopTime
Partici publicCode
PartyRole
pant
partyId
roleId Role
startTime id
stopTime publicCode
4. Order ProductDef
id productId
time Order startTime
inParty stopTime
inRole publicCode
outParty
outRole OrderItem
inPartyId orderId
inRoleId quantity
outPartyId productId Product
outRoleId product id
5. 1)Start-stop intervals must not overlap.
2)Entity exists only within start-stop interval.
3)Order must have valid and existent in party.
4)Order must have valid and existent out party.
5)Order must have valid and existent in role.
6)Order must have valid and existent out role.
7)Order items must have valid and existent
product.
8)Order in and out parties must not be the
same.
9)Order roles must be: (buyer, seller), (buyer,
repairer), (repairer, seller), (seller, buyer).
9. public void placeOrder(Order order) {
PartyDef ip = dao.findPartyBy(...);
if (ip == null) {
throw new Rule3Exception(...);
}
}
10. public void placeOrder(Order order) {
PartyDef ip = dao.findPartyBy(...);
if (ip == null) {
throw new Rule3Exception(...);
}
PartyDef op = dao.findPartyBy(...);
if (op == null) {
throw new Rule4Exception(...);
}
}
11. public void placeOrder(Order order) {
PartyDef ip = dao.findPartyBy(...);
if (ip == null) {
throw new Rule3Exception(...);
}
PartyDef op = dao.findPartyBy(...);
if (op == null) {
throw new Rule4Exception(...);
}
PartyRole ir = dao.findRoleBy(...);
if (ir == null) {
throw new Rule5Exception(...);
}
}
12. public void placeOrder(Order order) {
PartyDef ip = dao.findPartyBy(...);
assertRule3(ip);
PartyDef op = dao.findPartyBy(...);
assertRule4(op);
PartyRole ir = dao.findRoleBy(...);
assertRule5(ir);
}
13. public void placeOrder(Order order) {
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getValidatedByRule5(...);
}
14. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getValidatedByRule5(...); //???
}
15. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
if (ip != null) {
PartyRole ir = getValidatedByRule5(...);
}
}
16. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
if (ip != null) {
PartyRole ir = getValidatedByRule5(...);
}
if (op != null) {
PartyRole or = getValidatedByRule6(...);
}
}
17. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
if (ip != null) {
PartyRole ir = getValidatedByRule5(...);
}
if (op != null) {
PartyRole or = getValidatedByRule6(...);
}
if (ip != null && op != null && ip == op) {
problems.add(...); // Rule #8 violation
}
}
18. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getSafeValidatedByRule5(...);
PartyRole or = getSafeValidatedByRule6(...);
validateRule8(...);
}
19. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getSafeValidatedByRule5(...);
PartyRole or = getSafeValidatedByRule6(...);
validateRule8(...);
if (ir != null && or != null && (...)) {
problems.add(...); // Rule #9 violation
}
}
20. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getSafeValidatedByRule5(...);
PartyRole or = getSafeValidatedByRule6(...);
validateRule8(...);
validateRule9(...);
if (problems.isEmpty()) {
order.inPartyId = ip.partyId;
...
}
}
21. public void placeOrder(Order order) {
List<Problem> problems = …;
PartyDef ip = getValidatedByRule3(...);
PartyDef op = getValidatedByRule4(...);
PartyRole ir = getSafeValidatedByRule5(...);
PartyRole or = getSafeValidatedByRule6(...);
validateRule8(...);
validateRule9(...);
fillOrderIdentifications(...);
// TODO: Rule #7
}
49. Drools Rule Pattern
rule "Rule example" // Rule unique name
... // Rule attributes: grouping, priority, etc.
when
... // Left hand side. Condition.
then
... // Right hand side. Consequence.
end
66. package com.victor.drools
dialect "mvel"
import com.victor.drools.*; // optional
global GeneralDao dao;
global org.slf4j.Logger log;
declare Problem
orderId : long @key
ruleId : int @key
end
declare OIProblem extends Problem
product : String @key
end
67. Drools Class Declaration
declare ExampleClass // Class name
[extends ParentExampleClass] // Inheritance
@stringMetadata("I am String") // Metadata
@dateMetadata(01-Jan-1970)
propertyName1 : ValidType, // Properties
propertyName2 : AnotherValidType
68. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
70. rule "Function usage in LHS"
when
eval( hello("Victor")!="Hello Victor!" )
then
int faults = ++alexeyFaults.count;
log.fatal("Alexey, fix hello(..) function");
log.anger("You'd better be off");
log.info("You've broken it " +faults+ " time(s)");
end
71. rule "Function usage in RHS"
when
eval(true)
then
log.happiness(hello("Victor"));
log.worship(hello("Master"));
end
72. Drools Query Declaration
query "Orders with inParty"
$o : Order(inParty != null)
end
query "Orders with inRole equals to" (String
role)
$o : Order(inRole == role)
end
73. Drools Templates
template header
field1... // Template fields
template “TemplateName”
rule "ExampleRule_@{row.rowNumber}"
... // Usage of declared fields
end
end template
76. rule "Rule #3 violation"
when
$o : Order($id:id, $t:time, $pty:inParty)
not( Problem(orderId==$id, ruleId==3) )
eval( dao.findPartyBy($t, $pty)==null )
then
log.info("Rule #3 violated for the order: " + $id);
insert(new Problem($id, 3));
end
77. rule "Rule #3 violation"
when
Every Order
Without violations of rule 3
Which violates inParty constraints
then
Add the violation of the rule 3
end
78. [when] Every Order = $o : Order($id:id, $t:time,
$inPty:inParty)
[when] Without violations of rule {ruleNumber} =
not(Problem(orderId==$id, ruleId=={ruleNumber}))
[when] Which violates inParty constraints =
eval( dao.findPartyBy($t, $inPty) == null )
[then] Add the violation of the rule {ruleNumber} =
log.info("Rule #" + {ruleNumber} + " violated for
order: " + $id); insert(new Problem($id,
{ruleNumber}));
79. rule "Rule #4 violation"
when
Every Order
Without violations of rule 4
Which violates outParty constraints
then
Add the violation of the rule 4
end
80. [when] Every Order = $o : Order($id:id, $t:time,
$inPty:inParty)
[when] Without violations of rule {ruleNumber} =
not(Problem(orderId==$id, ruleId=={ruleNumber}))
[when] Which violates inParty constraints =
eval( dao.findPartyBy($t, $inPty) == null )
[then] Add the violation of the rule {ruleNumber} =
log.info("Rule #" + {ruleNumber} + " violated for
order: " + $id); insert(new Problem($id,
{ruleNumber}));
81. [when] Every Order = $o : Order($id:id, $t:time,
$inPty:inParty,$outPty:outParty)
[when] Without violations of rule {ruleNumber} =
not(Problem(orderId==$id, ruleId=={ruleNumber}))
[when] Which violates inParty constraints =
eval( dao.findPartyBy($t, $inPty) == null )
[when] Which violates outParty constraints =
eval( dao.findPartyBy($t, $outPty) == null )
[then] Add the violation of the rule {ruleNumber} =
log.info("Rule #" + {ruleNumber} + " violated for
order: " + $id); insert(new Problem($id,
{ruleNumber}));
83. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
84. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
85. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
86. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
87. rule "Rule #7 violation"
when
$o : Order(items!=null, $id:id, $t:time)
$item : OrderItem($prd:product) from $o.items
not( OIProblem(orderId==$id, ruleId==7,
product==$prd) )
eval(dao.findProductBy($t, $prd)==null)
then
log.info("Rule #7 violated for order: " + $id
+ " and product: " + $prd);
insert(new OIProblem($id, 7, $prd));
end
88. rule "Rule #7 violation"
when
Every Order
- which has items
And every OrderItem
Without violations of order item rule 7
Which violates product constraints
then
Add the violation of the rule 7 for the order item
end
89. [when] Every Order =
[when] Without violations of rule {N} =
[when] Which violates inParty constraints =
[when] Which violates outParty constraints =
[then] Add the violation of the rule {N} =
90. [when] Every Order =
[when] - which has items = items != null
[when] And every OrderItem =
[when] Without violations of rule {N} =
[when] Which violates inParty constraints =
[when] Which violates outParty constraints =
[when] Without violations of order item rule {N} =
[when] Which violates product constraints =
[then] Add the violation of the rule {N} for order
item =
[then] Add the violation of the rule {N} =
94. 1)Start-stop intervals must not overlap.
2)Entity exists only within start-stop interval.
3)Order must have valid and existent in party.
4)Order must have valid and existent out party.
5)Order must have valid and existent in role.
6)Order must have valid and existent out role.
7)Order items must have valid and existent
product.
8)Order in and out parties CAN be the same.
ONLY IF they have roles (seller, repairer).
9)Order roles must be: (buyer, seller), (buyer,
repairer), (repairer, seller), (seller, buyer). OR
(seller, repairer) if they are the same.
95. rule "Rule #8 violation"
when
$o : Order(
inPartyId != null, outPartyId != null,
outPartyId == inPartyId,
$id : id)
not( Problem(orderId == $id,
ruleId in (3, 4, 8)) )
then
log.info("Rule #8 violated for order: " + $id);
insert(new Problem($id, 8));
end
96. rule "Rule #8 violation"
when
$o : Order(!(inRole == "S" && outRole == "R"),
inPartyId != null, outPartyId != null,
outPartyId == inPartyId,
$id : id)
not( Problem(orderId == $id,
ruleId in (3, 4, 8)) )
then
log.info("Rule #8 violated for order: " + $id);
insert(new Problem($id, 8));
end
97. rule "Rule #8 violation"
when
Every Order
- with inPartyId
- with outPartyId
- where inPartyId equals outPartyId
- and inRole not "S" and outRole not "R"
Without violations of rules [3,4,8]
then
Add the violation of the rule 8
end
98. rule "Rule #8 exceptional case"
// salience 100
when
$o : Order(inRole == "S", outRole == "R",
inPartyId != null, outPartyId != null,
outPartyId == inPartyId,
$id : id)
then
log.info("Rule #8 special case for order: " +
$id);
insertLogical(new SkipRule($id, 8));
end
102. Rete Adapters/Eval
Entry Point Join
Object Type Not
Alpha Terminal
103. Rete
Entry Point Entry Point Node
Scope 1 EntryPointNode#1
Scope 2 EntryPointNode#2
Scope 3 EntryPointNode#3
104. Entry Point Node
Object Type Object Type Node
Order ObjectTypeNode#1
PartyDef ObjectTypeNode#2
Problem ObjectTypeNode#3
OIProblem ObjectTypeNode#4
105. Object Type Node (Order)
Fact Set
Order#112
Order#113
Order#114
Order#115
...
118. rule "Prefetch inParty PartyDef"
salience 100
when
Order(inParty!=null, $t:time, $pCode:inParty)
not( PartyDef(publicCode == $pCode,
startTime <= $t, stopTime > $t) )
then
PartyDef pd = dao.findPartyBy($t, $pCode);
log.info("insert party (if exists): " + pd);
insert(pd); // null won't be inserted
end
119. Hard to Test Inefficient
High Cost of Refactoring
Impossible Exception Handling
Can Change State Between Invocations
Usually Less Readable
Several More Rules to Support