(() => {
    'use strict';

    // main :: IO ()
    const main = () =>
        showGroups(
            circularWords(
                // Local copy of:
                // https://www.mit.edu/~ecprice/wordlist.10000
                lines(readFile('~/mitWords.txt'))
            )
        );

    // circularWords :: [String] -> [String]
    const circularWords = ws =>
        ws.filter(isCircular(new Set(ws)), ws);

    // isCircular :: Set String -> String -> Bool
    const isCircular = lexicon => w => {
        const iLast = w.length - 1;
        return 1 < iLast && until(
            ([i, bln, s]) => iLast < i || !bln,
            ([i, bln, s]) => [1 + i, lexicon.has(s), rotated(s)],
            [0, true, rotated(w)]
        )[1];
    };

    // DISPLAY --------------------------------------------

    // showGroups :: [String] -> String
    const showGroups = xs =>
        unlines(map(
            gp => map(snd, gp).join(' -> '),
            groupBy(
                (a, b) => fst(a) === fst(b),
                sortBy(
                    comparing(fst),
                    map(x => Tuple(concat(sort(chars(x))), x),
                        xs
                    )
                )
            ).filter(gp => 1 < gp.length)
        ));

    // MAC OS JS FOR AUTOMATION ---------------------------

    // readFile :: FilePath -> IO String
    const readFile = fp => {
        const
            e = $(),
            uw = ObjC.unwrap,
            s = uw(
                $.NSString.stringWithContentsOfFileEncodingError(
                    $(fp)
                    .stringByStandardizingPath,
                    $.NSUTF8StringEncoding,
                    e
                )
            );
        return undefined !== s ? (
            s
        ) : uw(e.localizedDescription);
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = (a, b) => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // chars :: String -> [Char]
    const chars = s => s.split('');

    // comparing :: (a -> b) -> (a -> a -> Ordering)
    const comparing = f =>
        (x, y) => {
            const
                a = f(x),
                b = f(y);
            return a < b ? -1 : (a > b ? 1 : 0);
        };

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs =>
        0 < xs.length ? (() => {
            const unit = 'string' !== typeof xs[0] ? (
                []
            ) : '';
            return unit.concat.apply(unit, xs);
        })() : [];

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    const groupBy = (f, xs) => {
        const tpl = xs.slice(1)
            .reduce((a, x) => {
                const h = a[1].length > 0 ? a[1][0] : undefined;
                return (undefined !== h) && f(h, x) ? (
                    Tuple(a[0], a[1].concat([x]))
                ) : Tuple(a[0].concat([a[1]]), [x]);
            }, Tuple([], 0 < xs.length ? [xs[0]] : []));
        return tpl[0].concat([tpl[1]]);
    };

    // lines :: String -> [String]
    const lines = s => s.split(/[\r\n]/);

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // rotated :: String -> String
    const rotated = xs =>
        xs.slice(1) + xs[0];

    // showLog :: a -> IO ()
    const showLog = (...args) =>
        console.log(
            args
            .map(JSON.stringify)
            .join(' -> ')
        );

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // sort :: Ord a => [a] -> [a]
    const sort = xs => xs.slice()
        .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));

    // sortBy :: (a -> a -> Ordering) -> [a] -> [a]
    const sortBy = (f, xs) =>
        xs.slice()
        .sort(f);

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = (p, f, x) => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // MAIN ---
    return main();
})();


fromKelvin = function(temp)
    print temp + " degrees in Kelvin is:"
    Celsius = temp - 273.15
    print Celsius + " degrees Celsius"
    Fahrenheit = round(Celsius  * 9/5 + 32,2)
    print Fahrenheit + " degrees Fahrenheit"
    Rankine = Fahrenheit + 459.67
    print Rankine + " degrees Rankine"
end function

temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val


float: kelvin;

var float: celsius;
var float: fahrenheit;
var float: rankine;

constraint celsius == kelvin - 273.15;
constraint fahrenheit == celsius * 1.8 + 32;
constraint rankine == fahrenheit + 459.67;
solve satisfy;

output ["K \(kelvin)\n", "C \(celsius)\n", "F \(fahrenheit)\n", "R \(rankine)\n"];


on factorCount(n)
    if (n < 1) then return 0
    set counter to 2
    set sqrt to n ^ 0.5
    if (sqrt mod 1 = 0) then set counter to 1
    repeat with i from (sqrt div 1) to 2 by -1
        if (n mod i = 0) then set counter to counter + 2
    end repeat

    return counter
end factorCount

-- Task code:
local output, n, astid
set output to {"Positive divisor counts for integers 1 to 100:"}
repeat with n from 1 to 100
    if (n mod 20 = 1) then set end of output to linefeed
    set end of output to text -3 thru -1 of ("  " & factorCount(n))
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set output to output as text
set AppleScript's text item delimiters to astid
return output


/* ARM assembly Raspberry PI  */
/*  program taufunction.s   */

 /* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"

.equ MAXI,      100

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .asciz " @ "
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                  .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             @ entry of program
    mov r0,#1                     @ factor number one
    bl displayResult
    mov r0,#2                     @ factor number two
    bl displayResult
    mov r2,#3                     @ begin number three
1:                                @ begin loop
    mov r5,#2                     @ divisor counter
    mov r4,#2                     @ first divisor 1
2:
    udiv r0,r2,r4                 @ compute divisor 2
    mls r3,r0,r4,r2               @ remainder
    cmp r3,#0
    bne 3f                        @ remainder = 0 ?
    cmp r0,r4                     @ same divisor ?
    addeq r5,r5,#1                @ yes increment one
    addne r5,r5,#2                @ no increment two
3:
    add r4,r4,#1                  @ increment divisor
    cmp r4,r0                     @ divisor 1  < divisor 2
    blt 2b                        @ yes -> loop

    mov r0,r5                     @ equal -> display
    bl displayResult

    add r2,#1                     @
    cmp r2,#MAXI                  @ end ?
    bls 1b                        @ no -> loop

    ldr r0,iAdrszCarriageReturn
    bl affichageMess

100:                              @ standard end of the program
    mov r0, #0                    @ return code
    mov r7, #EXIT                 @ request to exit program
    svc #0                        @ perform the system call
iAdrszCarriageReturn:        .int szCarriageReturn
/***************************************************/
/*   display message number                        */
/***************************************************/
/* r0 contains the number            */
displayResult:
    push {r1,r2,lr}               @ save registers
    ldr r1,iAdrsZoneConv
    bl conversion10               @ call décimal conversion
    mov r2,#0
    strb r2,[r1,r0]
    ldr r0,iAdrsMessResult
    ldr r1,iAdrsZoneConv          @ insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess              @ display message
    pop {r1,r2,pc}                @ restaur des registres
iAdrsMessResult:     .int sMessResult
iAdrsZoneConv:       .int sZoneConv
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


# Output: an array of the words when read around the rim
def read_teacup:
  . as $in
  | [range(0; length) | $in[.:] + $in[:.] ];

# Boolean
def is_teacup_word($dict):
  . as $in
  | all( range(1; length); . as $i | $dict[ $in[$i:] + $in[:$i] ]) ;

# Output: a stream of the eligible teacup words
def teacup_words:
  def same_letters:
     explode
     | .[0] as $first
     | all( .[1:][]; . == $first);

  # Only consider one word in a teacup cycle
  def consider: explode | .[0] == min;

 # Create the dictionary
  reduce (inputs
           | select(length>2 and (same_letters|not))) as $w ( {};
     .[$w]=true )
  | . as $dict
  | keys[]
  | select(consider and is_teacup_word($dict)) ;

# The task:
teacup_words
| read_teacup


using HTTP

rotate(s, n) = String(circshift(Vector{UInt8}(s), n))

isliketea(w, d) = (n = length(w); n > 2 && any(c -> c != w[1], w) &&
    all(i -> haskey(d, rotate(w, i)), 1:n-1))

function getteawords(listuri)
    req = HTTP.request("GET", listuri)
    wdict = Dict{String, Int}((lowercase(string(x)), 1) for x in split(String(req.body), r"\s+"))
    sort(unique([sort([rotate(word, i) for i in 1:length(word)])
        for word in collect(keys(wdict)) if isliketea(word, wdict)]))
end

foreach(println, getteawords("https://www.mit.edu/~ecprice/wordlist.10000"))


const wc = new CS.System.Net.WebClient();
const lines = wc.DownloadString("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
const words = lines.split(/\n/g);
const collection = {};
words.filter(word => word.length > 2).forEach(word => {
  let allok = true;
  let newword = word;
  for (let i = 0; i < word.length - 1; i++) {
    newword = newword.substr(1) + newword.substr(0, 1);
    if (!words.includes(newword)) {
      allok = false;
      break;
    }
  }
  if (allok) {
    const key = word.split("").sort().join("");
    if (!collection[key]) {
      collection[key] = [word];
    } else {
      if (!collection[key].includes(word)) {
        collection[key].push(word);
      }
    }
  }
});
Object.keys(collection)
.filter(key => collection[key].length > 1)
.forEach(key => console.log("%s", collection[key].join(", ")));


fun KtoC n = n - 273.15;
fun KtoF n = n * 1.8 - 459.67;
fun KtoR n = n * 1.8;
val K = argv 0;

if K = false then
    println "mlite -f temcon.m <temp>"
else
    let
        val K = ston K
    in
        print "Kelvin:     "; println K;
        print "Celcius:    "; println ` KtoC K;
        print "Fahrenheit: "; println ` KtoF K;
        print "Rankine:    "; println ` KtoR K
    end


% while true
  ...   print "K ? "
  ...   k = float(input())
  ...
  ...   println format("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees.", k, k-273.15, k*1.8-459.67, k*1.8)
  ... end
K ? 21
21.0000 Kelvin = -252.150 Celsius = -421.870 Fahrenheit = 37.8000 Rankine degrees.
K ? 222.2
222.200 Kelvin = -50.9500 Celsius = -59.7100 Fahrenheit = 399.960 Rankine degrees.
K ?


tau: function [x] -> size factors x

loop split.every:20 1..100 => [
    print map & => [pad to :string tau & 3]
]


# syntax: GAWK -f TAU_FUNCTION.AWK
BEGIN {
    print("The tau functions for the first 100 positive integers:")
    for (i=1; i<=100; i++) {
      printf("%2d ",count_divisors(i))
      if (i % 10 == 0) {
        printf("\n")
      }
    }
    exit(0)
}
function count_divisors(n,  count,i) {
    for (i=1; i*i<=n; i++) {
      if (n % i == 0) {
        count += (i == n / i) ? 1 : 2
      }
    }
    return(count)
}


10 DEFINT A-Z
20 FOR I=1 TO 100
30 N=I: GOSUB 100
40 PRINT USING " ##";T;
50 IF I MOD 20=0 THEN PRINT
60 NEXT
70 END
100 T=1
110 IF (N AND 1)=0 THEN N=N\2: T=T+1: GOTO 110
120 P=3
130 GOTO 180
140 C=1
150 IF N MOD P=0 THEN N=N\P: C=C+1: GOTO 150
160 T=T*C
170 P=P+2
180 IF P*P<=N GOTO 140
190 IF N>1 THEN T=T*2
200 RETURN


ClearAll[Teacuppable]
TeacuppableHelper[set_List] := Module[{f, s},
  f = First[set];
  s = StringRotateLeft[f, #] & /@ Range[Length[set]];
  Sort[s] == Sort[set]
  ]
Teacuppable[set_List] := Module[{ss, l},
  l = StringLength[First[set]];
  ss = Subsets[set, {l}];
  Select[ss, TeacuppableHelper]
  ]
s = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "String"];
s //= StringSplit[#, "\n"] &;
s //= Select[StringLength /* GreaterThan[2]];
s //= Map[ToLowerCase];
s //= Map[{#, Sort[Characters[#]]} &];
s //= GatherBy[#, Last] &;
s //= Select[Length /* GreaterEqualThan[2]];
s = s[[All, All, 1]];
s //= Select[StringLength[First[#]] <= Length[#] &];
Flatten[Teacuppable /@ s, 1]


import sequtils, sets, sugar

let words = collect(initHashSet, for word in "unixdict.txt".lines: {word})

proc rotate(s: var string) =
  let first = s[0]
  for i in 1..s.high: s[i - 1] = s[i]
  s[^1] = first

var result: seq[string]
for word in "unixdict.txt".lines:
  if word.len >= 3:
    block checkWord:
      var w = word
      for _ in 1..w.len:
        w.rotate()
        if w notin words or w in result:
          # Not present in dictionary or already encountered.
          break checkWord
      if word.anyIt(it != word[0]):
        # More then one letter.
        result.add word

for word in result:
  var w = word
  stdout.write w
  for _ in 2..w.len:
    w.rotate()
    stdout.write " → ", w
  echo()


use strict;
use warnings;
use feature 'say';
use List::Util qw(uniqstr any);

my(%words,@teacups,%seen);

open my $fh, '<', 'ref/wordlist.10000';
while (<$fh>) {
    chomp(my $w = uc $_);
    next if length $w < 3;
    push @{$words{join '', sort split //, $w}}, $w;}

for my $these (values %words) {
    next if @$these < 3;
    MAYBE: for (@$these) {
        my $maybe = $_;
        next if $seen{$_};
        my @print;
        for my $i (0 .. length $maybe) {
            if (any { $maybe eq $_ } @$these) {
                push @print, $maybe;
                $maybe = substr($maybe,1) . substr($maybe,0,1)
            } else {
                @print = () and next MAYBE
            }
        }
        if (@print) {
            push @teacups, [@print];
            $seen{$_}++ for @print;
        }
    }
}

say join ', ', uniqstr @$_ for sort @teacups;


get "libhdr"

let tau(n) = valof
$(  let total = 1 and p = 3
    while (n & 1) = 0
    $(  total := total + 1
        n := n >> 1
    $)
    while p*p <= n
    $(  let count = 1
        while n rem p = 0
        $(  count := count + 1
            n := n / p
        $)
        total := total * count
        p := p + 2
    $)
    if n>1 then total := total * 2
    resultis total
$)

let start() be
    for n=1 to 100
    $(  writed(tau(n), 3)
        if n rem 20 = 0 then wrch('*N')
    $)


#include <stdio.h>

// See https://en.wikipedia.org/wiki/Divisor_function
unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    // Odd prime factors up to the square root
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int n;

    printf("Count of divisors for the first %d positive integers:\n", limit);
    for (n = 1; n <= limit; ++n) {
        printf("%3d", divisor_count(n));
        if (n % 20 == 0) {
            printf("\n");
        }
    }

    return 0;
}


#include <iomanip>
#include <iostream>

// See https://en.wikipedia.org/wiki/Divisor_function
unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1)
        ++total;
    // Odd prime factors up to the square root
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p)
            ++count;
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1)
        total *= 2;
    return total;
}

int main() {
    const unsigned int limit = 100;
    std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
    for (unsigned int n = 1; n <= limit; ++n) {
        std::cout << std::setw(3) << divisor_count(n);
        if (n % 20 == 0)
            std::cout << '\n';
    }
}


procedure filter_set(sequence anagrams)
    -- anagrams is a (small) set of words that are all anagrams of each other
    --  for example: {"angel","angle","galen","glean","lange"}
    -- print any set(s) for which every rotation is also present (marking as
    -- you go to prevent the same set appearing with each word being first)
    sequence used = repeat(false,length(anagrams))
    for i=1 to length(anagrams) do
        if not used[i] then
            used[i] = true
            string word = anagrams[i]
            sequence res = {word}
            for r=2 to length(word) do
                word = word[2..$]&word[1]
                integer k = find(word,anagrams)
                if k=0 then res = {} exit end if
                if not find(word,res) then
                    res = append(res,word)
                end if
                used[k] = true
            end for
            if length(res) then ?res end if
        end if
    end for
end procedure

procedure teacup(string filename, integer minlen=3, bool allow_mono=false)
    sequence letters,       -- a sorted word, eg "ate" -> "aet".
             words = {},    -- in eg {{"aet","ate"},...} form
             anagrams = {}, -- a set with same letters
             last = ""      -- (for building such sets)
    object word

    printf(1,"using %s",filename)
    integer fn = open(filename,"r")
    if fn=-1 then crash(filename&" not found") end if
    while 1 do
        word = lower(trim(gets(fn)))
        if atom(word) then exit end if
        if length(word)>=minlen then
            letters = sort(word)
            words = append(words, {letters, word})
        end if
    end while
    close(fn)
    printf(1,", %d words read\n",length(words))
    if length(words)!=0 then
        words = sort(words) -- group by anagram
        for i=1 to length(words) do
            {letters,word} = words[i]
            if letters=last then
                anagrams = append(anagrams,word)
            else
                if allow_mono or length(anagrams)>=length(last) then
                    filter_set(anagrams)
                end if
                last = letters
                anagrams = {word}
            end if
        end for
        if allow_mono or length(anagrams)>=length(last) then
            filter_set(anagrams)
        end if
    end if
end procedure

teacup(join_path({"demo","unixdict.txt"}))
-- These match output from other entries:
--teacup(join_path({"demo","unixdict.txt"}),allow_mono:=true)
--teacup(join_path({"demo","rosetta","mit.wordlist.10000.txt"}))
--teacup(join_path({"demo","rosetta","words.txt"}),4,true)
-- Note that allow_mono is needed to display eg {"agag","gaga"}


func KtoC(k : float) -> float { k - 273.15 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
func KtoR(k : float) -> float { k * 1.8 }

func convertK(k : float) -> int {
    prints("K " + k + "\n");
    prints("C " + KtoC(k) + "\n");
    prints("F " + KtoF(k) + "\n");
    prints("R " + KtoR(k) + "\n");
    0
}

func main(k : float) -> int {
    convertK(k);
    0
}


(define (to-celsius k)
    (- k 273.15)
)

(define (to-fahrenheit k)
    (- (* k 1.8) 459.67)
)

(define (to-rankine k)
    (* k 1.8)
)

(define (kelvinConversion k)
    (if (number? k)
        (println k " kelvin is equivalent to:\n"
            (to-celsius k) " celsius\n"
            (to-fahrenheit k) " fahrenheit\n"
            (to-rankine k) " rankine")
        (println "Please enter a number only, with no º or letter. ")
    )
)


tau = proc (n: int) returns (int)
    total: int := 1
    while n//2 = 0 do
        total := total + 1
        n := n/2
    end
    p: int := 3
    while p*p <= n do
        count: int := 1
        while n//p = 0 do
            count := count + 1
            n := n/p
        end
        total := total * count
        p := p+2
    end
    if n>1 then
        total := total * 2
    end
    return(total)
end tau

start_up = proc ()
    po: stream := stream$primary_output()
    for n: int in int$from_to(1, 100) do
        stream$putright(po, int$unparse(tau(n)), 3)
        if n//20=0 then stream$putl(po, "") end
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. TAU-FUNCTION.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 TAU-VARS.
          03 TOTAL              PIC 999.
          03 N                  PIC 999.
          03 FILLER             REDEFINES N.
             05 FILLER          PIC 99.
             05 FILLER          PIC 9.
                88 N-EVEN       VALUES 0, 2, 4, 6, 8.
          03 P                  PIC 999.
          03 P-SQUARED          PIC 999.
          03 N-DIV-P            PIC 999V999.
          03 FILLER             REDEFINES N-DIV-P.
             05 NEXT-N          PIC 999.
             05 FILLER          PIC 999.
                88 DIVISIBLE    VALUE ZERO.
          03 F-COUNT            PIC 999.
       01 CONTROL-VARS.
          03 I                  PIC 999.
       01 OUT-VARS.
          03 OUT-ITM            PIC ZZ9.
          03 OUT-STR            PIC X(80) VALUE SPACES.
          03 OUT-PTR            PIC 99 VALUE 1.

       PROCEDURE DIVISION.
       BEGIN.
           PERFORM SHOW-TAU VARYING I FROM 1 BY 1
               UNTIL I IS GREATER THAN 100.
           STOP RUN.

       SHOW-TAU.
           MOVE I TO N.
           PERFORM TAU.
           MOVE TOTAL TO OUT-ITM.
           STRING OUT-ITM DELIMITED BY SIZE INTO OUT-STR
               WITH POINTER OUT-PTR.
           IF OUT-PTR IS EQUAL TO 61,
               DISPLAY OUT-STR,
               MOVE 1 TO OUT-PTR.

       TAU.
           MOVE 1 TO TOTAL.
           PERFORM POWER-OF-2 UNTIL NOT N-EVEN.
           MOVE ZERO TO P-SQUARED.
           PERFORM ODD-FACTOR THRU ODD-FACTOR-LOOP
               VARYING P FROM 3 BY 2
               UNTIL P-SQUARED IS GREATER THAN N.
           IF N IS GREATER THAN 1,
               MULTIPLY 2 BY TOTAL.
       POWER-OF-2.
           ADD 1 TO TOTAL.
           DIVIDE 2 INTO N.
       ODD-FACTOR.
           MULTIPLY P BY P GIVING P-SQUARED.
           MOVE 1 TO F-COUNT.
       ODD-FACTOR-LOOP.
           DIVIDE N BY P GIVING N-DIV-P.
           IF DIVISIBLE,
               MOVE NEXT-N TO N,
               ADD 1 TO F-COUNT,
               GO TO ODD-FACTOR-LOOP.
           MULTIPLY F-COUNT BY TOTAL.


MODE ADDRESS = STRUCT(
	INT page,
	FLEX[50]CHAR street,
	FLEX[25]CHAR city,
	FLEX[2]CHAR state,
	FLEX[10]CHAR zip
);
FORMAT address repr = $"Page: "gl"Street: "gl"City: "gl"State: "gl"Zip: "gll$;

INT errno;
FILE sequence; errno := open(sequence, "sequence.txt", stand back channel);
SEMA sequence sema := LEVEL 1;

OP NEXTVAL = ([]CHAR table name)INT: (
  INT out;
  # INT table page = 0; # # only one sequence implemented #
  # DOWN sequence sema; # # NO interprocess concurrency protection #
    on open error(sequence,
      (REF FILE f)BOOL: (
        reset(sequence); #set(table page,1,1);#
        put(sequence, 0);
        try again;
        FALSE
      )
    );
    try again:
    reset(sequence); #set(table page,1,1);# get(sequence,out);
    out +:=1;
    reset(sequence); #set(table page,1,1);# put(sequence,out);
  # UP sequence sema; #
  out
);

OP INIT = (REF ADDRESS self)REF ADDRESS: ( page OF self := NEXTVAL "address"; self);

REF ADDRESS john brown = INIT LOC ADDRESS;

john brown := (page OF john brown, "10 Downing Street","London","England","SW1A 2AA");

printf((address repr, john brown));

FILE address table;
errno := open(address table,"address.txt",stand back channel);
# set(address table, page OF john brown,1,1);  - standard set page not available in a68g #
put bin(address table, john brown);
close(address table)


(de rotw (W)
   (let W (chop W)
      (unless (or (apply = W) (not (cddr W)))
         (make
            (do (length W)
               (link (pack (copy W)))
               (rot W) ) ) ) ) )
(off D)
(put 'D 'v (cons))
(mapc
   '((W)
      (idx 'D (cons (hash W) W) T) )
   (setq Words
      (make (in "wordlist.10000" (while (line T) (link @)))) ) )
(mapc
   println
   (extract
      '((W)
         (let? Lst (rotw W)
            (when
               (and
                  (fully
                     '((L) (idx 'D (cons (hash L) L)))
                     Lst )
                  (not
                     (member (car Lst) (car (get 'D 'v))) ) )
               (mapc
                  '((L) (push (get 'D 'v) L))
                  Lst )
               Lst ) ) )
      Words ) )


DataSection
  dname:
  Data.s "./Data/unixdict.txt"
  Data.s "./Data/wordlist.10000.txt"
  Data.s ""
EndDataSection

EnableExplicit
Dim c.s{1}(2)
Define.s txt, bset, res, dn
Define.i i,q, cw
Restore dname : Read.s dn
While OpenConsole() And ReadFile(0,dn)
  While Not Eof(0)
    cw+1
    txt=ReadString(0)
    If Len(txt)=3 : bset+txt+";" : EndIf
  Wend
  CloseFile(0)
  For i=1 To CountString(bset,";")
    PokeS(c(),StringField(bset,i,";"))
    If FindString(res,c(0)+c(1)+c(2)) : Continue : EndIf
    If c(0)=c(1) Or c(1)=c(2) Or c(0)=c(2) : Continue : EndIf
    If FindString(bset,c(1)+c(2)+c(0)) And FindString(bset,c(2)+c(0)+c(1))
      res+c(0)+c(1)+c(2)+~"\t"+c(1)+c(2)+c(0)+~"\t"+c(2)+c(0)+c(1)+~"\n"
    EndIf
  Next
  PrintN(res+Str(cw)+" words, "+Str(CountString(res,~"\n"))+" circular") : Input()
  bset="" : res="" : cw=0
  Read.s dn
Wend


import rdstdin, strutils, strfmt

while true:
  let k = parseFloat readLineFromStdin "K ? "
  echo "{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees".fmt(
    k, k - 273.15, k * 1.8 - 459.67, k * 1.8)


class Temperature {
  function : Main(args : String[]) ~ Nil {
    k := System.IO.Console->ReadString()->ToFloat();
    c := KelvinToCelsius(k);
    f := KelvinToFahrenheit(k);
    r := KelvinToRankine(k);

    "K: {$k}"->PrintLine();
    "C: {$c}"->PrintLine();
    "F: {$f}"->PrintLine();
    "R: {$r}"->PrintLine();
  }

  function : KelvinToCelsius(k : Float) ~ Float {
    return k - 273.15;
  }

  function : KelvinToFahrenheit(k : Float) ~ Float {
    return k * 1.8 - 459.67;
  }

  function : KelvinToRankine(k : Float) ~ Float {
    return k * 1.8;
  }
}


include "cowgol.coh";

typedef N is uint8;
sub tau(n: N): (total: N) is
    total := 1;
    while n & 1 == 0 loop
        total := total + 1;
        n := n >> 1;
    end loop;
    var p: N := 3;
    while p*p <= n loop
        var count: N := 1;
        while n%p == 0 loop
            count := count + 1;
            n := n / p;
        end loop;
        total := total * count;
        p := p + 2;
    end loop;
    if n>1 then
        total := total << 1;
    end if;
end sub;

sub print2(n: uint8) is
    print_char(' ');
    if n<10
        then print_char(' ');
        else print_i8(n/10);
    end if;
    print_i8(n%10);
end sub;

var n: N := 1;
while n <= 100 loop
    print2(tau(n));
    if n % 20 == 0 then print_nl(); end if;
    n := n + 1;
end loop;


import std.stdio;

// See https://en.wikipedia.org/wiki/Divisor_function
uint divisor_count(uint n) {
    uint total = 1;
    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    // Odd prime factors up to the square root
    for (uint p = 3; p * p <= n; p += 2) {
        uint count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1) {
        total *= 2;
    }
    return total;
}

void main() {
    immutable limit = 100;
    writeln("Count of divisors for the first ", limit, " positive integers:");
    for (uint n = 1; n <= limit; ++n) {
        writef("%3d", divisor_count(n));
        if (n % 20 == 0) {
            writeln;
        }
    }
}


program Tau_function;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function CountDivisors(n: Integer): Integer;
begin
  Result := 0;
  var i := 1;
  var k := 2;
  if (n mod 2) = 0 then
    k := 1;

  while i * i <= n do
  begin
    if (n mod i) = 0 then
    begin
      inc(Result);
      var j := n div i;
      if j <> i then
        inc(Result);
    end;
    inc(i, k);
  end;
end;

begin
  writeln('The tau functions for the first 100 positive integers are:');
  for var i := 1 to 100 do
  begin
    write(CountDivisors(i): 2, ' ');
    if (i mod 20) = 0 then
      writeln;
  end;
  readln;
end.


CREATE TABLE Address (
  addrID     INTEGER PRIMARY KEY generated BY DEFAULT AS IDENTITY,
  addrStreet VARCHAR(50) NOT NULL,
  addrCity   VARCHAR(50) NOT NULL,
  addrState  CHAR(2)     NOT NULL,
  addrZip    CHAR(10)    NOT NULL
);


db: open.sqlite "addresses.db"

query db {!sql
    CREATE TABLE address (
        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
        addrStreet TEXT NOT NULL,
        addrCity   TEXT NOT NULL,
        addrState  TEXT NOT NULL,
        addrZIP    TEXT NOT NULL
    )
}

close db


#!/bin/sh -f
awk '
BEGIN {
    print "Creating table..."
    dbExec("address.db", "create table address (street, city, state, zip);")
    print "Done."
    exit
}

function dbExec(db, qry,      result) {
    dbMakeQuery(db, qry) | getline result
    dbErrorCheck(result)
}

function dbMakeQuery(db, qry,      q) {
    q = dbEscapeQuery(qry) ";"
    return "echo \"" q "\" | sqlite3 " db
}

function dbEscapeQuery(qry,      q) {
    q = qry
    gsub(/"/, "\\\"", q)
    return q
}

function dbErrorCheck(res) {
    if (res ~ "SQL error") {
        print res
        exit
    }
}

'


#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

const char *code =
"CREATE TABLE address (\n"
"       addrID		INTEGER PRIMARY KEY AUTOINCREMENT,\n"
"	addrStreet	TEXT NOT NULL,\n"
"	addrCity	TEXT NOT NULL,\n"
"	addrState	TEXT NOT NULL,\n"
"	addrZIP		TEXT NOT NULL)\n" ;

int main()
{
  sqlite3 *db = NULL;
  char *errmsg;

  if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {
      fprintf(stderr, errmsg);
      sqlite3_free(errmsg);
      sqlite3_close(db);
      exit(EXIT_FAILURE);
    }
    sqlite3_close(db);
  } else {
    fprintf(stderr, "cannot open db...\n");
    sqlite3_close(db);
    exit(EXIT_FAILURE);
  }
  return EXIT_SUCCESS;
}


'''Teacup rim text'''

from itertools import chain, groupby
from os.path import expanduser
from functools import reduce

# main :: IO ()
def main():
    '''Circular anagram groups, of more than one word,
       and containing words of length > 2, found in:
       https://www.mit.edu/~ecprice/wordlist.10000
    '''
    print('\n'.join(
        concatMap(circularGroup)(
            anagrams(3)(
                # Reading from a local copy.
                lines(readFile('~/mitWords.txt'))
            )
        )
    ))

# anagrams :: Int -> [String] -> [[String]]
def anagrams(n):
    '''Groups of anagrams, of minimum group size n,
       found in the given word list.
    '''
    def go(ws):
        def f(xs):
            return [
                [snd(x) for x in xs]
            ] if n <= len(xs) >= len(xs[0][0]) else []
        return concatMap(f)(groupBy(fst)(sorted(
            [(''.join(sorted(w)), w) for w in ws],
            key=fst
        )))
    return go

# circularGroup :: [String] -> [String]
def circularGroup(ws):
    '''Either an empty list, or a list containing
       a string showing any circular subset found in ws.
    '''
    lex = set(ws)
    iLast = len(ws) - 1
    # If the set contains one word that is circular,
    # then it must contain all of them.
    (i, blnCircular) = until(
        lambda tpl: tpl[1] or (tpl[0] > iLast)
    )(
        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
    )(
        (0, False)
    )
    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []

# isCircular :: Set String -> String -> Bool
def isCircular(lexicon):
    '''True if all of a word's rotations
       are found in the given lexicon.
    '''
    def go(w):
        def f(tpl):
            (i, _, x) = tpl
            return (1 + i, x in lexicon, rotated(x))

        iLast = len(w) - 1
        return until(
            lambda tpl: iLast < tpl[0] or (not tpl[1])
        )(f)(
            (0, True, rotated(w))
        )[1]
    return go

# allRotations :: String -> [String]
def allRotations(w):
    '''All rotations of the string w.'''
    return takeIterate(len(w) - 1)(
        rotated
    )(w)

# GENERIC -------------------------------------------------

# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    '''A concatenated list over which a function has been mapped.
       The list monad can be derived by using a function f which
       wraps its output in a list,
       (using an empty list to represent computational failure).
    '''
    def go(xs):
        return chain.from_iterable(map(f, xs))
    return go

# fst :: (a, b) -> a
def fst(tpl):
    '''First member of a pair.'''
    return tpl[0]

# groupBy :: (a -> b) -> [a] -> [[a]]
def groupBy(f):
    '''The elements of xs grouped,
       preserving order, by equality
       in terms of the key function f.
    '''
    def go(xs):
        return [
            list(x[1]) for x in groupby(xs, key=f)
        ]
    return go

# lines :: String -> [String]
def lines(s):
    '''A list of strings,
       (containing no newline characters)
       derived from a single new-line delimited string.
    '''
    return s.splitlines()

# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumL(f):
    '''A tuple of an accumulation and a list derived by a
       combined map and fold,
       with accumulation from left to right.
    '''
    def go(a, x):
        tpl = f(a[0], x)
        return (tpl[0], a[1] + [tpl[1]])
    return lambda acc: lambda xs: (
        reduce(go, xs, (acc, []))
    )

# readFile :: FilePath -> IO String
def readFile(fp):
    '''The contents of any file at the path
       derived by expanding any ~ in fp.
    '''
    with open(expanduser(fp), 'r', encoding='utf-8') as f:
        return f.read()

# rotated :: String -> String
def rotated(s):
    '''A string rotated 1 character to the right.'''
    return s[1:] + s[0]

# snd :: (a, b) -> b
def snd(tpl):
    '''Second member of a pair.'''
    return tpl[1]

# takeIterate :: Int -> (a -> a) -> a -> [a]
def takeIterate(n):
    '''Each value of n iterations of f
       over a start value of x.
    '''
    def go(f):
        def g(x):
            def h(a, i):
                v = f(a) if i else x
                return (v, v)
            return mapAccumL(h)(x)(
                range(0, 1 + n)
            )[1]
        return g
    return go

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
    '''The result of repeatedly applying f until p holds.
       The initial seed value is x.
    '''
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go

# MAIN ---
if __name__ == '__main__':
    main()


#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        if(argc > 1)
        {
            NSString *arg1 = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
            // encoding shouldn't matter in this case
            double kelvin = [arg1 doubleValue];

            NSLog(@"K %.2f",kelvin);
            NSLog(@"C %.2f\n", kelvin - 273.15);
            NSLog(@"F %.2f\n", (kelvin * 1.8) - 459.67);
            NSLog(@"R %.2f", kelvin * 1.8);
        }
    }
    return 0;
}


let print_temp s t =
  print_string s;
  print_endline (string_of_float t);;

let kelvin_to_celsius k =
  k -. 273.15;;

let kelvin_to_fahrenheit k =
  (kelvin_to_celsius k)*. 9./.5. +. 32.00;;

let kelvin_to_rankine k =
  (kelvin_to_celsius k)*. 9./.5. +. 491.67;;

print_endline "Enter a temperature in Kelvin please:";
let k = read_float () in
print_temp "K " k;
print_temp "C " (kelvin_to_celsius k);
print_temp "F " (kelvin_to_fahrenheit k);
print_temp "R " (kelvin_to_rankine k);;


proc nonrec tau(word n) word:
    word count, total, p;
    total := 1;
    while n & 1 = 0 do
        total := total + 1;
        n := n >> 1
    od;
    p := 3;
    while p*p <= n do
        count := 1;
        while n % p = 0 do
            count := count + 1;
            n := n / p
        od;
        total := total * count;
        p := p + 2
    od;
    if n>1
        then total << 1
        else total
    fi
corp

proc nonrec main() void:
    byte n;
    for n from 1 upto 100 do
        write(tau(n):3);
        if n%20=0 then writeln() fi
    od
corp


func divisorCount(number) {
    var n = number
    var total = 1

    while (n &&& 1) == 0 {
        total += 1
        n >>>= 1
    }

    var p = 3
    while p * p <= n {
        var count = 1
        while n % p == 0 {
            count += 1
            n /= p
        }
        total *= count
        p += 2
    }

    if n > 1 {
        total *= 2
    }

    total
}

let limit = 100
print("Count of divisors for the first \(limit) positive integers:")
for n in 1..limit {
    print(divisorCount(number: n).ToString().PadLeft(2, ' ') + " ", terminator: "")
    print() when n % 20 == 0
}


// Tau function. Nigel Galloway: March 10th., 2021
let tau u=let P=primes32()
          let rec fN g=match u%g with 0->g |_->fN(Seq.head P)
          let rec fG n i g e l=match n=u,u%l with (true,_)->e |(_,0)->fG (n*i) i g (e+g)(l*i) |_->let q=fN(Seq.head P) in fG (n*q) q e (e+e) (q*q)
          let n=Seq.head P in fG 1 n 1 1 n
[1..100]|>Seq.iter(tau>>printf "%d "); printfn ""


USING: assocs formatting io kernel math math.primes.factors
math.ranges sequences sequences.extras ;

ERROR: nonpositive n ;

: (tau) ( n -- count )
    group-factors values [ 1 + ] map-product ; inline

: tau ( n -- count ) dup 0 > [ (tau) ] [ nonpositive ] if ;

"Number of divisors for integers 1-100:" print nl
" n   |                   tau(n)" print
"-----+-----------------------------------------" print
1 100 10 <range> [
    [ "%2d   |" printf ]
    [ dup 10 + [a,b) [ tau "%4d" printf ] each nl ] bi
] each


Func Tau(t) =
    if t<3 then Return(t) else
        numdiv:=2;
        for q = 2 to t\2 do
            if Divides(q, t) then numdiv:=numdiv+1 fi;
        od;
        Return(numdiv);
    fi;
    .;

for i = 1 to 100 do
    !(Tau(i),'  ');
od;


(require '[clojure.java.jdbc :as sql])
; Using h2database for this simple example.
(def db {:classname "org.h2.Driver"
         :subprotocol "h2:file"
         :subname "db/my-dbname"})

(sql/db-do-commands db
  (sql/create-table-ddl :address
    [:id "bigint primary key auto_increment"]
    [:street "varchar"]
    [:city "varchar"]
    [:state "varchar"]
    [:zip "varchar"]))


(lib 'struct)
(lib 'sql)

(define Postal (make-table
    (struct postal (auto: id name street city state zip))))

Postal
    → #table:#struct:postal [id name street city state zip]:[0]

(table-insert Postal '(0 Gallubert "29 rue de l'Ermitage" Paris Seine 75020))
(table-insert Postal '(0 Brougnard "666 rue des Cascades " Paris Seine 75042))
(table-make-index Postal 'postal.id)
(table-print Postal)

[0]   15  Gallubert  29 rue de l'Ermitage   Paris  Seine  75020
[1]   16  Brougnard  666 rue des Cascades   Paris  Seine  75042


-module( table_creation ).

-export( [task/0] ).

-record( address, {id, street, city, zip} ).

task() ->
	mnesia:start(),
	mnesia:create_table( address, [{attributes, record_info(fields, address)}] ).


my %*SUB-MAIN-OPTS = :named-anywhere;

unit sub MAIN ( $dict = 'unixdict.txt', :$min-chars = 3, :$mono = False );

my %words;
$dict.IO.slurp.words.map: { .chars < $min-chars ?? (next) !! %words{.uc.comb.sort.join}.push: .uc };

my @teacups;
my %seen;

for %words.values -> @these {
    next if !$mono && @these < 2;
    MAYBE: for @these {
        my $maybe = $_;
        next if %seen{$_};
        my @print;
        for ^$maybe.chars {
            if $maybe ∈ @these {
                @print.push: $maybe;
                $maybe = $maybe.comb.list.rotate.join;
            } else {
                @print = ();
                next MAYBE
            }
        }
        if @print.elems {
            @teacups.push: @print;
            %seen{$_}++ for @print;
        }
    }
}

say .unique.join(", ") for sort @teacups;


/*REXX pgm finds circular words (length>2),  using a dictionary,  suppress permutations.*/
parse arg iFID L .                               /*obtain optional arguments from the CL*/
if iFID==''|iFID==","  then iFID= 'wordlist.10k' /*Not specified?  Then use the default.*/
if    L==''|   L==","  then    L= 3              /* "      "         "   "   "     "    */
#= 0                                             /*number of words in dictionary, Len>L.*/
@.=                                              /*stemmed array of non─duplicated words*/
       do r=0  while lines(iFID) \== 0           /*read all lines (words) in dictionary.*/
       parse upper value  linein(iFID)  with z . /*obtain a word from the dictionary.   */
       if length(z)<L | @.z\==''  then iterate   /*length must be  L  or more,  no dups.*/
       if \datatype(z, 'U')       then iterate   /*Word contains non-letters?  Then skip*/
       @.z = z                                   /*assign a word from the dictionary.   */
       #= # + 1;     $.#= z                      /*bump word count; append word to list.*/
       end   /*r*/                               /* [↑]  dictionary need not be sorted. */
cw= 0                                            /*the number of circular words (so far)*/
say "There're "    r    ' entries in the dictionary (of all types):  '      iFID
say "There're "    #    ' words in the dictionary of at least length '      L
say
       do j=1  for #;      x= $.j;      y= x     /*obtain the  Jth  word in the list.   */
       if x==''  then iterate                    /*if a null, don't show variants.      */
       yy= y                                     /*the start of a list of the variants. */
                     do k=1  for length(x)-1     /*"circulate" the litters in the word. */
                     y= substr(y, 2)left(y, 1)   /*add the left letter to the right end.*/
                     if @.y==''  then iterate j  /*if not a word,  then skip this word. */
                     yy= yy','   y               /*append to the list of the variants.  */
                     @.y=                        /*nullify word to suppress permutations*/
                     end   /*k*/
       cw= cw + 1                                /*bump counter of circular words found.*/
       say 'circular word: '     yy              /*display a circular word and variants.*/
       end   /*j*/
say
say cw     ' circular words were found.'         /*stick a fork in it,  we're all done. */


: kelvinToCelsius  273.15 - ;
: kelvinToFahrenheit   1.8 * 459.67 - ;
: kelvinToRankine  1.8 * ;

: testTemp(n)
   n kelvinToCelsius println
   n kelvinToFahrenheit println
   n kelvinToRankine println ;


: divisor_count ( n -- n )
  1 >r
  begin
    dup 2 mod 0=
  while
    r> 1+ >r
    2/
  repeat
  3
  begin
    2dup dup * >=
  while
    1 >r
    begin
      2dup mod 0=
    while
      r> 1+ >r
      tuck / swap
    repeat
    2r> * >r
    2 +
  repeat
  drop 1 > if r> 2* else r> then ;

: print_divisor_counts ( n -- )
  ." Count of divisors for the first " dup . ." positive integers:" cr
  1+ 1 do
    i divisor_count 2 .r
    i 20 mod 0= if cr else space then
  loop ;

100 print_divisor_counts
bye


function numdiv( n as uinteger ) as uinteger
    dim as uinteger c = 1
    for i as uinteger = 1 to (n+1)\2
        if n mod i = 0 then c += 1
    next i
    if n=1 then c-=1
    return c
end function

for i as uinteger = 1 to 100
   print numdiv(i),
   if i mod 10 = 0 then print
next i


package main

import "fmt"

func countDivisors(n int) int {
    count := 0
    i := 1
    k := 2
    if n%2 == 0 {
        k = 1
    }
    for i*i <= n {
        if n%i == 0 {
            count++
            j := n / i
            if j != i {
                count++
            }
        }
        i += k
    }
    return count
}

func main() {
    fmt.Println("The tau functions for the first 100 positive integers are:")
    for i := 1; i <= 100; i++ {
        fmt.Printf("%2d  ", countDivisors(i))
        if i%20 == 0 {
            fmt.Println()
        }
    }
}


10 FOR N = 1 TO 100
20 IF N < 3 THEN T=N: GOTO 70
30 T=2
40 FOR A = 2 TO INT( (N+1)/2 )
50 IF N MOD A = 0 THEN T = T + 1
60 NEXT A
70 PRINT T;
80 IF N MOD 10 = 0 THEN PRINT
90 NEXT N


import db.*
import util.*

Class.forName( 'org.h2.Driver' )
conn = DriverManager.getConnection( 'jdbc:h2:mem:test', 'sa', '' )
statement = conn.createStatement()

statement.execute( '''
  CREATE TABLE `user_data` (
    `id` identity,
    `name` varchar(255) NOT NULL,
    `street` varchar(255) NOT NULL,
    `city` varchar(255) NOT NULL,
    `region` char(2) NOT NULL,
    `country` char(2) NOT NULL,
    `code` varchar(20) NOT NULL,
    `phone` varchar(20) NOT NULL,
    PRIMARY KEY (`id`)
  )''' )

statement.execute( '''
  INSERT INTO `user_data` (`name`, `street`, `city`, `region`, `code`, `country`, `phone`) VALUES
    ('Jacinthe Steinert', '8540 Fallen Pony Villas', 'Searights', 'IA', '51584-4315', 'US', '(641) 883-4342'),
    ('Keeley Pinkham', '1363 Easy Downs', 'Mileta', 'TX', '77667-7376', 'US', '(469) 527-4784'),
    ('Rimon Cleveland', '8052 Blue Pond Dale', 'The Willows', 'UT', '84630-2674', 'US', '(385) 305-7261'),
    ('Berenice Benda', '2688 Merry Pines', 'Dacono', 'HI', '96766-7398', 'US', '(808) 451-2732'),
    ('Mehetabel Marcano', '109 Sleepy Goose Crescent', 'Plains', 'UT', '84727-7254', 'US', '(385) 733-8404'),
    ('Ambria Schiller', '7100 Tawny Robin Highway', 'Barlowes', 'ID', '83792-2043', 'US', '(208) 227-8887'),
    ('Carne Cancino', '3842 Broad Pioneer Cape', 'Bardstown', 'IA', '51571-6473', 'US', '(563) 060-8352'),
    ('Ince Leite', '7876 Stony Fawn Boulevard', 'Easton', 'ID', '83651-9235', 'US', '(208) 951-3024'),
    ('Britney Odell', '3386 Lazy Shadow Thicket', 'Kimberly', 'OK', '73539-6632', 'US', '(539) 848-4448'),
    ('Suprabha Penton', '9311 Dusty Leaf Alley', 'Niumalu', 'GA', '39927-8332', 'US', '(404) 589-0183')''' )

result = statement.executeQuery( '''SELECT * FROM user_data WHERE region = 'ID' ORDER BY code''' )
print( TextTable.apply(result) )

conn.close()


package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    // task req: show database connection
    db, err := sql.Open("sqlite3", "rc.db")
    if err != nil {
        log.Print(err)
        return
    }
    defer db.Close()
    // task req: create table with typed fields, including a unique id
    _, err = db.Exec(`create table addr (
        id     int unique,
        street text,
        city   text,
        state  text,
        zip    text
    )`)
    if err != nil {
        log.Print(err)
        return
    }
    // show output:  query the created field names and types
    rows, err := db.Query(`pragma table_info(addr)`)
    if err != nil {
        log.Print(err)
        return
    }
    var field, storage string
    var ignore sql.RawBytes
    for rows.Next() {
        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
        if err != nil {
            log.Print(err)
            return
        }
        fmt.Println(field, storage)
    }
}


{-# LANGUAGE OverloadedStrings #-}

import Database.SQLite.Simple

main = do
     db <- open "postal.db"
     execute_ db "\
     \CREATE TABLE address (\
        \addrID     INTEGER PRIMARY KEY AUTOINCREMENT, \
        \addrStreet TEXT NOT NULL, \
        \addrCity   TEXT NOT NULL, \
        \addrState  TEXT NOT NULL, \
        \addrZIP    TEXT NOT NULL  \
     \)"
     close db


   Create__hd  'Address';noun define
addrID autoid;
addrStreet varchar
addrCity varchar
addrState char
addrZip char
)


use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;

fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> {
    let file = File::open(filename)?;
    let mut dict = BTreeSet::new();
    for line in io::BufReader::new(file).lines() {
        let word = line?;
        dict.insert(word);
    }
    Ok(dict)
}

fn find_teacup_words(dict: &BTreeSet<String>) {
    let mut teacup_words: Vec<&String> = Vec::new();
    let mut found: HashSet<&String> = HashSet::new();
    for word in dict {
        let len = word.len();
        if len < 3 || found.contains(word) {
            continue;
        }
        teacup_words.clear();
        let mut is_teacup_word = true;
        let mut chars: Vec<char> = word.chars().collect();
        for _ in 1..len {
            chars.rotate_left(1);
            if let Some(w) = dict.get(&String::from_iter(&chars)) {
                if !w.eq(word) && !teacup_words.contains(&w) {
                    teacup_words.push(w);
                }
            } else {
                is_teacup_word = false;
                break;
            }
        }
        if !is_teacup_word || teacup_words.is_empty() {
            continue;
        }
        print!("{}", word);
        found.insert(word);
        for w in &teacup_words {
            found.insert(w);
            print!(" {}", w);
        }
        println!();
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 2 {
        eprintln!("Usage: teacup dictionary");
        std::process::exit(1);
    }
    let dict = load_dictionary(&args[1]);
    match dict {
        Ok(dict) => find_teacup_words(&dict),
        Err(error) => eprintln!("Cannot open file {}: {}", &args[1], error),
    }
}


import Foundation

func loadDictionary(_ path: String) throws -> Set<String> {
    let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
    return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}

func rotate<T>(_ array: inout [T]) {
    guard array.count > 1 else {
        return
    }
    let first = array[0]
    array.replaceSubrange(0..<array.count-1, with: array[1...])
    array[array.count - 1] = first
}

func findTeacupWords(_ dictionary: Set<String>) {
    var teacupWords: [String] = []
    var found = Set<String>()
    for word in dictionary {
        if word.count < 3 || found.contains(word) {
            continue
        }
        teacupWords.removeAll()
        var isTeacupWord = true
        var chars = Array(word)
        for _ in 1..<word.count {
            rotate(&chars)
            let w = String(chars)
            if (!dictionary.contains(w)) {
                isTeacupWord = false
                break
            }
            if w != word && !teacupWords.contains(w) {
                teacupWords.append(w)
            }
        }
        if !isTeacupWord || teacupWords.isEmpty {
            continue
        }
        print(word, terminator: "")
        found.insert(word)
        for w in teacupWords {
            found.insert(w)
            print(" \(w)", terminator: "")
        }
        print()
    }
}

do {
    let dictionary = try loadDictionary("unixdict.txt")
    findTeacupWords(dictionary)
} catch {
    print(error)
}


import "io" for File
import "/str" for Str
import "/sort" for Find

var readWords = Fn.new { |fileName|
    var dict = File.read(fileName).split("\n")
    return dict.where { |w| w.count >= 3 }.toList
}

var dicts = ["mit10000.txt", "unixdict.txt"]
for (dict in dicts) {
    System.print("Using %(dict):\n")
    var words = readWords.call(dict)
    var n = words.count
    var used = {}
    for (word in words) {
        var outer = false
        var variants = [word]
        var word2 = word
        for (i in 0...word.count-1) {
            word2 = Str.lshift(word2)
            if (word == word2 || used[word2]) {
                outer = true
                break
            }
            var ix = Find.first(words, word2)
            if (ix == n || words[ix] != word2) {
                outer = true
                break
            }
            variants.add(word2)
        }
        if (!outer) {
            for (variant in variants) used[variant] = true
            System.print(variants)
        }
    }
    System.print()
}


// Limited to ASCII
// This is limited to the max items a Dictionary can hold
fcn teacut(wordFile){
   words:=File(wordFile).pump(Dictionary().add.fp1(True),"strip");
   seen :=Dictionary();
   foreach word in (words.keys){
      rots,w,sz := List(), word, word.len();
      if(sz>2 and word.unique().len()>2 and not seen.holds(word)){
	 do(sz-1){
	    w=String(w[-1],w[0,-1]);	// rotate one character
	    if(not words.holds(w)) continue(2);	// not a word, skip these
	    rots.append(w); 		// I'd like to see all the rotations
	 }
	 println(rots.append(word).sort().concat(" "));
	 rots.pump(seen.add.fp1(True));	// we've seen these rotations
      }
   }
}


program TemperatureConvert;

type
    TemperatureType = (C, F, K, R);

var
    kelvin: real;

    function ConvertTemperature(temperature: real; fromType, toType: TemperatureType): real;

    var
        initial, result: real;

    begin
        (* We are going to first convert whatever we're given into Celsius.
           Then we'll convert that into whatever we're asked to convert into.
           Maybe not the most efficient way to do this, but easy to understand
           and should make it easier to add any additional temperature units. *)
        if fromType <> toType then
            begin
                case fromType of (* first convert the temperature into Celsius *)
                    C:
                        initial := temperature;
                    F:
                        initial := (temperature - 32) / 1.8;
                    K:
                        initial := temperature - 273.15;
                    R:
                        initial := (temperature - 491.67) / 1.8;
                end;
                case toType of (* now convert from Celsius into whatever degree type was asked for *)
                    C:
                        result := initial;
                    F:
                        result := (initial * 1.8) + 32;
                    K:
                        result := initial + 273.15;
                    R:
                        result := (initial * 1.8) + 491.67;
                end;
            end
        else (* no point doing all that math if we're asked to convert from and to the same type *)
            result := temperature;
        ConvertTemperature := result;
    end;

begin
    write('Temperature to convert (in kelvins): ');
    readln(kelvin);
    writeln(kelvin : 3 : 2, ' in kelvins is ');
    writeln('    ', ConvertTemperature(kelvin, K, C) : 3 : 2, ' in degrees Celsius.');
    writeln('    ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.');
    writeln('    ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.');
end.


tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
    where
    yo i = (i, i * i)
    go r (i, ii)
        | n < ii = r
        | n == ii = r + 1
        | 0 == mod n i = go (r + 2) (yo $ i + 1)
        | otherwise = go r (yo $ i + 1)

main = print $ map tau [1..100]


public class TauFunction {
    private static long divisorCount(long n) {
        long total = 1;
        // Deal with powers of 2 first
        for (; (n & 1) == 0; n >>= 1) {
            ++total;
        }
        // Odd prime factors up to the square root
        for (long p = 3; p * p <= n; p += 2) {
            long count = 1;
            for (; n % p == 0; n /= p) {
                ++count;
            }
            total *= count;
        }
        // If n > 1 then it's prime
        if (n > 1) {
            total *= 2;
        }
        return total;
    }

    public static void main(String[] args) {
        final int limit = 100;
        System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%3d", divisorCount(n));
            if (n % 20 == 0) {
                System.out.println();
            }
        }
    }
}


using SQLite

db = SQLite.DB()
SQLite.execute!(db, """\
	CREATE TABLE address (
	addrID		INTEGER PRIMARY KEY AUTOINCREMENT,
	addrStreet	TEXT NOT NULL,
	addrCity	TEXT NOT NULL,
	addrState	TEXT NOT NULL,
	addrZIP		TEXT NOT NULL)
	""")


// Version 1.2.41

import java.io.File
import java.io.RandomAccessFile

fun String.toFixedLength(len: Int) = this.padEnd(len).substring(0, len)

class Address(
    var name: String,
    var street: String = "",
    var city: String = "",
    var state: String = "",
    var zipCode: String = "",
    val autoId: Boolean = true
) {
    var id = 0L
        private set

    init {
        if (autoId) id = ++nextId
    }

    companion object {
        private var nextId = 0L

        const val RECORD_LENGTH = 127  // including 2 bytes for UTF string length

        fun readRecord(file: File, id: Long): Address {
            val raf = RandomAccessFile(file, "r")
            val seekPoint = (id - 1) * RECORD_LENGTH
            raf.use {
                it.seek(seekPoint)
                val id2 = it.readLong()
                if (id != id2) {
                    println("Database is corrupt")
                    System.exit(1)
                }
                val text    = it.readUTF()
                val name    = text.substring(0, 30).trimEnd()
                val street  = text.substring(30, 80).trimEnd()
                val city    = text.substring(80, 105).trimEnd()
                val state   = text.substring(105, 107)
                val zipCode = text.substring(107).trimEnd()
                val a = Address(name, street, city, state, zipCode, false)
                a.id = id
                return a
            }
        }
    }

    override fun toString() =
        "Id       : ${this.id}\n" +
        "Name     : $name\n" +
        "Street   : $street\n" +
        "City     : $city\n" +
        "State    : $state\n" +
        "Zip Code : $zipCode\n"

    fun writeRecord(file: File) {
        val raf = RandomAccessFile(file, "rw")
        val text =
            name.toFixedLength(30) +
            street.toFixedLength(50) +
            city.toFixedLength(25) +
            state +
            zipCode.toFixedLength(10)
        val seekPoint = (id - 1) * RECORD_LENGTH
        raf.use {
            it.seek(seekPoint)
            it.writeLong(id)
            it.writeUTF(text)
        }
    }
}

fun main(args: Array<String>) {
    val file = File("addresses.dat")
    val addresses = listOf(
        Address("FSF Inc.", "51 Franklin Street", "Boston", "MA", "02110-1301"),
        Address("The White House", "The Oval Office, 1600 Pennsylvania Avenue NW", "Washington", "DC", "20500")
    )
    // write the address records to the file
    addresses.forEach { it.writeRecord(file) }

    // now read them back in reverse order and print them out
    for (i in 2 downTo 1) {
        println(Address.readRecord(file, i.toLong()))
    }
}


my %scale = (
    Celcius    => { factor => 1  , offset => -273.15 },
    Rankine    => { factor => 1.8, offset =>    0    },
    Fahrenheit => { factor => 1.8, offset => -459.67 },
);

print "Enter a temperature in Kelvin: ";
chomp(my $kelvin = <STDIN>);
die "No such temperature!\n" unless $kelvin > 0;

foreach (sort keys %scale) {
    printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
}


atom K = prompt_number("Enter temperature in Kelvin >=0: ",{0,1e307})
printf(1,"    Kelvin: %5.2f\n   Celsius: %5.2f\nFahrenheit: %5.2f\n   Rankine: %5.2f\n\n",
                      {K,                 K-273.15,          K*1.8-459.67,      K*1.8})


def count(s): reduce s as $x (0; .+1);

# For pretty-printing
def nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;


using Primes

function numfactors(n)
    f = [one(n)]
    for (p, e) in factor(n)
        f = reduce(vcat, [f * p^j for j in 1:e], init = f)
    end
    length(f)
end

for i in 1:100
    print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
end


function divisorCount(n)
    local total = 1
    -- Deal with powers of 2 first
    while (n & 1) == 0 do
        total = total + 1
        n = math.floor(n / 2)
    end
    -- Odd prime factors up tot eh square root
    local p = 3
    while p * p <= n do
        local count = 1
        while n % p == 0 do
            count = count + 1
            n = n / p
        end
        total = total * count
        p = p + 2
    end
    -- If n > 1 then it's prime
    if n > 1 then
        total = total * 2
    end
    return total
end

limit = 100
print("Count of divisors for the first " .. limit .. " positive integers:")
for n=1,limit do
    io.write(string.format("%3d", divisorCount(n)))
    if n % 20 == 0 then
        print()
    end
end


// connect to a Mysql database
inline(-database = 'rosettatest', -sql = "CREATE TABLE `address` (
    `id`       int(11)     NOT NULL   auto_increment,
    `street`   varchar(50) NOT NULL   default '',
    `city`     varchar(25) NOT NULL   default '',
    `state`    char(2)     NOT NULL   default '',
    `zip`      char(10)    NOT NULL   default '',
    PRIMARY KEY (`id`)
);
") => {^
	error_msg
^}


-- Import module
local sql = require("ljsqlite3")

-- Open connection to database file
local conn = sql.open("address.sqlite")

-- Create address table unless it already exists
conn:exec[[
CREATE TABLE IF NOT EXISTS address(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  street TEXT NOT NULL,
  city TEXT NOT NULL,
  state TEXT NOT NULL,
  zip TEXT NOT NULL)
]]

-- Explicitly close connection
conn:close()


TableCreation="CREATE TABLE address (
addrID		INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet	TEXT NOT NULL,	addrCity	TEXT NOT NULL,
addrState	TEXT NOT NULL,	addrZIP		TEXT NOT NULL    )";
Needs["DatabaseLink`"]
conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"]
SQLExecute[ conn, TableCreation]


CREATE TABLE `Address` (
    `addrID`       int(11)     NOT NULL   auto_increment,
    `addrStreet`   varchar(50) NOT NULL   default '',
    `addrCity`     varchar(25) NOT NULL   default '',
    `addrState`    char(2)     NOT NULL   default '',
    `addrZIP`      char(10)    NOT NULL   default '',
    PRIMARY KEY (`addrID`)
);


while (true) {
    echo "\nEnter a value in kelvin (q to quit): ";
    if ($kelvin = trim(fgets(STDIN))) {
        if ($kelvin == 'q') {
            echo 'quitting';
            break;
        }
        if (is_numeric($kelvin)) {
            $kelvin = floatVal($kelvin);
            if ($kelvin >= 0) {
                printf(" K  %2.2f\n", $kelvin);
                printf(" C  %2.2f\n", $kelvin - 273.15);
                printf(" F  %2.2f\n", $kelvin * 1.8 - 459.67);
                printf(" R  %2.2f\n", $kelvin * 1.8);
            } else printf(" %2.2f K is below absolute zero\n", $kelvin);
        }
    }
}


MODULE TauFunc;
FROM InOut IMPORT WriteCard, WriteLn;

VAR i: CARDINAL;

PROCEDURE tau(n: CARDINAL): CARDINAL;
    VAR total, count, p: CARDINAL;
BEGIN
    total := 1;
    WHILE n MOD 2 = 0 DO
        n := n DIV 2;
        total := total + 1
    END;
    p := 3;
    WHILE p*p <= n DO
        count := 1;
        WHILE n MOD p = 0 DO
            n := n DIV p;
            count := count + 1
        END;
        total := total * count;
        p := p + 2
    END;
    IF n>1 THEN total := total * 2 END;
    RETURN total;
END tau;

BEGIN
    FOR i := 1 TO 100 DO
        WriteCard(tau(i), 3);
        IF i MOD 20 = 0 THEN WriteLn END
    END
END TauFunc.


import math, strutils

func divcount(n: Natural): Natural =
  for i in 1..sqrt(n.toFloat).int:
    if n mod i == 0:
      inc result
      if n div i != i: inc result

echo "Count of divisors for the first 100 positive integers:"
for i in 1..100:
  stdout.write ($divcount(i)).align(3)
  if i mod 20 == 0: echo()


/* NetRexx */
options replace format comments java crossref symbols binary

import java.sql.Connection
import java.sql.Statement
import java.sql.SQLException
import java.sql.DriverManager

class RTableCreate01 public
  properties private constant
    addressDDL = String '' -
    ' create table Address' -
    ' (' -
    '   addrID     integer     primary key generated by default as identity,' -
    '   addrStreet varchar(50) not null,' -
    '   addrCity   varchar(50) not null,' -
    '   addrState  char(2)     not null,' -
    '   addrZip    char(10)    not null' -
    ' )'
    driver = String 'org.apache.derby.jdbc.EmbeddedDriver'
    dbName = String 'db/rosetta_code'

  method createTable() public static
    connectionURL = String
    conn = java.sql.Connection
    sqlStatement = java.sql.Statement
    do
      Class.forName(driver)
      connectionURL = 'jdbc:derby:' || dbName || ';' || 'create=true'
      conn = DriverManager.getConnection(connectionURL)
      sqlStatement = conn.createStatement()
      say 'Creating table'
      sqlStatement.execute(addressDDL)
      say 'Table creation complete'
      sqlStatement.close()
      conn.close()
      do
        -- In embedded mode, an application should shut down Derby.
        -- Shutdown throws the XJ015 exception to confirm success.
        connectionURL = 'jdbc:derby:' || ';' || 'shutdown=true'
        DriverManager.getConnection(connectionURL)
      catch sex = SQLException
        if sex.getSQLState().equals("XJ015") then do
          say 'Database shut down normally'
          end
        else do
          say 'Database did not shut down normally'
          signal sex
          end
      end
    catch sex = SQLException
      sex.printStackTrace()
    catch ex = ClassNotFoundException
      ex.printStackTrace()
    end
    return

  method main(args = String[]) public static
    createTable()
    return


import db_sqlite as db
#import db_mysql as db
#import db_postgres as db

const
  connection = ":memory:"
  user = "foo"
  pass = "bar"
  database = "db"

var c = open(connection, user, pass, database)
c.exec sql"""CREATE TABLE address (
  addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
  addrStreet TEXT NOT NULL,
  addrCity   TEXT NOT NULL,
  addrState  TEXT NOT NULL,
  addrZIP    TEXT NOT NULL)"""
c.close()


*process source attributes xref;
 /* PL/I **************************************************************
 * 15.08.2013 Walter Pachl translated from NetRexx
 * temperatures below 0K are considered invalid
 *********************************************************************/
 temperature: Proc Options(main);
 Dcl sysin record Input;
 On Endfile(sysin) Goto eoj;
 On Record(sysin);
 Dcl 1 dat,
      2 t Pic'SSSS9V.99',
      2 *    char( 1),
      2 from char(10),
      2 *    char( 1),
      2 to   char(10);
 Do Forever;
   Read File(sysin) Into(dat);
   If tc(t,from,'KELVIN')<0 Then
     Put Edit('Input (',t,from,') invalid. Below absolute zero')
             (Skip,a,f(8,2),x(1),a,a);
   Else
     Put edit(t,from,' -> ',tc(t,from,to),to)
             (skip,f(8,2),x(1),a(10),a,f(8,2),x(1),a(10));
   End;
 eoj: Return;

 tc: Procedure(T,scaleFrom,scaleTo) Returns(Dec Fixed(8,2));
 Dcl t Pic'SSSS9V.99';
 Dcl (val) Dec Fixed(8,2);
 Dcl (scaleFrom,scaleTo) Char(10);
  select(scaleFrom);
    when('KELVIN ') do;
      select(scaleTo);
        when('KELVIN    ') val = T;
        when('CELSIUS   ') val = T - 273.15;
        when('FAHRENHEIT') val = T * 9 / 5 - 459.67;
        when('RANKINE   ') val = T * 9 / 5;
        when('DELISLE   ') val = (373.15 - T) * 3 / 2;
        when('NEWTON    ') val = (T - 273.15) * 33 / 100;
        when('REAUMUR   ') val = (T - 273.15) * 4 / 5;
        when('ROEMER    ') val = (T - 273.15) * 21 / 40 + 7.5;
        otherwise Do;
          Put Edit('scaleTo=',scaleTo)(Skip,a,a);
          Call err(1);
          End;
        end;
      end;
    when('CELSIUS') do;
      select(scaleTo);
        when('KELVIN    ') val = T + 273.15;
        when('CELSIUS   ') val = T;
        when('FAHRENHEIT') val = T * 9 / 5 + 32;
        when('RANKINE   ') val = (T + 273.15) * 9 / 5;
        when('DELISLE   ') val = (100 - T) * 3 / 2;
        when('NEWTON    ') val = T * 33 / 100;
        when('REAUMUR   ') val = T * 4 / 5;
        when('ROEMER    ') val = T * 21 / 40 + 7.5;
        otherwise Call err(2);
        end;
      end;
    when('FAHRENHEIT') do;
      select(scaleTo);
        when('KELVIN    ') val = (T + 459.67) * 5 / 9;
        when('CELSIUS   ') val = (T - 32) * 5 / 9;
        when('FAHRENHEIT') val = T;
        when('RANKINE   ') val = T + 459.67;
        when('DELISLE   ') val = (212 - T) * 5 / 6;
        when('NEWTON    ') val = (T - 32) * 11 / 60;
        when('REAUMUR   ') val = (T - 32) * 4 / 9;
        when('ROEMER    ') val = (T - 32) * 7 / 24 + 7.5;
        otherwise Call err(3);
        end;
      end;
    when('RANKINE') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 5 / 9;
        when('CELSIUS   ') val = (T - 491.67) * 5 / 9;
        when('FAHRENHEIT') val = T - 459.67;
        when('RANKINE   ') val = T;
        when('DELISLE   ') val = (671.67 - T) * 5 / 6;
        when('NEWTON    ') val = (T - 491.67) * 11 / 60;
        when('REAUMUR   ') val = (T - 491.67) * 4 / 9;
        when('ROEMER    ') val = (T - 491.67) * 7 / 24 + 7.5;
        otherwise Call err(4);
        end;
      end;
    when('DELISLE') do;
      select(scaleTo);
        when('KELVIN    ') val = 373.15 - T * 2 / 3;
        when('CELSIUS   ') val = 100 - T * 2 / 3;
        when('FAHRENHEIT') val = 212 - T * 6 / 5;
        when('RANKINE   ') val = 671.67 - T * 6 / 5;
        when('DELISLE   ') val = T;
        when('NEWTON    ') val = 33 - T * 11 / 50;
        when('REAUMUR   ') val = 80 - T * 8 / 15;
        when('ROEMER    ') val = 60 - T * 7 / 20;
        otherwise Call err(5);
        end;
      end;
    when('NEWTON') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 100 / 33 + 273.15;
        when('CELSIUS   ') val = T * 100 / 33;
        when('FAHRENHEIT') val = T * 60 / 11 + 32;
        when('RANKINE   ') val = T * 60 / 11 + 491.67;
        when('DELISLE   ') val = (33 - T) * 50 / 11;
        when('NEWTON    ') val = T;
        when('REAUMUR   ') val = T * 80 / 33;
        when('ROEMER    ') val = T * 35 / 22 + 7.5;
        otherwise Call err(6);
        end;
      end;
    when('REAUMUR') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 5 / 4 + 273.15;
        when('CELSIUS   ') val = T * 5 / 4;
        when('FAHRENHEIT') val = T * 9 / 4 + 32;
        when('RANKINE   ') val = T * 9 / 4 + 491.67;
        when('DELISLE   ') val = (80 - T) * 15 / 8;
        when('NEWTON    ') val = T * 33 / 80;
        when('REAUMUR   ') val = T;
        when('ROEMER    ') val = T * 21 / 32 + 7.5;
        otherwise Call err(7);
        end;
      end;
    when('ROEMER') do;
      select(scaleTo);
        when('KELVIN    ') val = (T - 7.5) * 40 / 21 + 273.15;
        when('CELSIUS   ') val = (T - 7.5) * 40 / 21;
        when('FAHRENHEIT') val = (T - 7.5) * 24 / 7 + 32;
        when('RANKINE   ') val = (T - 7.5) * 24 / 7 + 491.67;
        when('DELISLE   ') val = (60 - T) * 20 / 7;
        when('NEWTON    ') val = (T - 7.5) * 22 / 35;
        when('REAUMUR   ') val = (T - 7.5) * 32 / 21;
        when('ROEMER    ') val = T;
        otherwise Call err(8);
        end;
      end;
    otherwise Call err(9);
    end;
  return(val);
  err: Proc(e);
  Dcl e Dec fixed(1);
  Put Edit('error ',e,' invalid input')(Skip,a,f(1),a);
  val=0;
  End;
  End;
 End;


:start:
I :argv.len == 1
   print(File(‘notes.txt’).read(), end' ‘’)
E
   V f = File(‘notes.txt’, ‘a’)
   f.write(Time().format("YYYY-MM-DD hh:mm:ss\n"))
   f.write("\t"(:argv[1..].join(‘ ’))"\n")


program tauFunction(output);

type
	{ name starts with `integer…` to facilitate sorting in documentation }
	integerPositive = 1..maxInt value 1;
	{ the `value …` will initialize all variables to this value }

{ returns Boolean value of the expression divisor ∣ dividend ----------- }
function divides(
		protected divisor: integerPositive;
		protected dividend: integer
	): Boolean;
begin
	{ in Pascal, function result variable has the same name as function }
	divides := dividend mod divisor = 0
end;

{ returns τ(i) --------------------------------------------------------- }
function tau(protected i: integerPositive): integerPositive;
var
	count, potentialDivisor: integerPositive;
begin
	{ count is initialized to 1 and every number is divisible by one }
	for potentialDivisor := 2 to i do
	begin
		count := count + ord(divides(potentialDivisor, i))
	end;

	{ in Pascal, there must be exactly one assignment to result variable }
	tau := count
end;

{ === MAIN ============================================================= }
var
	i: integerPositive;
	f: string(6);
begin
	for i := 1 to 100 do
	begin
		writeStr(f, 'τ(', i:1);
		writeLn(f:8, ') = ', tau(i):5)
	end
end.


use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';

my @x;
push @x, scalar divisors($_) for 1..100;

say "Tau function - first 100:\n" .
    ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);


/* REXX ***************************************************************
* 17.05.2013 Walter Pachl  translated from REXX version 2
* nice try? improvements are welcome as I am rather unexperienced
* 18.05.2013 the array may contain a variety of objects!
**********************************************************************/
alist=.array~new
alist[1]=.addr~new('Boston','MA','51 Franklin Street',,'FSF Inc.',,
                                                          '02110-1301')
alist[2]='not an address at all'
alist[3]=.addr~new('Washington','DC','The Oval Office',,
                 '1600 Pennsylvania Avenue NW','The White House',20500)
Do i=1 To alist~items
  a=alist[i]
  If a~isinstanceof(.addr) Then
    a~show
  End

::class addr
  ::attribute city
  ::attribute state
  ::attribute addr
  ::attribute addr2
  ::attribute name
  ::attribute zip

::method init
  Parse Arg self~city,,
            self~state,,
            self~addr,,
            self~addr2,,
            self~name,,
            self~zip

::method show
                         Say '  name -->' self~name
                         Say '  addr -->' self~addr
  If self~addr2<>'' Then Say ' addr2 -->' self~addr2
                         Say '  city -->' self~city
                         Say ' state -->' self~state
                         Say '   zip -->' self~zip
  Say copies('-',40)


CREATE SEQUENCE seq_address_pk START BY 100 INCREMENT BY 1
/
CREATE TABLE address (
    addrID   NUMBER DEFAULT seq_address_pk.NEXTVAL,
    street   VARCHAR2( 50 ) NOT NULL,
    city     VARCHAR2( 25 ) NOT NULL,
    state    VARCHAR2( 2 ) NOT NULL,
    zip      VARCHAR2( 20 ) NOT NULL,
    CONSTRAINT address_pk1 PRIMARY KEY ( addrID )
)
/


declare
  [Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}

  DB = {Sqlite.open 'test.db'}
in
  try

     {Sqlite.exec DB
      "CREATE TABLE address ("
      #"addrID		INTEGER PRIMARY KEY,"
      #"addrStreet	TEXT NOT NULL,"
      #"addrCity	TEXT NOT NULL,"
      #"addrState	TEXT NOT NULL,"
      #"addrZIP		TEXT NOT NULL"
      #")" _}

  catch E then
     {Inspector.configure widgetShowStrings true}
     {Inspect E}
  finally
     {Sqlite.close DB}
  end


To run:
Start up.
Put 21 into a kelvin temperature.
Show the kelvin temperature in various temperature scales.
Wait for the escape key.
Shut down.

A temperature is a fraction.
A kelvin temperature is a temperature.
A celsius temperature is a temperature.
A rankine temperature is a temperature.
A fahrenheit temperature is a temperature.

To convert a kelvin temperature to a celsius temperature:
Put the kelvin temperature minus 273-15/100 into the celsius temperature.

To convert a kelvin temperature to a rankine temperature:
Put the kelvin temperature times 9/5 into the rankine temperature.

To convert a kelvin temperature to a fahrenheit temperature:
Convert the kelvin temperature to a rankine temperature.
Put the rankine temperature minus 459-67/100 into the fahrenheit temperature.

To show a temperature given a temperature scale string:
Write the temperature scale then " = " then the temperature then " degrees" on the console.

To show a kelvin temperature in various temperature scales:
Convert the kelvin temperature to a celsius temperature.
Convert the kelvin temperature to a fahrenheit temperature.
Convert the kelvin temperature to a rankine temperature.
Show the kelvin temperature given "K".
Show the celsius temperature given "C".
Show the fahrenheit temperature given "F".
Show the rankine temperature given "R".


function temp($k){
    try{
        $c = $k - 273.15
        $r = $k / 5 * 9
        $f = $r - 459.67
    } catch {
        Write-host "Input error."
        return
    }

    Write-host ""
    Write-host "    TEMP (Kelvin)    : " $k
    Write-host "    TEMP (Celsius)   : " $c
    Write-host "    TEMP (Fahrenheit): " $f
    Write-host "    TEMP (Rankine)   : " $r
    Write-host ""

}

$input=Read-host "Enter a temperature in Kelvin"
temp $input


		bits	16
		cpu	8086
		;;;	MS-DOS PSP locations
cmdlen:		equ	80h		; Amount of characters on cmdline
cmdtail:	equ	82h		; Command line tail
		;;;	MS-DOS system calls
puts:		equ	9h		; Print string to console
date:		equ	2Ah		; Get system date
time:		equ	2Ch		; Get system time
creat:		equ	3Ch		; Create file
open:		equ	3Dh		; Open file
close:		equ	3Eh		; Close file
read: 		equ	3Fh		; Read from file
write:		equ	40h		; Write to file
lseek:		equ	42h		; Set current file position
exit:		equ	4ch		; Exit
		;;;	File modes
O_RDONLY:	equ	0
O_WRONLY:	equ	1
		;;;	Error codes (well, we only need the one)
ENOTFOUND:	equ	2
		;;;	File positions (again we need only the one)
FP_END:		equ	2
		;;;	File buffer size
BUFSZ:		equ	4096
section		.text
		org	100h
		cmp	byte [cmdlen],0	; Is the command line empty?
		je	printnotes	; Then, go print current notes
		;;;	Retrieve and format current date and time
		mov	ah,date		; Retrieve date
		int	21h
		mov	di,datefmt	; Fill in date string
		xor	ah,ah
		mov	al,dh		; Write month
		mov	bl,2		; Two digits
		call	asciinum
		add	di,3		; Onwards three positions
		mov	al,dl		; Write day
		mov	bl,2		; Two digits
		call	asciinum
		add	di,3		; Onwards three positions
		mov	ax,cx		; Write year
		mov	bl,4		; Four digits
		call	asciinum
		mov	ah,time		; Get system time
		int	21h
		mov	di,timefmt+6	; Fill in time string
		xor	ah,ah
		mov	al,dh		; Write seconds
		mov	bl,2		; Two digits
		call	asciinum
		sub	di,3		; Back three positions
		mov	al,cl		; Write minutes
		mov	bl,2		; Two digits
		call	asciinum
		cmp	ch,12		; AM or PM?
		jbe 	houram		; <=12, AM
		sub	ch,12 		; PM - subtract 12 hours,
		mov	byte [ampm],'P'	; And set the AM/PM to 'P'(M)
		jmp	wrhours
houram:		and	ch,ch		; Hour 0 is 12:XX:XX AM.
		jnz	wrhours
		mov	ch,12
wrhours:	sub	di,3		; Back three positions
		mov 	al,ch		; Write hours
		mov	bl,2		; Two digits
		call	asciinum
		;;;	Open or create the NOTES.TXT file
		mov	dx,filnam
		mov	ax,open<<8|O_WRONLY
		int	21h		; Try to open the file
		jnc	writenote	; If successful, go write the note
		cmp 	al,ENOTFOUND	; File not found?
		jne	diefile		; Some other error = print error msg
		mov	ah,creat	; No notes file, try to create it
		xor	cx,cx		; Normal file (no attributes set)
		int	21h
		jc	diefile		; If that fails too, print error msg
		;;;	Write the note to the file
writenote:	mov	bx,ax		; File handle in BX
		mov	ax,lseek<<8|FP_END	; Seek to end of file
		xor	cx,cx		; Offset 0
		xor	dx,dx
		int	21h
		jc	diefile		; Error if it fails
		mov	dx,datetime	; Write the date/time string first
		mov	cx,dtsize
		mov	ah,write
		int	21h
		jc	diefile		; Error if it fails
		mov	cx,bx		; Store file handle in CX
		;;;	Terminate note with \r\n
		xor	bx,bx		; BX = length of command line
		mov	bl,[cmdlen]	; Find 2 bytes past cmd input
		add	bx,cmdlen+1	; Note: this might overwrite the first
		mov	word [bx],0A0Dh	; instruction, but we don't need it
		sub	bx,cmdtail-2	; Get length (add 2 for the 0D0A)
		xchg	bx,cx		; File handle in BX, length in CX
		mov	dx,cmdtail	; Write what's on the command line
		mov	ah,write
		int	21h
		jc	diefile		; Error if it fails.
		jmp	closeexit	; Close file and exit if it succeeds.
		;;;	Print the contents of the NOTES.TXT file
printnotes:	mov	dx,filnam	; Open file for reading
		mov	ax,open<<8|O_RDONLY
		int	21h
		jnc	readnotes	; Carry flag set = error.
		cmp	al,ENOTFOUND	; File not found?
		jne	diefile		; Some other error = print error msg
		jmp	exitok 		; Not found = no notes = just exit
readnotes:	mov	di,ax 		; Keep the file handle in DI.
.loop		mov	bx,di		; Get file handle for file
		mov	cx,BUFSZ	; Read as many bytes as will fit in the
		mov	ah,read		; buffer
		int	21h
		jc	diefile		; Carry flag set = error
		and	ax,ax		; If 0 bytes read, we're done.
		jz	.done
		xor	bx,bx		; File handle 0 = standard output
		mov	cx,ax		; Write as many bytes as we read
		mov 	ah,write
		int	21h
		jc	diefile
		jmp	.loop		; Go get more bytes if there are any
.done		mov	bx,di		; Done: close the file
closeexit:	mov	ah,close
		int	21h
exitok:		mov	ax,exit<<8|0	; Exit with errorlevel 0 (success)
		int	21h
		;;;	Print 'File error' and exit.
diefile:	mov 	dx,fileerror
		;;;	Print error message in DX and exit
die:		mov	ah,puts		; Print error message
		int	21h
		mov	ax,exit<<8|2	; Exit with errorlevel 2.
		int	21h
		;;;	Subroutine: write AX as BL-digit ASCII number at [DI]
asciinum:	push	dx		; Store DX and CX
		push	cx
		mov	cx,10 		; CX = divisor
		xor	bh,bh		; We never need >255.
.loop:		xor	dx,dx		; Set high word of division to 0.
		div	cx 		; AX /= CX; DX = AX % CX
		add	dl,'0'		; Make digit ASCII
		dec	bl		; Move forward one digit
		mov	[di+bx],dl	; Store digit
		jnz	.loop		; Are we there yet?
		pop 	cx		; Restore DX and CX
		pop 	dx
		ret
section		.data
datetime:	equ	$		; Start of date/time string.
datefmt:	db	'**/**/**** '	; Date placeholder,
timefmt:	db	'**:**:** '	; Time placeholder,
ampm:		db	'AM'		; AM/PM placeholder.
		db	13,10,9		; \r\n\t
dtsize:		equ	$-datetime	; Size of date/time string.
fileerror:	db	'File error.$'	; Printed on error
filnam:		db	'NOTES.TXT',0	; File name to use
section		.bss
filebuf:	resb	BUFSZ		; 4K file buffer


for i=1 to 100 do
    printf(1,"%3d",{length(factors(i,1))})
    if remainder(i,20)=0 then puts(1,"\n") end if
end for


taufunc: procedure options(main);
    tau: procedure(nn) returns(fixed);
        declare (n, nn, tot, pf, cnt) fixed;
	tot = 1;
	do n=nn repeat(n/2) while(mod(n,2)=0);
            tot = tot + 1;
        end;
        do pf=3 repeat(pf+2) while(pf*pf<=n);
            do cnt=1 repeat(cnt+1) while(mod(n,pf)=0);
               n = n/pf;
            end;
            tot = tot * cnt;
        end;
        if n>1 then tot = tot * 2;
	return(tot);
    end tau;

    declare n fixed;
    do n=1 to 100;
        put edit(tau(n)) (F(3));
        if mod(n,20)=0 then put skip;
    end;
end taufunc;


V cubes = (1..1199).map(x -> Int64(x) ^ 3)
[Int64 = Int64] crev
L(x3) cubes
   crev[x3] = L.index + 1

V sums = sorted(multiloop_filtered(cubes, cubes, (x, y) -> y < x, (x, y) -> x + y))

V idx = 0
L(i) 1 .< sums.len - 1
   I sums[i - 1] != sums[i] & sums[i] == sums[i + 1]
      idx++
      I (idx > 25 & idx < 2000) | idx > 2006
         L.continue

      V n = sums[i]
      [(Int64, Int64)] p
      L(x) cubes
         I n - x < x
            L.break
         I n - x C crev
            p.append((crev[x], crev[n - x]))
      print(‘#4: #10’.format(idx, n), end' ‘ ’)
      L(x1, x2) p
         print(‘ = #4^3 + #4^3’.format(x1, x2), end' ‘ ’)
      print()


use DBI;

my $db = DBI->connect('DBI:mysql:database:server','login','password');

my $statment = <<EOF;
CREATE TABLE `Address` (
    `addrID`       int(11)     NOT NULL   auto_increment,
    `addrStreet`   varchar(50) NOT NULL   default '',
    `addrCity`     varchar(25) NOT NULL   default '',
    `addrState`    char(2)     NOT NULL   default '',
    `addrZIP`      char(10)    NOT NULL   default '',
    PRIMARY KEY (`addrID`)
);
EOF

my $exec = $db->prepare($statment);
$exec->execute;


without js -- (file i/o)
include pSQLite.e
constant sqlcode = """
CREATE TABLE address (
 addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
 addrStreet TEXT NOT NULL,
 addrCity   TEXT NOT NULL,
 addrState  TEXT NOT NULL,
 addrZIP    TEXT NOT NULL)"""

sqlite3 db = sqlite3_open("address.sqlite")
integer res = sqlite3_exec(db,sqlcode)
if res=SQLITE_OK then
    sqlite3_close(db)
else
    -- can show eg "sqlite3_exec error: 1 [table address already exists]"
    printf(1,"sqlite3_exec error: %d [%s]\n",{res,sqlite_last_exec_err})
end if


<?php
$db = new SQLite3(':memory:');
$db->exec("
    CREATE TABLE address (
        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
        addrStreet TEXT NOT NULL,
        addrCity   TEXT NOT NULL,
        addrState  TEXT NOT NULL,
        addrZIP    TEXT NOT NULL
    )
");
?>


(class +Adr +Entity)
(rel nm (+Sn +Idx +String))            # Name [Soundex index]
(rel str (+String))                    # Street
(rel zip (+Ref +String))               # ZIP [Non-unique index]
(rel cit (+Fold +Idx +String))         # City [Folded substring index]
(rel st (+String))                     # State
(rel tel (+Fold +Ref +String))         # Phone [Folded non-unique index]
(rel em (+Ref +String))                # EMail [Non-unique index]
(rel txt (+Blob))                      # Memo
(rel jpg (+Blob))                      # Photo

(pool "address.db")  # Create database


Procedure.d Kelvin2Celsius(tK.d)    : ProcedureReturn tK-273.15     : EndProcedure
Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure
Procedure.d Kelvin2Rankine(tK.d)    : ProcedureReturn tK*1.8        : EndProcedure

OpenConsole()
Repeat
  Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input())
  PrintN("Conversion:")
  PrintN(#TAB$+"Celsius   "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32)))
  PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32)))
  PrintN(#TAB$+"Rankine   "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32)))
  PrintN("ESC = End.")
  Repeat
    k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf
  Until RawKey()
ForEver


>>> while True:
    k = float(input('K ? '))
    print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
          % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))

K ? 21.0
21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees.
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
K ?


with Ada.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.IO_Exceptions;
with Ada.Text_IO;
procedure Notes is
   Notes_Filename : constant String := "notes.txt";
   Notes_File     : Ada.Text_IO.File_Type;
   Argument_Count : Natural         := Ada.Command_Line.Argument_Count;
begin
   if Argument_Count = 0 then
      begin
         Ada.Text_IO.Open
           (File => Notes_File,
            Mode => Ada.Text_IO.In_File,
            Name => Notes_Filename);
         while not Ada.Text_IO.End_Of_File (File => Notes_File) loop
            Ada.Text_IO.Put_Line (Ada.Text_IO.Get_Line (File => Notes_File));
         end loop;
      exception
         when Ada.IO_Exceptions.Name_Error =>
            null;
      end;
   else
      begin
         Ada.Text_IO.Open
           (File => Notes_File,
            Mode => Ada.Text_IO.Append_File,
            Name => Notes_Filename);
      exception
         when Ada.IO_Exceptions.Name_Error =>
            Ada.Text_IO.Create (File => Notes_File, Name => Notes_Filename);
      end;
      Ada.Text_IO.Put_Line
        (File => Notes_File,
         Item => Ada.Calendar.Formatting.Image (Date => Ada.Calendar.Clock));
      Ada.Text_IO.Put (File => Notes_File, Item => Ada.Characters.Latin_1.HT);
      for I in 1 .. Argument_Count loop
         Ada.Text_IO.Put
           (File => Notes_File,
            Item => Ada.Command_Line.Argument (I));
         if I /= Argument_Count then
            Ada.Text_IO.Put (File => Notes_File, Item => ' ');
         end if;
      end loop;
      Ada.Text_IO.Flush (File => Notes_File);
   end if;
   if Ada.Text_IO.Is_Open (File => Notes_File) then
      Ada.Text_IO.Close (File => Notes_File);
   end if;
end Notes;


#! /usr/local/bin/aime -a

if (argc() == 1) {
    file f;
    text s;

    f.affix("NOTES.TXT");

    while (~f.line(s)) {
        o_(s, "\n");
    }
} else {
    date d;
    file f;

    f.open("NOTES.TXT", OPEN_APPEND | OPEN_CREATE | OPEN_WRITEONLY, 0644);

    d.now;

    f.form("/f4/-/f2/-/f2/ /f2/:/f2/:/f2/\n", d.year, d.y_month,
           d.m_day, d.d_hour, d.h_minute, d.m_second);

    for (integer i, text s in 1.args) {
        f.bytes(i ? ' ' : '\t', s);
    }

    f.byte('\n');
}


100H:

/* CP/M BDOS FUNCTIONS */
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PR$CHAR: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PR$CHAR;
PR$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PR$STR;

/* PRINT BYTE IN A 3-CHAR COLUMN */
PRINT3: PROCEDURE(N);
    DECLARE (N, M) BYTE;
    M = 100;
    DO WHILE M>0;
        IF N>=M
            THEN CALL PR$CHAR('0' + (N/M) MOD 10);
            ELSE CALL PR$CHAR(' ');
        M = M/10;
    END;
END PRINT3;

/* TAU FUNCTION */
TAU: PROCEDURE(N) BYTE;
    DECLARE (N, TOTAL, COUNT, P) BYTE;
    TOTAL = 1;
    DO WHILE NOT N;
        N = SHR(N,1);
        TOTAL = TOTAL + 1;
    END;
    P = 3;
    DO WHILE P*P <= N;
        COUNT = 1;
        DO WHILE N MOD P = 0;
            COUNT = COUNT + 1;
            N = N / P;
        END;
        TOTAL = TOTAL * COUNT;
        P = P + 2;
    END;
    IF N>1 THEN TOTAL = SHL(TOTAL, 1);
    RETURN TOTAL;
END TAU;

/* PRINT TAU 1..100 */
DECLARE N BYTE;
DO N=1 TO 100;
    CALL PRINT3(TAU(N));
    IF N MOD 20=0 THEN CALL PR$STR(.(13,10,'$'));
END;
CALL EXIT;
EOF


If OpenConsole()
  For i=1 To 100
    If i<3 : Print(RSet(Str(i),4)) : Continue :EndIf
    c=2
    For j=2 To i/2+1 : c+Bool(i%j=0) : Next
    Print(RSet(Str(c),4))
    If i%10=0 : PrintN("") : EndIf
  Next
  Input()
EndIf
End


# syntax: GAWK -f TAXICAB_NUMBERS.AWK
BEGIN {
    stop = 99
    for (a=1; a<=stop; a++) {
      for (b=1; b<=stop; b++) {
        n1 = a^3 + b^3
        for (c=1; c<=stop; c++) {
          if (a == c) { continue }
          for (d=1; d<=stop; d++) {
            n2 = c^3 + d^3
            if (n1 == n2 && (a != d || b != c)) {
              if (n1 in arr) { continue }
              arr[n1] = sprintf("%7d = %2d^3 + %2d^3 = %2d^3 + %2d^3",n1,a,b,c,d)
            }
          }
        }
      }
    }
    PROCINFO["sorted_in"] = "@ind_num_asc"
    for (i in arr) {
      if (++count <= 25) {
        printf("%2d: %s\n",count,arr[i])
      }
    }
    printf("\nThere are %d taxicab numbers using bounds of %d\n",length(arr),stop)
    exit(0)
}


CREATE SEQUENCE address_seq START 100;
CREATE TABLE address (
    addrID   int4 PRIMARY KEY DEFAULT NEXTVAL('address_seq'),
    street   VARCHAR(50) NOT NULL,
    city     VARCHAR(25) NOT NULL,
    state    VARCHAR(2) NOT NULL,
    zip      VARCHAR(20) NOT NULL
);


Import-Module -Name PSSQLite

## Create a database and a table
$dataSource = ".\Addresses.db"
$query = "CREATE TABLE SSADDRESS (Id        INTEGER  PRIMARY KEY  AUTOINCREMENT,
                                  LastName  TEXT     NOT NULL,
                                  FirstName TEXT     NOT NULL,
                                  Address   TEXT     NOT NULL,
                                  City      TEXT     NOT NULL,
                                  State     CHAR(2)  NOT NULL,
                                  Zip       CHAR(5)  NOT NULL
)"

Invoke-SqliteQuery -Query $Query -DataSource $DataSource

## Insert some data
$query = "INSERT INTO SSADDRESS ( FirstName,  LastName,  Address,  City,  State,  Zip)
                         VALUES (@FirstName, @LastName, @Address, @City, @State, @Zip)"

Invoke-SqliteQuery -DataSource $DataSource -Query $query -SqlParameters @{
        LastName  = "Monster"
        FirstName = "Cookie"
        Address   = "666 Sesame St"
        City      = "Holywood"
        State     = "CA"
        Zip       = "90013"
}

## View the data
Invoke-SqliteQuery -DataSource $DataSource -Query "SELECT * FROM SSADDRESS" | FormatTable -AutoSize


UseSQLiteDatabase()
Procedure CheckDatabaseUpdate(Database, Query$)
   Result = DatabaseUpdate(Database, Query$)
   If Result = 0
      Print(DatabaseError())
   EndIf
   ProcedureReturn Result
EndProcedure
openconsole()
DatabaseFile$ = GetCurrentDirectory()+"/rosettadb.sdb"
If CreateFile(0, DatabaseFile$)
   CloseFile(0)
    If OpenDatabase(0, DatabaseFile$, "", "")
      CheckDatabaseUpdate(0,"CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT,	addrStreet TEXT Not NULL, addrCity TEXT Not NULL, addrState TEXT Not NULL, addrZIP TEXT Not NULL)")
      CloseDatabase(0)
   Else
      print("Can't open database !")
   EndIf
Else
   print("Can't create the database file !")
EndIf
closeconsole()


  [ $ "bigrat.qky" loadfile ] now!

  [ 5 9 v* ]                        is r->k ( n/d --> n/d )
  [ 1/v r->k 1/v ]                  is k->r ( n/d --> n/d )

  [ 45967 100 v- ]                  is r->f ( n/d --> n/d )
  [ -v r->f -v ]                    is f->r ( n/d --> n/d )

  [ 5463 20 v- ]                    is k->c ( n/d --> n/d )
  [ -v k->c -v ]                    is c->k ( n/d --> n/d )

  [ k->r r->f ]                     is k->f ( n/d --> n/d )
  [ f->r r->k ]                     is f->k ( n/d --> n/d )

  [ r->k k->c ]                     is r->c ( n/d --> n/d )
  [ c->k k->r ]                     is c->r ( n/d --> n/d )

  [ f->k k->c ]                     is f->c ( n/d --> n/d )
  [ c->r r->f ]                     is c->f ( n/d --> n/d )

  [ $->v drop
         2dup 10 point$ echo$
    say " Kelvins is equal to" cr
    k->c 2dup 10 point$ echo$
    say " degrees Celcius"     cr
    c->f 2dup 10 point$ echo$
    say " degrees Fahrenheit"  cr
    f->r      10 point$ echo$
    say " degrees Rankine"     cr ] is task (   $ -->     )

  $ "21.00" task


convert_Kelvin <- function(K){
    if (!is.numeric(K))
      stop("\n Input has to be numeric")

    return(list(
      Kelvin = K,
      Celsius = K - 273.15,
      Fahreneit = K * 1.8 - 459.67,
      Rankine = K * 1.8
    ))

  }

  convert_Kelvin(21)


#lang racket
(define (converter temp init final)
  (define to-k
    (case init
      ('k temp)
      ('c (+ 273.15 temp))
      ('f (* (+ temp 459.67) 5/9))
      ('r (* temp 5/9))))
  (case final
    ('k to-k)
    ('c (- to-k 273.15))
    ('f (- (* to-k 9/5) 459.67))
    ('r (* to-k 1.8))))

(define (kelvin-to-all temp)
  (display (format "Kelvin: ~a \nCelsius: ~a \nFahrenheit: ~a \nRankine: ~a \n"
                   temp
                   (converter temp 'k 'c)
                   (converter temp 'k 'f)
                   (converter temp 'k 'r))))
(kelvin-to-all 21)
;Kelvin: 21
;Celsius: -252.14999999999998
;Fahrenheit: -421.87
;Rankine: 37.800000000000004


#!/usr/local/bin/apl -s --

∇r←ch Join ls                          ⍝ Join list of strings with character
        r←1↓∊ch,¨ls
∇

∇d←Date                                ⍝ Get system date as formatted string
        d←'/'Join ⍕¨1⌽3↑⎕TS
∇

∇t←Time;t24                            ⍝ Get system time as formatted string
        t←t24←3↑3↓⎕TS                  ⍝ Get system time
        t[1]←t[1]-12×t24[1]≥12         ⍝ If PM (hour≥12), subtract 12 from hour
        t[1]←t[1]+12×t[1]=0            ⍝ Hour 0 is hour 12 (AM)
        t←¯2↑¨'0',¨⍕¨t                 ⍝ Convert numbers to 2-digit strings
        t←(':'Join t),(1+t24[1]≥12)⊃' AM' ' PM'  ⍝ Add AM/PM and ':' separator
∇

∇Read;f
        →(¯2≡f←⎕FIO[49]'notes.txt')/0  ⍝ Read file, stop if not found
        ⎕←⊃f                           ⍝ Output file line by line
∇

∇Write note;f;_
        note←' 'Join note              ⍝ flatten input and separate with spaces
        note←Date,' ',Time,(⎕UCS 10 9),note,⎕UCS 10   ⍝ note format
        f←'a'⎕FIO[3]'notes.txt'        ⍝ append to file
        _←(⎕UCS note)⎕FIO[7]f          ⍝ write note to end of file
        _←⎕FIO[4]f                     ⍝ close the file
∇

∇Notes;note
        ⍎∊('Read' 'Write note')[1+0≠⍴note←4↓⎕ARG]
∇

Notes
)OFF


#!/usr/bin/osascript

-- format a number as a string with leading zero if needed
to format(aNumber)
  set resultString to aNumber as text
  if length of resultString < 2
    set resultString to "0" & resultString
  end if
  return resultString
end format

-- join a list with a delimiter
to concatenation of aList given delimiter:aDelimiter
  set tid to AppleScript's text item delimiters
  set AppleScript's text item delimiters to { aDelimiter }
  set resultString to aList as text
  set AppleScript's text item delimiters to tid
  return resultString
end join

-- apply a handler to every item in a list, returning
-- a list of the results
to mapping of aList given function:aHandler
  set resultList to {}
  global h
  set h to aHandler
  repeat with anItem in aList
    set resultList to resultList & h(anItem)
  end repeat
  return resultList
end mapping

-- return an ISO-8601-formatted string representing the current date and time
-- in UTC
to iso8601()
    set { year:y,   month:m,     day:d, ¬
          hours:hr, minutes:min, seconds:sec } to ¬
          (current date) - (time to GMT)
    set ymdList to the mapping of { y, m as integer, d } given function:format
    set ymd to the concatenation of ymdList given delimiter:"-"
    set hmsList to the mapping of { hr, min, sec } given function:format
    set hms to the concatenation of hmsList given delimiter:":"
    set dateTime to the concatenation of {ymd, hms} given delimiter:"T"
    return dateTime & "Z"
end iso8601

to exists(filePath)
  try
    filePath as alias
    return true
  on error
    return false
  end try
end exists

on run argv
  set curDir to (do shell script "pwd")
  set notesFile to POSIX file (curDir & "/NOTES.TXT")

  if (count argv) is 0 then
    if exists(notesFile) then
       set text item delimiters to {linefeed}
       return paragraphs of (read notesFile) as text
    else
       log "No notes here."
       return
    end if
  else
    try
      set fd to open for access notesFile with write permission
      write (iso8601() & linefeed & tab) to fd starting at eof
      set AppleScript's text item delimiters to {" "}
      write ((argv as text) & linefeed) to fd starting at eof
      close access fd
      return true
    on error errMsg number errNum
      try
         close access fd
      end try
      return "unable to open  " & notesFile & ": " & errMsg
    end try
  end if
end run