Rosetta Code/Count examples: Difference between revisions
m
→{{header|Wren}}: Minor changes (though see Talk Page re encoding of '+')
m (→{{header|Phix}}: bad link) |
m (→{{header|Wren}}: Minor changes (though see Talk Page re encoding of '+')) |
||
(8 intermediate revisions by 6 users not shown) | |||
Line 18:
{{libheader|AWS}}
Parsing XML file with XMLAda from AdaCore
<
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
Line 119:
Put_Line ("Total :" & Integer'Image (Total) & " exemples.");
end Count_Examples;
</syntaxhighlight>
Output :
<pre>
Line 130:
=={{header|AutoHotkey}}==
<
, http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml
, tasks.xml
Line 149:
}
MsgBox % output
Return</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
Line 236:
WHEN """: = """"
ENDCASE
= h$</
'''Sample output:'''
<pre>
Line 265:
=={{header|Bracmat}}==
<
=
. sys$(str$("wget -q -O wget.out \"" !arg \"))
Line 305:
)
& lst$(list,taskfreq,NEW)
)</
Output (in file <code>tasqfreq</code>):
<pre>list=
Line 353:
Object-oriented solution.
<
using System.Collections.Generic;
using System.Linq;
Line 402:
foreach (string task in tasknames) {
string content = GetSourceCodeFromPage(WebUtility.UrlEncode(task), wc);
Task t = new Task(task, count);
Console.WriteLine(t);
tasks.Add(t);
}
catch (Exception ex) {
Console.WriteLine("**** Unable to get task \"" + task + "\": " + ex.Message);
}
}
Console.WriteLine("\nTotal: {0} examples.", tasks.Select(x => x.Examples).Sum());
}
}</
=={{header|Clojure}}==
<
(:import [java.net URLEncoder])
(:use [clojure.contrib.http.agent :only (http-agent string)]
Line 454 ⟶ 459:
(flush))
(println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
</syntaxhighlight>
<
100 doors: 73
24 game: 18
Line 471 ⟶ 476:
Total: 11216
nil
</syntaxhighlight>
=={{header|D}}==
{{works with|Tango}}
<syntaxhighlight lang="d">
import tango.io.Stdout;
import tango.net.http.HttpClient;
Line 524 ⟶ 529:
}
}
</syntaxhighlight>
=={{header|EGL}}==
Line 532 ⟶ 537:
User Interface: RosettaCodeHandler.egl
<
import org.eclipse.edt.rui.widgets.*;
Line 607 ⟶ 612:
title string;
count int;
end</
Service Interface: ProxyFunctions.egl
<
library ProxyFunctions
Line 646 ⟶ 651:
record QueryContinue
categorymembers Categorymembers;
end</
=={{header|Erlang}}==
Line 652 ⟶ 657:
{{libheader|xmerl}}
<
-module(rosseta_examples).
-include_lib("xmerl/include/xmerl.hrl").
Line 715 ⟶ 720:
replace_chars([],Acc) ->
lists:reverse(Acc).
</syntaxhighlight>
Line 735 ⟶ 740:
Using asynchronous workflows to perform downloads concurrently:
<
let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
Line 752 ⟶ 757:
|> Async.Parallel
|> Async.RunSynchronously
|> fun xs -> printfn "Total: %d examples" (Seq.sum xs)</
This is 21× faster than the python thanks to the concurrency.
Line 759 ⟶ 764:
Runs in about a minute. The number of threads is limited to 10 avoid cloudfare's protection mechanism.
<
concurrency.semaphores formatting hashtables http.client io
json.reader kernel math math.parser sequences splitting
Line 800 ⟶ 805:
all-programming-titles fetch-counts print-counts ;
MAIN: rosetta-examples</
Outputs:
Line 812 ⟶ 817:
=={{header|Go}}==
<
import (
Line 886 ⟶ 891:
fmt.Printf("%s: %d\n", cm, examples)
total += examples
}</
{{out|Output: (May 25, 2011)}}
<pre>
Line 900 ⟶ 905:
{{libheader|HTTP XML}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
<
import Network.HTTP
import Network.URI
Line 936 ⟶ 941:
mapM_ putStrLn $ zipWith showFormatted tasks ns
putStrLn $ ("Total: " ++) $ show tot</
some output:
<
100 doors: 56
24 game: 11
Line 947 ⟶ 952:
Active object: 9
...
Total: 9156</
==Icon and {{header|Unicon}}==
The following code uses features exclusive to Unicon. This version handles all tasks, not just the first 500.
<
$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCUA "User-Agent: Unicon Rosetta 0.1"
Line 1,033 ⟶ 1,038:
close(page)
return text
end</
{{libheader|Icon Programming Library}}
Line 1,065 ⟶ 1,070:
'''Solution:'''<br>
Using <code>getCategoryMembers</code> from [[Find unimplemented tasks#J|Find unimplemented tasks]].
<
getAllTaskSolnCounts=: monad define
Line 1,084 ⟶ 1,089:
res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.'
res , 'Total examples: ' , ": +/counts
)</
'''Example Usage:'''
<
100 doors: 61 examples.
24 game: 15 examples.
24 game Player: 11 examples.
99 Bottles of Beer: 76 examples.
...</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.util.ArrayList;
import ScreenScrape;
Line 1,166 ⟶ 1,171:
}
}
</syntaxhighlight>
[[Count programming examples/Java/ScreenScrape|ScreenScrape class]]
Line 1,174 ⟶ 1,179:
`@uri` filter in the bash function `titles`.
<
# Produce lines of the form: URI TITLE
Line 1,198 ⟶ 1,203:
n=$((n + i))
done < <(titles)
echo Total: $n examples.</
{{out}}
Line 1,214 ⟶ 1,219:
=={{header|Julia}}==
Output by page is too long, so summaries only output shown.
<
rosorg = "http://rosettacode.org"
qURI = "/
qdURI = "/
sqURI = rosorg * "/wiki/"
topages(js, v) = for d in js["query"]["categorymembers"] push!(v, sqURI * replace(d["title"], " " => "_")) end
Line 1,259 ⟶ 1,264:
println("Draft programming tasks:")
qdURI |> getpages |> processtaskpages
</
<pre>
Programming examples at 2019-02-16T21:04:15.583:
Line 1,269 ⟶ 1,274:
=={{header|Lasso}}==
<
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
with i in #root->find('query')->find('categorymembers') do => {^
Line 1,285 ⟶ 1,290:
'\r'
^}
'Total: '+#totalex+' examples.'</
{{out}}
Line 1,307 ⟶ 1,312:
2. Add a text field called "tasks"
n.b. The list of tasks is limited to 10 for demo purposes<
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
Line 1,323 ⟶ 1,328:
end repeat
put "Total" & comma & allTaskTotal after fld "tasks"
end mouseUp</
=={{header|Maple}}==
<
local i, tempstring, uniindex;
try
Line 1,363 ⟶ 1,368:
print_examples(x["query"]["categorymembers"]);
end do:
</syntaxhighlight>
{{Out|Output}}
<pre>
Line 1,479 ⟶ 1,484:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]&
~Map~ StringReplace[TaskList, " " -> "_"]</
returns:
<pre>Task "100 doors" has 143 example(s)
Line 1,494 ⟶ 1,499:
The function count_examples() need to be saved in a file count_examples.m and its directory need to be included in the path.
<
c = 0;
[s, success] = urlread (url);
Line 1,511 ⟶ 1,516:
c = count_examples(['http://rosettacode.org',t]);
printf('Task "%s" has %i examples.\n',t(7:end), c);
end; </
Output:
Line 1,523 ⟶ 1,528:
=={{header|Nim}}==
<
proc count(s, sub: string): int =
Line 1,545 ⟶ 1,550:
inc sum, c
echo "\nTotal: ", sum, " examples."</
{{out}}
Line 1,573 ⟶ 1,578:
=={{header|Objeck}}==
<
use XML;
Line 1,610 ⟶ 1,615:
return xml;
}
}</
Output:<pre>Amb: 28
Line 1,643 ⟶ 1,648:
ocamlfind opt -linkpkg -package str,unix,xml-light,netclient countex.ml -o countex.opt
<
Line 1,704 ⟶ 1,709:
let catmb = get_child "categorymembers" query in
List.iter f catmb
| _ -> ()</
outputs:
Line 1,731 ⟶ 1,736:
{{libheader|OzHttpClient}}
<
[HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Line 1,815 ⟶ 1,820:
end
in
{Main}</
Example output:
Line 1,833 ⟶ 1,838:
=={{header|Perl}}==
<syntaxhighlight lang="perl">use HTTP::Tiny;
my $site = "http://rosettacode.org";
my $list_url = "/
my $response = HTTP::Tiny->new->get("$site$list_url");
Line 1,845 ⟶ 1,849:
my $count = () = $response->{content} =~ /toclevel-1/g;
print "$_: $count examples\n";
}</
{{libheader|Mojolicious}}
<syntaxhighlight lang="perl">use Mojo::UserAgent;
my $site = "http://rosettacode.org";
Line 1,859 ⟶ 1,862:
my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size;
say "$_->{title}: $count examples";
});</
=={{header|Phix}}==
First, some common code used by several tasks:
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\rosettacode_cache.e
Line 2,013 ⟶ 2,016:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</
The task itself:
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Count_examples.exw
Line 2,120 ⟶ 2,123:
<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>
<!--</
{{out}} (as of 30/2/22, showing first two, every 200th, and last two)
<pre>
Line 2,139 ⟶ 2,142:
=={{header|PicoLisp}}==
<
(client "rosettacode.org" 80
Line 2,150 ⟶ 2,153:
(unless (sub? "." (till "<" T))
(inc 'Cnt) ) )
(out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) )</
Output (05may10):
<pre>100 doors: 79
Line 2,161 ⟶ 2,164:
=={{header|PureBasic}}==
<
If value = 0
MessageRequester("Error", msg)
Line 2,224 ⟶ 2,227:
Input()
CloseConsole()
EndIf</
Sample output:
<pre>100 doors: 224 examples
Line 2,242 ⟶ 2,245:
=={{header|Python}}==
<
import xml.dom.minidom
Line 2,260 ⟶ 2,263:
print(f'\nTotal: {sum(tasks)} examples.')
</syntaxhighlight>
===Using Semantic MediaWiki===
{{libheader|Requests}}
Here we use the [https://www.semantic-mediawiki.org/wiki/Help:API:ask ask] API provided by the [https://www.semantic-mediawiki.org/wiki/Semantic_MediaWiki Semantic MediaWiki extension] to query page [https://www.semantic-mediawiki.org/wiki/Help:Properties_and_types properties] rather than parse page content, producing subtly different counts to some other solutions. Maybe too different for this task.
We only count task examples that have a corresponding category page AND that page has the "Is Language" property set to True. In other words, <code>Implemented In</code> + <code>Not Implemented In</code> + <code>Omitted From</code> is always equal to the total number of languages.
<syntaxhighlight lang="python">"""Count Rosetta Code tasks implementations using the Semantic MediaWiki API.
Works with Python >= 3.7."""
import json
import logging
from dataclasses import dataclass
from dataclasses import field
from datetime import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Set
from typing import Tuple
import requests
from requests.adapters import HTTPAdapter
from requests.adapters import Retry
logging.basicConfig(level=logging.WARN)
# See https://www.semantic-mediawiki.org/wiki/Help:API:ask
_SM_ASK: Dict[str, str] = {
"action": "ask",
"format": "json",
"formatversion": "2",
"api_version": "3",
}
_SM_ASK_REQUEST_BLOCK_SIZE = 500
@dataclass(frozen=True)
class Page:
# fulltext is the page's title, not the page content.
fulltext: str
fullurl: str
namespace: int
exists: str
displaytitle: str
@dataclass(frozen=True, eq=False)
class Lang(Page):
def __eq__(self, other: object) -> bool:
if isinstance(other, Lang):
return self.fullurl == other.fullurl
elif isinstance(other, str):
return self.fullurl == other
return False
def __hash__(self) -> int:
return hash(self.fullurl)
def unimplemented(self, tasks: Set["Task"]) -> Set["Task"]:
return {task for task in tasks if self.fullurl not in task.exclude}
def omitted_from(self, tasks: Set["Task"]) -> Set["Task"]:
return {task for task in tasks if self.fullurl in task.omitted_from}
@dataclass(frozen=True)
class Task(Page):
title: str
implemented_in: Set[Lang] = field(repr=False, compare=False)
omitted_from: Set[Lang] = field(repr=False, compare=False)
exclude: Set[Lang] = field(repr=False, compare=False)
def not_implemented_in(self, langs: Set[Lang]) -> Set[Lang]:
return langs.difference(self.exclude)
@dataclass
class TaskResponseBlock:
tasks: List[Task]
continue_offset: Optional[int] = None
@dataclass
class LanguageResponseBlock:
langs: List[Lang]
continue_offset: Optional[int] = None
def sm_ask_category(
session: requests.Session,
url: str,
category: str,
limit: int,
offset: int,
known_langs: Set[Lang],
) -> TaskResponseBlock:
query_params = {
**_SM_ASK,
"query": (
f"[[Category:{category}]]"
"|?Implemented in language"
"|?Omitted from language"
f"|limit={limit}"
f"|offset={offset}"
),
}
# Display some progress
log(f"ask [[Category:{category}]] offset={offset}")
response = session.get(url, params=query_params)
response.raise_for_status()
data = response.json()
handle_warnings_and_errors(data)
return _transform_implemented_in_response_data(data, known_langs)
def sm_ask_tasks(
session: requests.Session,
url: str,
limit: int,
offset: int,
known_langs: Set[Lang],
):
return sm_ask_category(
session, url, "Programming Tasks", limit, offset, known_langs
)
def sm_ask_drafts(
session: requests.Session,
url: str,
limit: int,
offset: int,
known_langs: Set[Lang],
):
return sm_ask_category(
session, url, "Draft Programming Tasks", limit, offset, known_langs
)
def sm_ask_languages(
session: requests.Session,
url: str,
limit: int,
offset: int,
) -> LanguageResponseBlock:
query_params = {
**_SM_ASK,
"query": (
"[[Is language::+]]"
"|?Implemented in language"
"|?Omitted from language"
f"|limit={limit}"
f"|offset={offset}"
),
}
# Display some progress
log(f"ask [[Is language::+]] offset={offset}")
response = session.get(url, params=query_params)
response.raise_for_status()
data = response.json()
handle_warnings_and_errors(data)
return _transform_language_response_data(data)
def sm_ask_all_tasks(
session: requests.Session, url: str, known_langs: Set[Lang]
) -> List[Task]:
block = sm_ask_tasks(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=0,
known_langs=known_langs,
)
tasks = block.tasks
while block.continue_offset:
block = sm_ask_tasks(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=block.continue_offset,
known_langs=known_langs,
)
tasks.extend(block.tasks)
return tasks
def sm_ask_all_drafts(
session: requests.Session, url: str, known_langs: Set[Lang]
) -> List[Task]:
block = sm_ask_drafts(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=0,
known_langs=known_langs,
)
tasks = block.tasks
while block.continue_offset:
block = sm_ask_drafts(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=block.continue_offset,
known_langs=known_langs,
)
tasks.extend(block.tasks)
return tasks
def sm_ask_all_languages(session: requests.Session, url: str) -> List[Lang]:
block = sm_ask_languages(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=0,
)
langs = block.langs
while block.continue_offset:
block = sm_ask_languages(
session,
url,
limit=_SM_ASK_REQUEST_BLOCK_SIZE,
offset=block.continue_offset,
)
langs.extend(block.langs)
return langs
def _transform_implemented_in_response_data(
data: Any, known_langs: Set[Lang]
) -> TaskResponseBlock:
tasks: List[Task] = []
for result in data["query"]["results"]:
for task_title, task_page in result.items():
# We're excluding implementations that don't have a corresponding
# category page with an "Is Language" property.
implemented_in = {
Lang(**lang)
for lang in task_page["printouts"]["Implemented in language"]
}.intersection(known_langs)
omitted_from = (
{
Lang(**lang)
for lang in task_page["printouts"]["Omitted from language"]
}
.intersection(known_langs)
.difference(implemented_in)
)
tasks.append(
Task(
title=task_title,
implemented_in=implemented_in,
omitted_from=omitted_from,
fulltext=task_page["fulltext"],
fullurl=task_page["fullurl"],
namespace=task_page["namespace"],
exists=task_page["exists"],
displaytitle=task_page["displaytitle"],
exclude=implemented_in.union(omitted_from),
)
)
return TaskResponseBlock(
tasks=tasks, continue_offset=data.get("query-continue-offset", None)
)
def _transform_language_response_data(data: Any) -> LanguageResponseBlock:
langs: List[Lang] = []
for result in data["query"]["results"]:
for _, task_page in result.items():
langs.append(
Lang(
fulltext=task_page["fulltext"],
fullurl=task_page["fullurl"],
namespace=task_page["namespace"],
exists=task_page["exists"],
displaytitle=task_page["displaytitle"],
)
)
return LanguageResponseBlock(
langs=langs, continue_offset=data.get("query-continue-offset", None)
)
def get_session() -> requests.Session:
"""Setup a requests.Session with retries."""
retry_strategy = Retry(
total=5,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
def log(msg: str) -> None:
print(f"{datetime.now().isoformat(' ', 'seconds')}: {msg}")
def handle_warnings_and_errors(data: Any) -> None:
if data.get("errors"):
for error in data["errors"]:
logging.error(json.dumps(error))
# legacy format
if data.get("error"):
logging.error(json.dumps(data["error"]))
if data.get("warnings"):
for warning in data["warnings"]:
logging.warning(json.dumps(warning))
def count_examples(url: str, n: int = 30) -> None:
"""Print a table to stdout containing implementation counts for the first
`n` tasks, sorted by number implementations (most to least)."""
session = get_session()
langs = set(sm_ask_all_languages(session, url))
tasks = sm_ask_all_tasks(session, url, langs)
drafts = sm_ask_all_drafts(session, url, langs)
all_tasks = [*tasks, *drafts]
# Map of task to (implemented in, not implemented in, omitted from)
counts: Dict[Task, Tuple[int, int, int]] = {}
# Running total of examples for all tasks. Where a language has multiple examples
# for a single tasks, we only count one example.
total: int = 0
for task in all_tasks:
total += len(task.implemented_in)
counts[task] = (
len(task.implemented_in),
len(task.not_implemented_in(langs)),
len(task.omitted_from),
)
# Pretty print
top = sorted(counts.items(), key=lambda it: it[1][0], reverse=True)[:n]
pad = max([len(task.fulltext) for task, _ in top])
print("\nKnown languages:", len(langs))
print("Total tasks:", len(all_tasks))
print("Total examples:", total)
print(f"{'Task':>{pad}} | Implemented In | Not Implemented In | Omitted From")
print("-" * (pad + 1), "+", "-" * 16, "+", "-" * 20, "+", "-" * 13, sep="")
for task, _counts in top:
implemented_in, not_implemented_in, omitted_from = _counts
print(
f"{task.fulltext:>{pad}} |"
f"{implemented_in:>15} |"
f"{not_implemented_in:>19} |"
f"{omitted_from:>13}"
)
if __name__ == "__main__":
import argparse
URL = "https://rosettacode.org/w/api.php"
parser = argparse.ArgumentParser(description="Count tasks on Rosetta Code.")
parser.add_argument(
"--rows",
"-n",
type=int,
default=30,
dest="n",
help="number of rows to display in the output table (default: 30)",
)
parser.add_argument(
"--url",
default=URL,
help=f"target MediaWiki URL (default: {URL})",
)
args = parser.parse_args()
count_examples(args.url, args.n)</syntaxhighlight>
{{out}}
<pre>
2023-02-11 11:09:34: ask [[Is language::+]] offset=0
2023-02-11 11:09:35: ask [[Is language::+]] offset=500
2023-02-11 11:09:36: ask [[Category:Programming Tasks]] offset=0
2023-02-11 11:09:47: ask [[Category:Programming Tasks]] offset=500
2023-02-11 11:10:04: ask [[Category:Programming Tasks]] offset=1000
2023-02-11 11:10:12: ask [[Category:Draft Programming Tasks]] offset=0
Known languages: 890
Total tasks: 1602
Total examples: 91075
Task | Implemented In | Not Implemented In | Omitted From
--------------------------------+----------------+--------------------+-------------
Hello world/Text | 498 | 392 | 0
99 bottles of beer | 371 | 519 | 0
100 doors | 334 | 555 | 1
FizzBuzz | 325 | 565 | 0
Fibonacci sequence | 308 | 582 | 0
Factorial | 302 | 588 | 0
Comments | 297 | 592 | 1
A+B | 293 | 597 | 0
Empty program | 274 | 616 | 0
Function definition | 254 | 634 | 2
Loops/Infinite | 254 | 635 | 1
Loops/For | 248 | 641 | 1
Loops/While | 244 | 645 | 1
Arrays | 237 | 652 | 1
Ackermann function | 234 | 653 | 3
Reverse a string | 231 | 657 | 2
Conditional structures | 223 | 666 | 1
Arithmetic/Integer | 213 | 677 | 0
Greatest common divisor | 213 | 677 | 0
Array concatenation | 208 | 682 | 0
Greatest element of a list | 208 | 682 | 0
Even or odd | 207 | 683 | 0
Loops/Downward for | 207 | 683 | 0
Sieve of Eratosthenes | 203 | 687 | 0
Increment a numerical string | 202 | 688 | 0
Integer comparison | 202 | 688 | 0
Repeat a string | 199 | 691 | 0
Boolean values | 198 | 691 | 1
Loops/For with a specified step | 198 | 691 | 1
Copy a string | 196 | 693 | 1
</pre>
=={{header|R}}==
Line 2,266 ⟶ 2,716:
{{libheader|RCurl}}
<syntaxhighlight lang="r">
library(XML)
library(RCurl)
Line 2,281 ⟶ 2,731:
}
cat("Total: ", length(unlist(counts)), "examples\n")
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
Line 2,311 ⟶ 2,761:
(printf "~a: ~a\n" task s)
s))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,327 ⟶ 2,777:
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]]
<syntaxhighlight lang="raku"
use URI::Escape;
use JSON::Fast;
Line 2,343 ⟶ 2,793:
$client.timeout = 10;
my $url = '
my $hashfile = './RC_Task_count.json';
Line 2,501 ⟶ 2,951:
sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~(65+$0.chars).chr~$0},:g) }
sub clear { "\r" ~ ' ' x 116 ~ "\r" }</
{{out|Abridged output}}
Line 2,565 ⟶ 3,015:
=={{header|Ring}}==
<
# Project: Rosetta Code/Count examples
Line 2,621 ⟶ 3,071:
end
return sum
</syntaxhighlight>
Output:
<pre>
Line 2,652 ⟶ 3,102:
{{libheader|REXML}}
First, a RosettaCode module, saved as <tt>rosettacode.rb</tt>:
<
require 'rexml/document'
Line 2,702 ⟶ 3,152:
end
end</
Then, we implement the task with:
<
total_examples = 0
Line 2,717 ⟶ 3,167:
puts
puts "Total: #{total_examples}"</
=={{header|Run BASIC}}==
<
a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks")
Line 2,751 ⟶ 3,201:
wend
html "<tr bgcolor=wheat><td>**</td><td>** Total **</td><td align=right>";totExamp;"</td></tr></table>"
end</
<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>
Line 2,775 ⟶ 3,225:
=={{header|Rust}}==
<
extern crate url;
extern crate rustc_serialize;
Line 2,886 ⟶ 3,336:
let json: Json = query_api(query).unwrap();
count_number_examples(&json, task.page_id).unwrap()
}</
The function is then run using the following:
<
extern crate count_examples;
fn main() {
Line 2,897 ⟶ 3,347:
println!("Task: {} has {} examples", task.title, count);
}
}</
=={{header|Scala}}==
{{libheader|Scala}}<
object TaskCount extends App {
Line 2,924 ⟶ 3,374:
counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println
println("\nTotal: %d examples." format (counts map (_.apply._2) sum))
}</
=={{header|Sidef}}==
{{trans|Perl}}
<
var site = 'http://rosettacode.org';
Line 2,940 ⟶ 3,390:
var count = lwp.get("#{site}/wiki/#{slug}").decoded_content.count(/toclevel-1/g);
say "#{m[0]}: #{count} examples";
}</
{{out}}
<pre>
Line 2,958 ⟶ 3,408:
=={{header|Tcl}}==
{{tcllib|json}}
<
package require http
package require json
Line 3,022 ⟶ 3,472:
}
puts "\nTotal: $total examples"</
=={{header|TUSCRIPT}}==
<
url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
data=REQUEST (url)
Line 3,064 ⟶ 3,514:
FILE "tasks" = line
</syntaxhighlight>
Output in file "tasks":
<pre style='height:30ex;overflow:scroll'>
Line 3,090 ⟶ 3,540:
Requires the <tt>curl</tt> and <tt>jq</tt> command-line utilities.
<
SITE=https://www.rosettacode.org
API=$SITE/mw/api.php
Line 3,109 ⟶ 3,559:
| jq -r '.query.categorymembers[].title')
printf '\nTotal: %d examples.\n' "$total"</
=={{header|Wren}}==
Line 3,115 ⟶ 3,565:
{{libheader|Wren-pattern}}
An embedded program so we can use the libcurl library.
<
import "./pattern" for Pattern
Line 3,152 ⟶ 3,602:
}
var url = "https://www.rosettacode.org/
var content = getContent.call(url)
var p = Pattern.new("title/=\"[+1^\"]\"")
Line 3,158 ⟶ 3,608:
for (m in matches) {
var title = m.capsText[0].replace("'", "'").replace(""", "\"")
var title2 = title.replace(" ", "_").replace("+", "\%
var taskUrl = "https://www.rosettacode.org/
var taskContent = getContent.call(taskUrl)
var lines = taskContent.split("\n")
Line 3,166 ⟶ 3,616:
}
curl.easyCleanup()</
<br>
which we now embed in the following C program, build and run.
<
#include <stdio.h>
Line 3,343 ⟶ 3,793:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 3,359 ⟶ 3,809:
free(script);
return 0;
}</
{{out}}
Just showing the first 25 'full' tasks:
<pre>
100 doors :
100 prisoners :
15 puzzle game :
15 puzzle solver :
2048 :
21 game :
24 game :
24 game/Solve :
4-rings or 4-squares puzzle :
9 billion names of God the integer :
99 bottles of beer :
A+B :
Abbreviations, automatic :
Abbreviations, easy :
Abbreviations, simple :
ABC problem :
Abelian sandpile model :
Abelian sandpile model/Identity :
Abstract type :
Abundant odd numbers :
Abundant, deficient and perfect number classifications :
Accumulator factory :
Ackermann function : 243 examples
Active Directory/Connect : 29 examples
....
</pre>
Line 3,394 ⟶ 3,844:
=={{header|zkl}}==
Uses shared libraries YAJL and cURL and handles "continue" responses.
<
fcn getTasks(language){
Line 3,421 ⟶ 3,871:
cnt,n:=0,0; while(re.search(page,True,n)){ cnt+=1; n=re.matched[0].sum(0); }
"%4d: %s".fmt(cnt,task).println();
}</
{{out}}
<pre>
|