Rosetta Code/Count examples: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: bad link)
m (syntax highlighting fixup automation)
Line 18: Line 18:
{{libheader|AWS}}
{{libheader|AWS}}
Parsing XML file with XMLAda from AdaCore
Parsing XML file with XMLAda from AdaCore
<lang Ada>with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
<syntaxhighlight lang="ada">with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
Line 119: Line 119:
Put_Line ("Total :" & Integer'Image (Total) & " exemples.");
Put_Line ("Total :" & Integer'Image (Total) & " exemples.");
end Count_Examples;
end Count_Examples;
</syntaxhighlight>
</lang>
Output :
Output :
<pre>
<pre>
Line 130: Line 130:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>UrlDownloadToFile
<syntaxhighlight lang="autohotkey">UrlDownloadToFile
, http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml
, http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml
, tasks.xml
, tasks.xml
Line 149: Line 149:
}
}
MsgBox % output
MsgBox % output
Return</lang>
Return</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support
<syntaxhighlight lang="bbcbasic"> VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
Line 236: Line 236:
WHEN "&quot;": = """"
WHEN "&quot;": = """"
ENDCASE
ENDCASE
= h$</lang>
= h$</syntaxhighlight>
'''Sample output:'''
'''Sample output:'''
<pre>
<pre>
Line 265: Line 265:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( get-page
<syntaxhighlight lang="bracmat">( ( get-page
=
=
. sys$(str$("wget -q -O wget.out \"" !arg \"))
. sys$(str$("wget -q -O wget.out \"" !arg \"))
Line 305: Line 305:
)
)
& lst$(list,taskfreq,NEW)
& lst$(list,taskfreq,NEW)
)</lang>
)</syntaxhighlight>
Output (in file <code>tasqfreq</code>):
Output (in file <code>tasqfreq</code>):
<pre>list=
<pre>list=
Line 353: Line 353:
Object-oriented solution.
Object-oriented solution.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 412: Line 412:
Console.WriteLine("\nTotal: {0} examples.", tasks.Select(x => x.Examples).Sum());
Console.WriteLine("\nTotal: {0} examples.", tasks.Select(x => x.Examples).Sum());
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(ns count-examples
<syntaxhighlight lang="clojure">(ns count-examples
(:import [java.net URLEncoder])
(:import [java.net URLEncoder])
(:use [clojure.contrib.http.agent :only (http-agent string)]
(:use [clojure.contrib.http.agent :only (http-agent string)]
Line 454: Line 454:
(flush))
(flush))
(println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
(println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
</syntaxhighlight>
</lang>
<lang clojure>count-examples> (print-result)
<syntaxhighlight lang="clojure">count-examples> (print-result)
100 doors: 73
100 doors: 73
24 game: 18
24 game: 18
Line 471: Line 471:
Total: 11216
Total: 11216
nil
nil
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
{{works with|Tango}}
{{works with|Tango}}
<syntaxhighlight lang="d">
<lang D>
import tango.io.Stdout;
import tango.io.Stdout;
import tango.net.http.HttpClient;
import tango.net.http.HttpClient;
Line 524: Line 524:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|EGL}}==
=={{header|EGL}}==
Line 532: Line 532:


User Interface: RosettaCodeHandler.egl
User Interface: RosettaCodeHandler.egl
<lang EGL>package com.eglexamples.client;
<syntaxhighlight lang="egl">package com.eglexamples.client;


import org.eclipse.edt.rui.widgets.*;
import org.eclipse.edt.rui.widgets.*;
Line 607: Line 607:
title string;
title string;
count int;
count int;
end</lang>
end</syntaxhighlight>


Service Interface: ProxyFunctions.egl
Service Interface: ProxyFunctions.egl
<lang EGL>package com.eglexamples.client;
<syntaxhighlight lang="egl">package com.eglexamples.client;


library ProxyFunctions
library ProxyFunctions
Line 646: Line 646:
record QueryContinue
record QueryContinue
categorymembers Categorymembers;
categorymembers Categorymembers;
end</lang>
end</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 652: Line 652:
{{libheader|xmerl}}
{{libheader|xmerl}}


<lang erlang>
<syntaxhighlight lang="erlang">
-module(rosseta_examples).
-module(rosseta_examples).
-include_lib("xmerl/include/xmerl.hrl").
-include_lib("xmerl/include/xmerl.hrl").
Line 715: Line 715:
replace_chars([],Acc) ->
replace_chars([],Acc) ->
lists:reverse(Acc).
lists:reverse(Acc).
</syntaxhighlight>
</lang>




Line 735: Line 735:
Using asynchronous workflows to perform downloads concurrently:
Using asynchronous workflows to perform downloads concurrently:


<lang fsharp>#r "System.Xml.Linq.dll"
<syntaxhighlight lang="fsharp">#r "System.Xml.Linq.dll"


let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
Line 752: Line 752:
|> Async.Parallel
|> Async.Parallel
|> Async.RunSynchronously
|> Async.RunSynchronously
|> fun xs -> printfn "Total: %d examples" (Seq.sum xs)</lang>
|> fun xs -> printfn "Total: %d examples" (Seq.sum xs)</syntaxhighlight>


This is 21&#215; faster than the python thanks to the concurrency.
This is 21&#215; faster than the python thanks to the concurrency.
Line 759: Line 759:
Runs in about a minute. The number of threads is limited to 10 avoid cloudfare's protection mechanism.
Runs in about a minute. The number of threads is limited to 10 avoid cloudfare's protection mechanism.


<lang factor>USING: arrays assocs concurrency.combinators
<syntaxhighlight lang="factor">USING: arrays assocs concurrency.combinators
concurrency.semaphores formatting hashtables http.client io
concurrency.semaphores formatting hashtables http.client io
json.reader kernel math math.parser sequences splitting
json.reader kernel math math.parser sequences splitting
Line 800: Line 800:
all-programming-titles fetch-counts print-counts ;
all-programming-titles fetch-counts print-counts ;


MAIN: rosetta-examples</lang>
MAIN: rosetta-examples</syntaxhighlight>
Outputs:
Outputs:


Line 812: Line 812:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 886: Line 886:
fmt.Printf("%s: %d\n", cm, examples)
fmt.Printf("%s: %d\n", cm, examples)
total += examples
total += examples
}</lang>
}</syntaxhighlight>
{{out|Output: (May 25, 2011)}}
{{out|Output: (May 25, 2011)}}
<pre>
<pre>
Line 900: Line 900:
{{libheader|HTTP XML}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
{{libheader|HTTP XML}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]


<lang haskell>import Network.Browser
<syntaxhighlight lang="haskell">import Network.Browser
import Network.HTTP
import Network.HTTP
import Network.URI
import Network.URI
Line 936: Line 936:


mapM_ putStrLn $ zipWith showFormatted tasks ns
mapM_ putStrLn $ zipWith showFormatted tasks ns
putStrLn $ ("Total: " ++) $ show tot</lang>
putStrLn $ ("Total: " ++) $ show tot</syntaxhighlight>
some output:
some output:
<lang haskell>*Main> progTaskExamples
<syntaxhighlight lang="haskell">*Main> progTaskExamples
100 doors: 56
100 doors: 56
24 game: 11
24 game: 11
Line 947: Line 947:
Active object: 9
Active object: 9
...
...
Total: 9156</lang>
Total: 9156</syntaxhighlight>


==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==
The following code uses features exclusive to Unicon. This version handles all tasks, not just the first 500.
The following code uses features exclusive to Unicon. This version handles all tasks, not just the first 500.


<lang Unicon>$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500"
<syntaxhighlight lang="unicon">$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500"
$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCUA "User-Agent: Unicon Rosetta 0.1"
$define RCUA "User-Agent: Unicon Rosetta 0.1"
Line 1,033: Line 1,033:
close(page)
close(page)
return text
return text
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,065: Line 1,065:
'''Solution:'''<br>
'''Solution:'''<br>
Using <code>getCategoryMembers</code> from [[Find unimplemented tasks#J|Find unimplemented tasks]].
Using <code>getCategoryMembers</code> from [[Find unimplemented tasks#J|Find unimplemented tasks]].
<lang j>require 'web/gethttp'
<syntaxhighlight lang="j">require 'web/gethttp'


getAllTaskSolnCounts=: monad define
getAllTaskSolnCounts=: monad define
Line 1,084: Line 1,084:
res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.'
res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.'
res , 'Total examples: ' , ": +/counts
res , 'Total examples: ' , ": +/counts
)</lang>
)</syntaxhighlight>


'''Example Usage:'''
'''Example Usage:'''
<lang j> formatSolnCounts getAllTaskSolnCounts ''
<syntaxhighlight lang="j"> formatSolnCounts getAllTaskSolnCounts ''
100 doors: 61 examples.
100 doors: 61 examples.
24 game: 15 examples.
24 game: 15 examples.
24 game Player: 11 examples.
24 game Player: 11 examples.
99 Bottles of Beer: 76 examples.
99 Bottles of Beer: 76 examples.
...</lang>
...</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>
<syntaxhighlight lang="java5">
import java.util.ArrayList;
import java.util.ArrayList;
import ScreenScrape;
import ScreenScrape;
Line 1,166: Line 1,166:
}
}
}
}
</syntaxhighlight>
</lang>
[[Count programming examples/Java/ScreenScrape|ScreenScrape class]]
[[Count programming examples/Java/ScreenScrape|ScreenScrape class]]


Line 1,174: Line 1,174:
`@uri` filter in the bash function `titles`.
`@uri` filter in the bash function `titles`.


<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash


# Produce lines of the form: URI TITLE
# Produce lines of the form: URI TITLE
Line 1,198: Line 1,198:
n=$((n + i))
n=$((n + i))
done < <(titles)
done < <(titles)
echo Total: $n examples.</lang>
echo Total: $n examples.</syntaxhighlight>


{{out}}
{{out}}
Line 1,214: Line 1,214:
=={{header|Julia}}==
=={{header|Julia}}==
Output by page is too long, so summaries only output shown.
Output by page is too long, so summaries only output shown.
<lang julia>using HTTP, JSON, Dates
<syntaxhighlight lang="julia">using HTTP, JSON, Dates


rosorg = "http://rosettacode.org"
rosorg = "http://rosettacode.org"
Line 1,259: Line 1,259:
println("Draft programming tasks:")
println("Draft programming tasks:")
qdURI |> getpages |> processtaskpages
qdURI |> getpages |> processtaskpages
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Programming examples at 2019-02-16T21:04:15.583:
Programming examples at 2019-02-16T21:04:15.583:
Line 1,269: Line 1,269:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result))
<syntaxhighlight lang="lasso">local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result))
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
with i in #root->find('query')->find('categorymembers') do => {^
with i in #root->find('query')->find('categorymembers') do => {^
Line 1,285: Line 1,285:
'\r'
'\r'
^}
^}
'Total: '+#totalex+' examples.'</lang>
'Total: '+#totalex+' examples.'</syntaxhighlight>


{{out}}
{{out}}
Line 1,307: Line 1,307:
2. Add a text field called "tasks"
2. Add a text field called "tasks"


n.b. The list of tasks is limited to 10 for demo purposes<lang LiveCode>on mouseUp
n.b. The list of tasks is limited to 10 for demo purposes<syntaxhighlight lang="livecode">on mouseUp
put empty into fld "taskurls"
put empty into fld "taskurls"
put URL "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=xml" into apixml
put URL "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=xml" into apixml
Line 1,323: Line 1,323:
end repeat
end repeat
put "Total" & comma & allTaskTotal after fld "tasks"
put "Total" & comma & allTaskTotal after fld "tasks"
end mouseUp</lang>
end mouseUp</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>ConvertUTF8 := proc( str )
<syntaxhighlight lang="maple">ConvertUTF8 := proc( str )
local i, tempstring, uniindex;
local i, tempstring, uniindex;
try
try
Line 1,363: Line 1,363:
print_examples(x["query"]["categorymembers"]);
print_examples(x["query"]["categorymembers"]);
end do:
end do:
</syntaxhighlight>
</lang>
{{Out|Output}}
{{Out|Output}}
<pre>
<pre>
Line 1,479: Line 1,479:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>TaskList = Flatten[
<syntaxhighlight lang="mathematica">TaskList = Flatten[
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]&
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]&
~Map~ StringReplace[TaskList, " " -> "_"]</lang>
~Map~ StringReplace[TaskList, " " -> "_"]</syntaxhighlight>
returns:
returns:
<pre>Task "100 doors" has 143 example(s)
<pre>Task "100 doors" has 143 example(s)
Line 1,494: Line 1,494:


The function count_examples() need to be saved in a file count_examples.m and its directory need to be included in the path.
The function count_examples() need to be saved in a file count_examples.m and its directory need to be included in the path.
<lang MATLAB> function c = count_examples(url)
<syntaxhighlight lang="matlab"> function c = count_examples(url)
c = 0;
c = 0;
[s, success] = urlread (url);
[s, success] = urlread (url);
Line 1,511: Line 1,511:
c = count_examples(['http://rosettacode.org',t]);
c = count_examples(['http://rosettacode.org',t]);
printf('Task "%s" has %i examples.\n',t(7:end), c);
printf('Task "%s" has %i examples.\n',t(7:end), c);
end; </lang>
end; </syntaxhighlight>


Output:
Output:
Line 1,523: Line 1,523:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import httpclient, strutils, xmltree, xmlparser, cgi
<syntaxhighlight lang="nim">import httpclient, strutils, xmltree, xmlparser, cgi


proc count(s, sub: string): int =
proc count(s, sub: string): int =
Line 1,545: Line 1,545:
inc sum, c
inc sum, c


echo "\nTotal: ", sum, " examples."</lang>
echo "\nTotal: ", sum, " examples."</syntaxhighlight>


{{out}}
{{out}}
Line 1,573: Line 1,573:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use HTTP;
<syntaxhighlight lang="objeck">use HTTP;
use XML;
use XML;


Line 1,610: Line 1,610:
return xml;
return xml;
}
}
}</lang>
}</syntaxhighlight>


Output:<pre>Amb: 28
Output:<pre>Amb: 28
Line 1,643: Line 1,643:
ocamlfind opt -linkpkg -package str,unix,xml-light,netclient countex.ml -o countex.opt
ocamlfind opt -linkpkg -package str,unix,xml-light,netclient countex.ml -o countex.opt


<lang ocaml>open Http_client.Convenience
<syntaxhighlight lang="ocaml">open Http_client.Convenience


Line 1,704: Line 1,704:
let catmb = get_child "categorymembers" query in
let catmb = get_child "categorymembers" query in
List.iter f catmb
List.iter f catmb
| _ -> ()</lang>
| _ -> ()</syntaxhighlight>


outputs:
outputs:
Line 1,731: Line 1,731:
{{libheader|OzHttpClient}}
{{libheader|OzHttpClient}}


<lang oz>declare
<syntaxhighlight lang="oz">declare
[HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Line 1,815: Line 1,815:
end
end
in
in
{Main}</lang>
{Main}</syntaxhighlight>


Example output:
Example output:
Line 1,834: Line 1,834:
=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|HTTP:Tiny}}
{{libheader|HTTP:Tiny}}
<lang Perl>use HTTP::Tiny;
<syntaxhighlight lang="perl">use HTTP::Tiny;


my $site = "http://rosettacode.org";
my $site = "http://rosettacode.org";
Line 1,845: Line 1,845:
my $count = () = $response->{content} =~ /toclevel-1/g;
my $count = () = $response->{content} =~ /toclevel-1/g;
print "$_: $count examples\n";
print "$_: $count examples\n";
}</lang>
}</syntaxhighlight>


{{libheader|Mojolicious}}
{{libheader|Mojolicious}}
<lang Perl>use v5.10;
<syntaxhighlight lang="perl">use v5.10;
use Mojo::UserAgent;
use Mojo::UserAgent;


Line 1,859: Line 1,859:
my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size;
my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size;
say "$_->{title}: $count examples";
say "$_->{title}: $count examples";
});</lang>
});</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
First, some common code used by several tasks:
First, some common code used by several tasks:
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\rosettacode_cache.e
-- demo\rosetta\rosettacode_cache.e
Line 2,013: Line 2,013:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
The task itself:
The task itself:
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Count_examples.exw
-- demo\rosetta\Count_examples.exw
Line 2,120: Line 2,120:
<span style="color: #7060A8;">progress</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Total: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count_tasks</span><span style="color: #0000FF;">()})</span>
<span style="color: #7060A8;">progress</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Total: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count_tasks</span><span style="color: #0000FF;">()})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}} (as of 30/2/22, showing first two, every 200th, and last two)
{{out}} (as of 30/2/22, showing first two, every 200th, and last two)
<pre>
<pre>
Line 2,139: Line 2,139:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/http.l")
<syntaxhighlight lang="picolisp">(load "@lib/http.l")


(client "rosettacode.org" 80
(client "rosettacode.org" 80
Line 2,150: Line 2,150:
(unless (sub? "." (till "<" T))
(unless (sub? "." (till "<" T))
(inc 'Cnt) ) )
(inc 'Cnt) ) )
(out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) )</lang>
(out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) )</syntaxhighlight>
Output (05may10):
Output (05may10):
<pre>100 doors: 79
<pre>100 doors: 79
Line 2,161: Line 2,161:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure handleError(value, msg.s)
<syntaxhighlight lang="purebasic">Procedure handleError(value, msg.s)
If value = 0
If value = 0
MessageRequester("Error", msg)
MessageRequester("Error", msg)
Line 2,224: Line 2,224:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>100 doors: 224 examples
<pre>100 doors: 224 examples
Line 2,242: Line 2,242:
=={{header|Python}}==
=={{header|Python}}==


<lang python>from urllib.request import urlopen, Request
<syntaxhighlight lang="python">from urllib.request import urlopen, Request
import xml.dom.minidom
import xml.dom.minidom


Line 2,260: Line 2,260:


print(f'\nTotal: {sum(tasks)} examples.')
print(f'\nTotal: {sum(tasks)} examples.')
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
Line 2,266: Line 2,266:


{{libheader|RCurl}}
{{libheader|RCurl}}
<syntaxhighlight lang="r">
<lang R>
library(XML)
library(XML)
library(RCurl)
library(RCurl)
Line 2,281: Line 2,281:
}
}
cat("Total: ", length(unlist(counts)), "examples\n")
cat("Total: ", length(unlist(counts)), "examples\n")
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,311: Line 2,311:
(printf "~a: ~a\n" task s)
(printf "~a: ~a\n" task s)
s))
s))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,327: Line 2,327:


For a full output, see [[Rosetta_Code/Count_examples/Full_list|Top tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_2|Second tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_3|Third tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_4|Fourth tier]]
For a full output, see [[Rosetta_Code/Count_examples/Full_list|Top tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_2|Second tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_3|Third tier]], [[Rosetta_Code/Count_examples/Full_list/Tier_4|Fourth tier]]
<lang perl6>use HTTP::UserAgent;
<syntaxhighlight lang="raku" line>use HTTP::UserAgent;
use URI::Escape;
use URI::Escape;
use JSON::Fast;
use JSON::Fast;
Line 2,501: Line 2,501:
sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~(65+$0.chars).chr~$0},:g) }
sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~(65+$0.chars).chr~$0},:g) }


sub clear { "\r" ~ ' ' x 116 ~ "\r" }</lang>
sub clear { "\r" ~ ' ' x 116 ~ "\r" }</syntaxhighlight>


{{out|Abridged output}}
{{out|Abridged output}}
Line 2,565: Line 2,565:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project: Rosetta Code/Count examples
# Project: Rosetta Code/Count examples


Line 2,621: Line 2,621:
end
end
return sum
return sum
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,652: Line 2,652:
{{libheader|REXML}}
{{libheader|REXML}}
First, a RosettaCode module, saved as <tt>rosettacode.rb</tt>:
First, a RosettaCode module, saved as <tt>rosettacode.rb</tt>:
<lang ruby>require 'open-uri'
<syntaxhighlight lang="ruby">require 'open-uri'
require 'rexml/document'
require 'rexml/document'


Line 2,702: Line 2,702:
end
end


end</lang>
end</syntaxhighlight>


Then, we implement the task with:
Then, we implement the task with:
<lang ruby>require 'rosettacode'
<syntaxhighlight lang="ruby">require 'rosettacode'


total_examples = 0
total_examples = 0
Line 2,717: Line 2,717:


puts
puts
puts "Total: #{total_examples}"</lang>
puts "Total: #{total_examples}"</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>html "<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>"
<syntaxhighlight lang="runbasic">html "<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>"


a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks")
a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks")
Line 2,751: Line 2,751:
wend
wend
html "<tr bgcolor=wheat><td>**</td><td>** Total **</td><td align=right>";totExamp;"</td></tr></table>"
html "<tr bgcolor=wheat><td>**</td><td>** Total **</td><td align=right>";totExamp;"</td></tr></table>"
end</lang>
end</syntaxhighlight>
<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>
<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>
<tr><td align=right>1</td><td>100 doors</td><td align=right>165</td></tr>
<tr><td align=right>1</td><td>100 doors</td><td align=right>165</td></tr>
Line 2,775: Line 2,775:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>extern crate reqwest;
<syntaxhighlight lang="rust">extern crate reqwest;
extern crate url;
extern crate url;
extern crate rustc_serialize;
extern crate rustc_serialize;
Line 2,886: Line 2,886:
let json: Json = query_api(query).unwrap();
let json: Json = query_api(query).unwrap();
count_number_examples(&json, task.page_id).unwrap()
count_number_examples(&json, task.page_id).unwrap()
}</lang>
}</syntaxhighlight>


The function is then run using the following:
The function is then run using the following:
<lang rust>
<syntaxhighlight lang="rust">
extern crate count_examples;
extern crate count_examples;
fn main() {
fn main() {
Line 2,897: Line 2,897:
println!("Task: {} has {} examples", task.title, count);
println!("Task: {} has {} examples", task.title, count);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang Scala>import scala.language.postfixOps
{{libheader|Scala}}<syntaxhighlight lang="scala">import scala.language.postfixOps


object TaskCount extends App {
object TaskCount extends App {
Line 2,924: Line 2,924:
counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println
counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println
println("\nTotal: %d examples." format (counts map (_.apply._2) sum))
println("\nTotal: %d examples." format (counts map (_.apply._2) sum))
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var lwp = require('LWP::UserAgent').new(agent => 'Mozilla/5.0');
<syntaxhighlight lang="ruby">var lwp = require('LWP::UserAgent').new(agent => 'Mozilla/5.0');


var site = 'http://rosettacode.org';
var site = 'http://rosettacode.org';
Line 2,940: Line 2,940:
var count = lwp.get("#{site}/wiki/#{slug}").decoded_content.count(/toclevel-1/g);
var count = lwp.get("#{site}/wiki/#{slug}").decoded_content.count(/toclevel-1/g);
say "#{m[0]}: #{count} examples";
say "#{m[0]}: #{count} examples";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,958: Line 2,958:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|json}}
{{tcllib|json}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require http
package require http
package require json
package require json
Line 3,022: Line 3,022:
}
}


puts "\nTotal: $total examples"</lang>
puts "\nTotal: $total examples"</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
data=REQUEST (url)
data=REQUEST (url)
Line 3,064: Line 3,064:


FILE "tasks" = line
FILE "tasks" = line
</syntaxhighlight>
</lang>
Output in file "tasks":
Output in file "tasks":
<pre style='height:30ex;overflow:scroll'>
<pre style='height:30ex;overflow:scroll'>
Line 3,090: Line 3,090:
Requires the <tt>curl</tt> and <tt>jq</tt> command-line utilities.
Requires the <tt>curl</tt> and <tt>jq</tt> command-line utilities.


<lang sh>#!/usr/bin/env bash
<syntaxhighlight lang="sh">#!/usr/bin/env bash
SITE=https://www.rosettacode.org
SITE=https://www.rosettacode.org
API=$SITE/mw/api.php
API=$SITE/mw/api.php
Line 3,109: Line 3,109:
| jq -r '.query.categorymembers[].title')
| jq -r '.query.categorymembers[].title')


printf '\nTotal: %d examples.\n' "$total"</lang>
printf '\nTotal: %d examples.\n' "$total"</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 3,115: Line 3,115:
{{libheader|Wren-pattern}}
{{libheader|Wren-pattern}}
An embedded program so we can use the libcurl library.
An embedded program so we can use the libcurl library.
<lang ecmascript>/* rc_count_examples.wren */
<syntaxhighlight lang="ecmascript">/* rc_count_examples.wren */


import "./pattern" for Pattern
import "./pattern" for Pattern
Line 3,166: Line 3,166:
}
}


curl.easyCleanup()</lang>
curl.easyCleanup()</syntaxhighlight>
<br>
<br>
which we now embed in the following C program, build and run.
which we now embed in the following C program, build and run.
<lang c>/* gcc rc_count_examples.c -o rc_count_examples -lcurl -lwren -lm */
<syntaxhighlight lang="c">/* gcc rc_count_examples.c -o rc_count_examples -lcurl -lwren -lm */


#include <stdio.h>
#include <stdio.h>
Line 3,359: Line 3,359:
free(script);
free(script);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,394: Line 3,394:
=={{header|zkl}}==
=={{header|zkl}}==
Uses shared libraries YAJL and cURL and handles "continue" responses.
Uses shared libraries YAJL and cURL and handles "continue" responses.
<lang zkl>var [const] YAJL=Import("zklYAJL")[0], CURL=Import("zklCurl");
<syntaxhighlight lang="zkl">var [const] YAJL=Import("zklYAJL")[0], CURL=Import("zklCurl");


fcn getTasks(language){
fcn getTasks(language){
Line 3,421: Line 3,421:
cnt,n:=0,0; while(re.search(page,True,n)){ cnt+=1; n=re.matched[0].sum(0); }
cnt,n:=0,0; while(re.search(page,True,n)){ cnt+=1; n=re.matched[0].sum(0); }
"%4d: %s".fmt(cnt,task).println();
"%4d: %s".fmt(cnt,task).println();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>