Conjunctions & Disjunctions

Prolog – Conjunctions & Disjunctions ”; Previous Next In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax. Conjunction Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male. Disjunction Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true. Program parent(jhon,bob). parent(lili,bob). male(jhon). female(lili). % Conjunction Logic father(X,Y) :- parent(X,Y),male(X). mother(X,Y) :- parent(X,Y),female(X). % Disjunction Logic child_of(X,Y) :- father(X,Y);mother(X,Y). Output | ?- [conj_disj]. compiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code… D:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read – 1513 bytes written, 24 ms yes | ?- father(jhon,bob). yes | ?- child_of(jhon,bob). true ? yes | ?- child_of(lili,bob). yes | ?- Print Page Previous Next Advertisements ”;

Prolog – Examples of Cuts

Prolog – Examples of Cuts ”; Previous Next In this section, we will see some examples of cuts in prolog. Let us consider, we want to find the maximum of two elements. So we will check these two conditions. If X > Y, then Max := X if X <= Y, then Max := Y Now from these two lines, we can understand that these two statements are mutually exclusive, so when one is true, another one must be false. In such cases we can use the cut. So let us see the program. We can also define a predicate where we use the two cases using disjunction (OR logic). So when first one satisfies, it does not check for the second one, otherwise, it will check for the second statement. Program max(X,Y,X) :- X >= Y,!. max(X,Y,Y) :- X < Y. max_find(X,Y,Max) :- X >= Y,!, Max = X; Max = Y. Output | ?- [cut_example]. 1 1 Call: [cut_example] ? compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code… D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 3 lines read – 1195 bytes written, 43 ms 1 1 Exit: [cut_example] ? yes {trace} | ?- max(10,20,Max). 1 1 Call: max(10,20,_23) ? 2 2 Call: 10>=20 ? 2 2 Fail: 10>=20 ? 2 2 Call: 10<20 ? 2 2 Exit: 10<20 ? 1 1 Exit: max(10,20,20) ? Max = 20 yes {trace} | ?- max_find(20,10,Max). 1 1 Call: max_find(20,10,_23) ? 2 2 Call: 20>=10 ? 2 2 Exit: 20>=10 ? 1 1 Exit: max_find(20,10,20) ? Max = 20 yes {trace} | ?- Program Let us see another example, where we will use list. In this program we will try to insert an element into a list, if it is not present in the list before. And if the list has the element before we will simply cut it. For the membership checking also, if the item is at the head part, we should not check further, so cut it, otherwise check into the tail part. list_member(X,[X|_]) :- !. list_member(X,[_|TAIL]) :- list_member(X,TAIL). list_append(A,T,T) :- list_member(A,T),!. list_append(A,T,[A|T]). Output | ?- [cut_example]. compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code… D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 9 lines read – 1954 bytes written, 15 ms yes | ?- trace. The debugger will first creep — showing everything (trace) yes {trace} | ?- list_append(a,[a,b,c,d,e], L). 1 1 Call: list_append(a,[a,b,c,d,e],_33) ? 2 2 Call: list_member(a,[a,b,c,d,e]) ? 2 2 Exit: list_member(a,[a,b,c,d,e]) ? 1 1 Exit: list_append(a,[a,b,c,d,e],[a,b,c,d,e]) ? L = [a,b,c,d,e] yes {trace} | ?- list_append(k,[a,b,c,d,e], L). 1 1 Call: list_append(k,[a,b,c,d,e],_33) ? 2 2 Call: list_member(k,[a,b,c,d,e]) ? 3 3 Call: list_member(k,[b,c,d,e]) ? 4 4 Call: list_member(k,[c,d,e]) ? 5 5 Call: list_member(k,[d,e]) ? 6 6 Call: list_member(k,[e]) ? 7 7 Call: list_member(k,[]) ? 7 7 Fail: list_member(k,[]) ? 6 6 Fail: list_member(k,[e]) ? 5 5 Fail: list_member(k,[d,e]) ? 4 4 Fail: list_member(k,[c,d,e]) ? 3 3 Fail: list_member(k,[b,c,d,e]) ? 2 2 Fail: list_member(k,[a,b,c,d,e]) ? 1 1 Exit: list_append(k,[a,b,c,d,e],[k,a,b,c,d,e]) ? L = [k,a,b,c,d,e] (16 ms) yes {trace} | ?- Print Page Previous Next Advertisements ”;

Prolog – Backtracking

Prolog – Backtracking ”; Previous Next In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops. Let us see how backtracking takes place using one tree like structure − Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops. How Backtracking works? Now we know, what is the backtracking in Prolog. Let us see one example, Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop. Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules − Knowledge Base boy(tom). boy(bob). girl(alice). girl(lili). pay(X,Y) :- boy(X), girl(Y). Following is the illustration of the above scenario − As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working. Output | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code… D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read – 703 bytes written, 22 ms yes | ?- pay(X,Y). X = tom Y = alice ? (15 ms) yes | ?- pay(X,Y). X = tom Y = alice ? ; X = tom Y = lili ? ; X = bob Y = alice ? ; X = bob Y = lili yes | ?- trace. The debugger will first creep — showing everything (trace) (16 ms) yes {trace} | ?- pay(X,Y). 1 1 Call: pay(_23,_24) ? 2 2 Call: boy(_23) ? 2 2 Exit: boy(tom) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(tom,alice) ? X = tom Y = alice ? ; 1 1 Redo: pay(tom,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(tom,lili) ? X = tom Y = lili ? ; 1 1 Redo: pay(tom,lili) ? 2 2 Redo: boy(tom) ? 2 2 Exit: boy(bob) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(bob,alice) ? X = bob Y = alice ? ; 1 1 Redo: pay(bob,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(bob,lili) ? X = bob Y = lili yes {trace} | ?- Preventing Backtracking So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog. Suppose we have some rules as follows − Double step function Rule 1 &minnus; if X < 3 then Y = 0 Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2 Rule 3 &minnus; if 6 <= X then Y = 4 In Prolog syntax we can write, f(X,0) :- X < 3. % Rule 1 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 Now if we ask for a question as f (1,Y), 2 The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that − The three rules are mutually exclusive and one of them at most will succeed. As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail. So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows − f (X,0) :- X < 3, !. &percnt; Rule 1 f (X,2) :- 3 =< X, X < 6, !. &percnt; Rule 2 f (X,4) :- 6 =< X. &percnt; Rule 3 Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated. Let us see this in below execution − Program f(X,0) :- X < 3. &percnt; Rule 1 f(X,2) :- 3 =< X, X < 6. &percnt; Rule 2 f(X,4) :- 6 =< X. &percnt; Rule 3 Output | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code… D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read – 1224 bytes written, 17 ms yes | ?- f(1,Y), 2<Y. no | ?- trace . The debugger will first creep — showing everything (trace) yes {trace} | ?- f(1,Y), 2<Y. 1 1 Call: f(1,_23) ? 2 2 Call:

Prolog – Basics

Prolog – Basics ”; Previous Next In this chapter, we will gain some basic knowledge about Prolog. So we will move on to the first step of our Prolog Programming. The different topics that will be covered in this chapter are − Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail about the Knowledge Base, and how it helps in logic programming. Facts, Rules and Queries − These are the building blocks of logic programming. We will get some detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic programming. Here, we will discuss about the essential building blocks of logic programming. These building blocks are Facts, Rules and the Queries. Facts We can define fact as an explicit relationship between objects, and properties these objects might have. So facts are unconditionally true in nature. Suppose we have some facts as given below − Tom is a cat Kunal loves to eat Pasta Hair is black Nawaz loves to play games Pratyusha is lazy. So these are some facts, that are unconditionally true. These are actually statements, that we have to consider as true. Following are some guidelines to write facts − Names of properties/relationships begin with lower case letters. The relationship name appears as the first term. Objects appear as comma-separated arguments within parentheses. A period “.” must end a fact. Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’). phoneno(agnibha, 1122334455). is also called a predicate or clause. Syntax The syntax for facts is as follows − relation(object1,object2…). Example Following is an example of the above concept − cat(tom). loves_to_eat(kunal,pasta). of_color(hair,black). loves_to_play_games(nawaz). lazy(pratyusha). Rules We can define rule as an implicit relationship between objects. So facts are conditionally true. So when one associated condition is true, then the predicate is also true. Suppose we have some rules as given below − Lili is happy if she dances. Tom is hungry if he is searching for food. Jack and Bili are friends if both of them love to play cricket. will go to play if school is closed, and he is free. So these are some rules that are conditionally true, so when the right hand side is true, then the left hand side is also true. Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol, the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,) which is known as conjunction, and we can also use semicolon, that is known as disjunction. Syntax rule_name(object1, object2, …) :- fact/rule(object1, object2, …) Suppose a clause is like : P :- Q;R. This can also be written as P :- Q. P :- R. If one clause is like : P :- Q,R;S,T,U. Is understood as P :- (Q,R);(S,T,U). Or can also be written as: P :- Q,R. P :- S,T,U. Example happy(lili) :- dances(lili). hungry(tom) :- search_for_food(tom). friends(jack, bili) :- lovesCricket(jack), lovesCricket(bili). goToPlay(ryan) :- isClosed(school), free(ryan). Queries Queries are some questions on the relationships between objects and object properties. So question can be anything, as given below − Is tom a cat? Does Kunal love to eat pasta? Is Lili happy? Will Ryan go to play? So according to these queries, Logic programming language can find the answer and return them. Knowledge Base in Logic Programming In this section, we will see what knowledge base in logic programming is. Well, as we know there are three main components in logic programming − Facts, Rules and Queries. Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we can say that the knowledge base is a collection of facts and rules. Now, we will see how to write some knowledge bases. Suppose we have our very first knowledge base called KB1. Here in the KB1, we have some facts. The facts are used to state things, that are unconditionally true of the domain of interest. Knowledge Base 1 Suppose we have some knowledge, that Priya, Tiyasha, and Jaya are three girls, among them, Priya can cook. Let’s try to write these facts in a more generic way as shown below − girl(priya). girl(tiyasha). girl(jaya). can_cook(priya). Note − Here we have written the name in lowercase letters, because in Prolog, a string starting with uppercase letter indicates a variable. Now we can use this knowledge base by posing some queries. “Is priya a girl?”, it will reply “yes”, “is jamini a girl?” then it will answer “No”, because it does not know who jamini is. Our next question is “Can Priya cook?”, it will say “yes”, but if we ask the same question for Jaya, it will say “No”. Output GNU Prolog 1.4.5 (64 bits) Compiled Jul 14 2018, 13:19:42 with x86_64-w64-mingw32-gcc By Daniel Diaz Copyright (C) 1999-2018 Daniel Diaz | ?- change_directory(”D:/TP Prolog/Sample_Codes”). yes | ?- [kb1] . compiling D:/TP Prolog/Sample_Codes/kb1.pl for byte code… D:/TP Prolog/Sample_Codes/kb1.pl compiled, 3 lines read – 489 bytes written, 10 ms yes | ?- girl(priya) . yes | ?- girl(jamini). no | ?- can_cook(priya). yes | ?- can_cook(jaya). no | ?- Let us see another knowledge base, where we have some rules. Rules contain some information that are conditionally true about the domain of interest. Suppose our knowledge base is as follows − sing_a_song(ananya). listens_to_music(rohit). listens_to_music(ananya) :- sing_a_song(ananya). happy(ananya) :- sing_a_song(ananya). happy(rohit) :- listens_to_music(rohit). playes_guitar(rohit) :- listens_to_music(rohit). So there are some facts and rules given above. The first two are facts, but the rest are rules. As we know that Ananya sings a song, this implies she also listens to

Ruby – Ruby/XML, XSLT

Ruby – XML, XSLT and XPath Tutorial ”; Previous Next What is XML? The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone. XML Parser Architectures and APIs There are two different flavors available for XML parsers − SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory. DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX obviously can”t process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files. SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can”t use them both for large projects. Parsing and Creating XML using Ruby The most common way to manipulate XML is with the REXML library by Sean Russell. Since 2002, REXML has been part of the standard Ruby distribution. REXML is a pure-Ruby XML processor conforming to the XML 1.0 standard. It is a non-validating processor, passing all of the OASIS non-validating conformance tests. REXML parser has the following advantages over other available parsers − It is written 100 percent in Ruby. It can be used for both SAX and DOM parsing. It is lightweight, less than 2000 lines of code. Methods and classes are really easy-to-understand. SAX2-based API and Full XPath support. Shipped with Ruby installation and no separate installation is required. For all our XML code examples, let”s use a simple XML file as an input − <collection shelf = “New Arrivals”> <movie title = “Enemy Behind”> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = “Transformers”> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = “Trigun”> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title = “Ishtar”> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> DOM-like Parsing Let”s first parse our XML data in tree fashion. We begin by requiring the rexml/document library; often we do an include REXML to import into the top-level namespace for convenience. #!/usr/bin/ruby -w require ”rexml/document” include REXML xmlfile = File.new(“movies.xml”) xmldoc = Document.new(xmlfile) # Now get the root element root = xmldoc.root puts “Root element : ” + root.attributes[“shelf”] # This will output all the movie titles. xmldoc.elements.each(“collection/movie”){ |e| puts “Movie Title : ” + e.attributes[“title”] } # This will output all the movie types. xmldoc.elements.each(“collection/movie/type”) { |e| puts “Movie Type : ” + e.text } # This will output all the movie description. xmldoc.elements.each(“collection/movie/description”) { |e| puts “Movie Description : ” + e.text } This will produce the following result − Root element : New Arrivals Movie Title : Enemy Behind Movie Title : Transformers Movie Title : Trigun Movie Title : Ishtar Movie Type : War, Thriller Movie Type : Anime, Science Fiction Movie Type : Anime, Action Movie Type : Comedy Movie Description : Talk about a US-Japan war Movie Description : A schientific fiction Movie Description : Vash the Stampede! Movie Description : Viewable boredom SAX-like Parsing To process the same data, movies.xml, file in a stream-oriented way we will define a listener class whose methods will be the target of callbacks from the parser. NOTE − It is not suggested to use SAX-like parsing for a small file, this is just for a demo example. #!/usr/bin/ruby -w require ”rexml/document” require ”rexml/streamlistener” include REXML class MyListener include REXML::StreamListener def tag_start(*args) puts “tag_start: #{args.map {|x| x.inspect}.join(”, ”)}” end def text(data) return if data =~ /^w*$/ # whitespace only abbrev = data[0..40] + (data.length > 40 ? “…” : “”) puts ” text : #{abbrev.inspect}” end end list = MyListener.new xmlfile = File.new(“movies.xml”) Document.parse_stream(xmlfile, list) This will produce the following result − tag_start: “collection”, {“shelf”=>”New Arrivals”} tag_start: “movie”, {“title”=>”Enemy Behind”} tag_start: “type”, {} text : “War, Thriller” tag_start: “format”, {} tag_start: “year”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Talk about a US-Japan war” tag_start: “movie”, {“title”=>”Transformers”} tag_start: “type”, {} text : “Anime, Science Fiction” tag_start: “format”, {} tag_start: “year”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “A schientific fiction” tag_start: “movie”, {“title”=>”Trigun”} tag_start: “type”, {} text : “Anime, Action” tag_start: “format”, {} tag_start: “episodes”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Vash the Stampede!” tag_start: “movie”, {“title”=>”Ishtar”} tag_start: “type”, {} tag_start: “format”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Viewable boredom” XPath and Ruby An alternative way to view XML is XPath. This is a kind of pseudo-language that describes how to locate specific elements and attributes in an XML document, treating that document as a logical ordered tree. REXML has XPath support via the XPath class. It assumes tree-based parsing (document object model) as we have seen above. #!/usr/bin/ruby -w require ”rexml/document” include REXML xmlfile = File.new(“movies.xml”) xmldoc = Document.new(xmlfile) # Info for the first movie found movie = XPath.first(xmldoc, “//movie”) p movie # Print out all the movie types XPath.each(xmldoc, “//type”) { |e| puts e.text } # Get an array of all of the movie formats. names = XPath.match(xmldoc, “//format”).map {|x| x.text } p

Ruby – Web Services

Web Services with Ruby – SOAP4R ”; Previous Next What is SOAP? The Simple Object Access Protocol (SOAP), is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP. It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa. SOAP has several advantages over other technologies like COM, CORBA etc: for example, its relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence of several implementations for different languages and platforms. Please refer to our simple tutorial SOAP to understand it in detail. This chapter makes you familiar with the SOAP implementation for Ruby (SOAP4R). This is a basic tutorial, so if you need a deep detail, you would need to refer other resources. Installing SOAP4R SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be downloaded from − NOTE − There may be a great chance that you already have installed this component. Download SOAP If you are aware of gem utility then you can use the following command to install SOAP4R and related packages. $ gem install soap4r –include-dependencies If you are working on Windows, then you need to download a zipped file from the above location and need to install it using the standard installation method by running ruby install.rb. Writing SOAP4R Servers SOAP4R supports two different types of servers − CGI/FastCGI based (SOAP::RPC::CGIStub) Standalone (SOAP::RPC:StandaloneServer) This chapter gives detail on writing a stand alone server. The following steps are involved in writing a SOAP server. Step 1 – Inherit SOAP::RPC::StandaloneServer Class To implement your own stand alone server you need to write a new class, which will be child of SOAP::StandaloneServer as follows − class MyServer < SOAP::RPC::StandaloneServer …………… end NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as parent class, rest of the procedure will remain the same. Step 2 – Define Handler Methods Second step is to write your Web Services methods, which you would like to expose to the outside world. They can be written as simple Ruby methods. For example, let”s write two methods to add two numbers and divide two numbers − class MyServer < SOAP::RPC::StandaloneServer …………… # Handler methods def add(a, b) return a &plus; b end def div(a, b) return a / b end end Step 3 – Expose Handler Methods Next step is to add our defined methods to our server. The initialize method is used to expose service methods with one of the two following methods − class MyServer < SOAP::RPC::StandaloneServer def initialize(*args) add_method(receiver, methodName, *paramArg) end end Here is the description of the parameters − Sr.No. Parameter & Description 1 receiver The object that contains the methodName method. You define the service methods in the same class as the methodDef method, this parameter is self. 2 methodName The name of the method that is called due to an RPC request. 3 paramArg Specifies, when given, the parameter names and parameter modes. To understand the usage of inout or out parameters, consider the following service method that takes two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further parameters: inoutParam and outParam − def aMeth(inParam, inoutParam) retVal = inParam &plus; inoutParam outParam = inParam . inoutParam inoutParam = inParam * inoutParam return retVal, inoutParam, outParam end Now, we can expose this method as follows − add_method(self, ”aMeth”, [ %w(in inParam), %w(inout inoutParam), %w(out outParam), %w(retval return) ]) Step 4 – Start the Server The final step is to start your server by instantiating one instance of the derived class and calling start method. myServer = MyServer.new(”ServerName”, ”urn:ruby:ServiceName”, hostname, port) myServer.start Here is the description of required parameters − Sr.No. Parameter & Description 1 ServerName A server name, you can give what you like most. 2 urn:ruby:ServiceName Here urn:ruby is constant but you can give a unique ServiceName name for this server. 3 hostname Specifies the hostname on which this server will listen. 4 port An available port number to be used for the web service. Example Now, using the above steps, let us write one standalone server − require “soap/rpc/standaloneserver” begin class MyServer < SOAP::RPC::StandaloneServer # Expose our services def initialize(*args) add_method(self, ”add”, ”a”, ”b”) add_method(self, ”div”, ”a”, ”b”) end # Handler methods def add(a, b) return a &plus; b end def div(a, b) return a / b end end server = MyServer.new(“MyServer”, ”urn:ruby:calculation”, ”localhost”, 8080) trap(”INT){ server.shutdown } server.start rescue => err puts err.message end When executed, this server application starts a standalone SOAP server on localhost and listens for requests on port 8080. It exposes one service methods, add and div, which takes two parameters and return the result. Now, you can run this server in background as follows − $ ruby MyServer.rb& Writing SOAP4R Clients The SOAP::RPC::Driver class provides support for writing SOAP client applications. This chapter describes this class and demonstrate its usage on the basis of an application. Following is the bare minimum information you would need to call a SOAP service − The URL of the SOAP service (SOAP Endpoint URL). The namespace of the service methods (Method Namespace URI). The names of the service methods and their parameters. Now, we will write a SOAP client which would call service methods defined in above example, named add and div. Here are the main steps to create a SOAP client. Step 1 – Create a SOAP Driver Instance We create an instance of SOAP::RPC::Driver by calling its new method as follows − SOAP::RPC::Driver.new(endPoint, nameSpace, soapAction) Here is the description of required parameters − Sr.No. Parameter & Description 1 endPoint URL of the SOAP server to connect with. 2 nameSpace The namespace to use for all RPCs done with this SOAP::RPC::Driver object. 3 soapAction A value for the SOAPAction field of the HTTP header. If nil this defaults to the empty string “”. Step 2

Ruby – Multithreading

Ruby – Multithreading ”; Previous Next Traditional programs have a single thread of execution the statements or instructions that comprise the program are executed sequentially until the program terminates. A multithreaded program has more than one thread of execution. Within each thread, statements are executed sequentially, but the threads themselves may be executed in parallel on a multicore CPU, for example. Often on a single CPU machine, multiple threads are not actually executed in parallel, but parallelism is simulated by interleaving the execution of the threads. Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code. Creating Ruby Threads To start a new thread, just associate a block with a call to Thread.new. A new thread will be created to execute the code in the block, and the original thread will return from Thread.new immediately and resume execution with the next statement − # Thread #1 is running here Thread.new { # Thread #2 runs this code } # Thread #1 runs this code Example Here is an example, which shows how we can use multi-threaded Ruby program. #!/usr/bin/ruby def func1 i = 0 while i<=2 puts “func1 at: #{Time.now}” sleep(2) i = i&plus;1 end end def func2 j = 0 while j<=2 puts “func2 at: #{Time.now}” sleep(1) j = j&plus;1 end end puts “Started At #{Time.now}” t1 = Thread.new{func1()} t2 = Thread.new{func2()} t1.join t2.join puts “End at #{Time.now}” This will produce following result − Started At Wed May 14 08:21:54 -0700 2008 func1 at: Wed May 14 08:21:54 -0700 2008 func2 at: Wed May 14 08:21:54 -0700 2008 func2 at: Wed May 14 08:21:55 -0700 2008 func1 at: Wed May 14 08:21:56 -0700 2008 func2 at: Wed May 14 08:21:56 -0700 2008 func1 at: Wed May 14 08:21:58 -0700 2008 End at Wed May 14 08:22:00 -0700 2008 Thread Lifecycle A new threads are created with Thread.new. You can also use the synonyms Thread.start and Thread.fork. There is no need to start a thread after creating it, it begins running automatically when CPU resources become available. The Thread class defines a number of methods to query and manipulate the thread while it is running. A thread runs the code in the block associated with the call to Thread.new and then it stops running. The value of the last expression in that block is the value of the thread, and can be obtained by calling the value method of the Thread object. If the thread has run to completion, then the value returns the thread”s value right away. Otherwise, the value method blocks and does not return until the thread has completed. The class method Thread.current returns the Thread object that represents the current thread. This allows threads to manipulate themselves. The class method Thread.main returns the Thread object that represents the main thread. This is the initial thread of execution that began when the Ruby program was started. You can wait for a particular thread to finish by calling that thread”s Thread.join method. The calling thread will block until the given thread is finished. Threads and Exceptions If an exception is raised in the main thread, and is not handled anywhere, the Ruby interpreter prints a message and exits. In threads, other than the main thread, unhandled exceptions cause the thread to stop running. If a thread t exits because of an unhandled exception, and another thread s calls t.join or t.value, then the exception that occurred in t is raised in the thread s. If Thread.abort_on_exception is false, the default condition, an unhandled exception simply kills the current thread and all the rest continue to run. If you would like any unhandled exception in any thread to cause the interpreter to exit, set the class method Thread.abort_on_exception to true. t = Thread.new { … } t.abort_on_exception = true Thread Variables A thread can normally access any variables that are in scope when the thread is created. Variables local to the block of a thread are local to the thread, and are not shared. Thread class features a special facility that allows thread-local variables to be created and accessed by name. You simply treat the thread object as if it were a Hash, writing to elements using []= and reading them back using []. In this example, each thread records the current value of the variable count in a threadlocal variable with the key mycount. Live Demo #!/usr/bin/ruby count = 0 arr = [] 10.times do |i| arr[i] = Thread.new { sleep(rand(0)/10.0) Thread.current[“mycount”] = count count &plus;= 1 } end arr.each {|t| t.join; print t[“mycount”], “, ” } puts “count = #{count}” This produces the following result − 8, 0, 3, 7, 2, 1, 6, 5, 4, 9, count = 10 The main thread waits for the subthreads to finish and then prints out the value of count captured by each. Thread Priorities The first factor that affects the thread scheduling is the thread priority: high-priority threads are scheduled before low-priority threads. More precisely, a thread will only get CPU time if there are no higher-priority threads waiting to run. You can set and query the priority of a Ruby Thread object with priority = and priority. A newly created thread starts at the same priority as the thread that created it. The main thread starts off at priority 0. There is no way to set the priority of a thread before it starts running. A thread can, however, raise or lower its own priority as the first action it takes. Thread Exclusion If two threads share access to the same data, and at least one of the threads modifies that data, you must take special care to ensure that no thread can ever see the data in an inconsistent state. This is called thread exclusion. Mutex is a class that implements a simple semaphore lock for mutually exclusive access to some shared resource. That is, only one thread

Prolog – Introduction

Prolog – Introduction ”; Previous Next Prolog as the name itself suggests, is the short form of LOGical PROgramming. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is. Logic Programming is one of the Computer Programming Paradigm, in which the program statements express the facts and rules about different problems within a system of formal logic. Here, the rules are written in the form of logical clauses, where head and body are present. For example, H is head and B1, B2, B3 are the elements of the body. Now if we state that “H is true, when B1, B2, B3 all are true”, this is a rule. On the other hand, facts are like the rules, but without any body. So, an example of fact is “H is true”. Some logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely declarative languages. These languages allow statements about what the program should accomplish. There is no such step-by-step instruction on how to perform the task. However, other languages like Prolog, have declarative and also imperative properties. This may also include procedural statements like “To solve the problem H, perform B1, B2 and B3”. Some logic programming languages are given below − ALF (algebraic logic functional programming language). ASP (Answer Set Programming) CycL Datalog FuzzyCLIPS Janus Parlog Prolog Prolog++ ROOP Logic and Functional Programming We will discuss about the differences between Logic programming and the traditional functional programming languages. We can illustrate these two using the below diagram − From this illustration, we can see that in Functional Programming, we have to define the procedures, and the rule how the procedures work. These procedures work step by step to solve one specific problem based on the algorithm. On the other hand, for the Logic Programming, we will provide knowledge base. Using this knowledge base, the machine can find answers to the given questions, which is totally different from functional programming. In functional programming, we have to mention how one problem can be solved, but in logic programming we have to specify for which problem we actually want the solution. Then the logic programming automatically finds a suitable solution that will help us solve that specific problem. Now let us see some more differences below − Functional Programming Logic Programming Functional Programming follows the Von-Neumann Architecture, or uses the sequential steps. Logic Programming uses abstract model, or deals with objects and their relationships. The syntax is actually the sequence of statements like (a, s, I). The syntax is basically the logic formulae (Horn Clauses). The computation takes part by executing the statements sequentially. It computes by deducting the clauses. Logic and controls are mixed together. Logics and controls can be separated. What is Prolog? Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. This is the main reason to use Prolog as the programming language in Artificial Intelligence, where symbol manipulation and inference manipulation are the fundamental tasks. In Prolog, we need not mention the way how one problem can be solved, we just need to mention what the problem is, so that Prolog automatically solves it. However, in Prolog we are supposed to give clues as the solution method. Prolog language basically has three different elements − Facts − The fact is predicate that is true, for example, if we say, “Tom is the son of Jack”, then this is a fact. Rules − Rules are extinctions of facts that contain conditional clauses. To satisfy a rule these conditions should be met. For example, if we define a rule as − grandfather(X, Y) :- father(X, Z), parent(Z, Y) This implies that for X to be the grandfather of Y, Z should be a parent of Y and X should be father of Z. Questions − And to run a prolog program, we need some questions, and those questions can be answered by the given facts and rules. History of Prolog The heritage of prolog includes the research on theorem provers and some other automated deduction system that were developed in 1960s and 1970s. The Inference mechanism of the Prolog is based on Robinson’s Resolution Principle, that was proposed in 1965, and Answer extracting mechanism by Green (1968). These ideas came together forcefully with the advent of linear resolution procedures. The explicit goal-directed linear resolution procedures, gave impetus to the development of a general purpose logic programming system. The first Prolog was the Marseille Prolog based on the work by Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter (Roussel, 1975) was the first detailed description of the Prolog language. Prolog is also considered as a fourth generation programming language supporting the declarative programming paradigm. The well-known Japanese Fifth-Generation Computer Project, that was announced in 1981, adopted Prolog as a development language, and thereby grabbed considerable attention on the language and its capabilities. Some Applications of Prolog Prolog is used in various domains. It plays a vital role in automation system. Following are some other important fields where Prolog is used − Intelligent Database Retrieval Natural Language Understanding Specification Language Machine Learning Robot Planning Automation System Problem Solving Print Page Previous Next Advertisements ”;

Loop & Decision Making

Prolog – Loop & Decision Making ”; Previous Next In this chapter, we will discuss loops and decision making in Prolog. Loops Loop statements are used to execute the code block multiple times. In general, for, while, do-while are loop constructs in programming languages (like Java, C, C++). Code block is executed multiple times using recursive predicate logic. There are no direct loops in some other languages, but we can simulate loops with few different techniques. Program count_to_10(10) :- write(10),nl. count_to_10(X) :- write(X),nl, Y is X + 1, count_to_10(Y). Output | ?- [loop]. compiling D:/TP Prolog/Sample_Codes/loop.pl for byte code… D:/TP Prolog/Sample_Codes/loop.pl compiled, 4 lines read – 751 bytes written, 16 ms (16 ms) yes | ?- count_to_10(3). 3 4 5 6 7 8 9 10 true ? yes | ?- Now create a loop that takes lowest and highest values. So, we can use the between() to simulate loops. Program Let us see an example program − count_down(L, H) :- between(L, H, Y), Z is H – Y, write(Z), nl. count_up(L, H) :- between(L, H, Y), Z is L + Y, write(Z), nl. Output | ?- [loop]. compiling D:/TP Prolog/Sample_Codes/loop.pl for byte code… D:/TP Prolog/Sample_Codes/loop.pl compiled, 14 lines read – 1700 bytes written, 16 ms yes | ?- count_down(12,17). 5 true ? ; 4 true ? ; 3 true ? ; 2 true ? ; 1 true ? ; 0 yes | ?- count_up(5,12). 10 true ? ; 11 true ? ; 12 true ? ; 13 true ? ; 14 true ? ; 15 true ? ; 16 true ? ; 17 yes | ?- Decision Making The decision statements are If-Then-Else statements. So when we try to match some condition, and perform some task, then we use the decision making statements. The basic usage is as follows − If <condition> is true, Then <do this>, Else In some different programming languages, there are If-Else statements, but in Prolog we have to define our statements in some other manner. Following is an example of decision making in Prolog. Program % If-Then-Else statement gt(X,Y) :- X >= Y,write(”X is greater or equal”). gt(X,Y) :- X < Y,write(”X is smaller”). % If-Elif-Else statement gte(X,Y) :- X > Y,write(”X is greater”). gte(X,Y) :- X =:= Y,write(”X and Y are same”). gte(X,Y) :- X < Y,write(”X is smaller”). Output | ?- [test]. compiling D:/TP Prolog/Sample_Codes/test.pl for byte code… D:/TP Prolog/Sample_Codes/test.pl compiled, 3 lines read – 529 bytes written, 15 ms yes | ?- gt(10,100). X is smaller yes | ?- gt(150,100). X is greater or equal true ? yes | ?- gte(10,20). X is smaller (15 ms) yes | ?- gte(100,20). X is greater true ? yes | ?- gte(100,100). X and Y are same true ? yes | ?- Print Page Previous Next Advertisements ”;

Ruby – Sending Email

Sending Email using Ruby – SMTP ”; Previous Next Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Ruby provides Net::SMTP class for Simple Mail Transfer Protocol (SMTP) client-side connection and provides two class methods new and start. The new takes two parameters − The server name defaulting to localhost. The port number defaulting to the well-known port 25. The start method takes these parameters − The server − IP name of the SMTP server, defaulting to localhost. The port − Port number, defaulting to 25. The domain − Domain of the mail sender, defaulting to ENV[“HOSTNAME”]. The account − Username, default is nil. The password − User password, defaulting to nil. The authtype − Authorization type, defaulting to cram_md5. An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters − The source − A string or array or anything with an each iterator returning one string at a time. The sender − A string that will appear in the from field of the email. The recipients − A string or an array of strings representing the recipients” addressee(s). Example Here is a simple way to send one email using Ruby script. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me&commat;fromdomain.com> To: A Test User <test&commat;todomain.com> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me&commat;fromdomain.com”, ”test&commat;todomain.com” end Here, you have placed a basic e-mail in message, using a document, taking care to format the headers correctly. E-mails require a From, To, and Subject header, separated from the body of the e-mail with a blank line. To send the mail you use Net::SMTP to connect to the SMTP server on the local machine and then use the send_message method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren”t always used to route mail). If you”re not running an SMTP server on your machine, you can use the Net::SMTP to communicate with a remote SMTP server. Unless you”re using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply to Net::SMTP, as follows − Net::SMTP.start(”mail.your-domain.com”) This line of code connects to the SMTP server on port 25 of mail.your-domain.com without using any username or password. If you need to, though, you can specify port number and other details. For example − Net::SMTP.start(”mail.your-domain.com”, 25, ”localhost”, ”username”, ”password” :plain) This example connects to the SMTP server at mail.your-domain.com using a username and password in plain text format. It identifies the client”s hostname as localhost. Sending an HTML e-mail using Ruby When you send a text message using Ruby then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Ruby Net::SMTP provides option to send an HTML message as actual HTML message. While sending an email message you can specify a Mime version, content type and character set to send an HTML email. Example Following is the example to send HTML content as an email. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me&commat;fromdomain.com> To: A Test User <test&commat;todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me&commat;fromdomain.com”, ”test&commat;todomain.com” end Sending Attachments as an e-mail To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the email. A final boundary denoting the email”s final section must also end with two hyphens. Attached files should be encoded with the pack(“m”) function to have base64 encoding before transmission. Example Following is the example, which will send a file /tmp/test.txt as an attachment. require ”net/smtp” filename = “/tmp/test.txt” # Read a file and encode it into base64 format filecontent = File.read(filename) encodedcontent = [filecontent].pack(“m”) # base64 marker = “AUNIQUEMARKER” body = <<EOF This is a test email to send an attachement. EOF # Define the main headers. part1 = <<EOF From: Private Person <me&commat;fromdomain.net> To: A Test User <test&commat;todmain.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary = #{marker} –#{marker} EOF # Define the message action part2 = <<EOF Content-Type: text/plain Content-Transfer-Encoding:8bit #{body} –#{marker} EOF # Define the attachment section part3 = <<EOF Content-Type: multipart/mixed; name = “#{filename}” Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename = “#{filename}” #{encodedcontent} –#{marker}– EOF mailtext = part1 &plus; part2 &plus; part3 # Let”s put our code in safe area begin Net::SMTP.start(”localhost”) do |smtp| smtp.sendmail(mailtext, ”me&commat;fromdomain.net”, [”test&commat;todmain.com”]) end rescue Exception => e print “Exception occured: ” &plus; e end NOTE − You can specify multiple destinations inside the array but they should be separated by comma. Print Page Previous Next Advertisements ”;