def factorize(n):
    assert(isinstance(n, int))
    if n < 0:
        n = -n
    if n < 2:
        return
    k = 0
    while 0 == n%2:
        k += 1
        n //= 2
    if 0 < k:
        yield (2,k)
    p = 3
    while p*p <= n:
        k = 0
        while 0 == n%p:
            k += 1
            n //= p
        if 0 < k:
            yield (p,k)
        p += 2
    if 1 < n:
        yield (n,1)

def tau(n):
    assert(n != 0)
    ans = 1
    for (p,k) in factorize(n):
        ans *= 1 + k
    return ans

if __name__ == "__main__":
    print([tau(n) for n in range(1,101)])


  [ factors size ] is tau ( n --> n )

  [] []
  100 times [ i^ 1+ tau join ]
  witheach [ number$ nested join ]
  70 wrap$


lengths(sapply(1:100, function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n)))


use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;

say "\nTau function - first 100:\n",        # ID
(1..*).map({ +.&divisors })[^100]\          # the task
.batch(20)».fmt("%3d").join("\n");          # display formatting

say "\nTau numbers - first 100:\n",         # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\   # the task
.batch(10)».&comma».fmt("%5s").join("\n");  # display formatting

say "\nDivisor sums - first 100:\n",        # ID
(1..*).map({ [+] .&divisors })[^100]\       # the task
.batch(20)».fmt("%4d").join("\n");          # display formatting

say "\nDivisor products - first 100:\n",    # ID
(1..*).map({ [×] .&divisors })[^100]\       # the task
.batch(5)».&comma».fmt("%16s").join("\n");  # display formatting


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

typedef unsigned long long xint;
typedef unsigned uint;
typedef struct {
	uint x, y; // x > y always
	xint value;
} sum_t;

xint *cube;
uint n_cubes;

sum_t *pq;
uint pq_len, pq_cap;

void add_cube(void)
{
	uint x = n_cubes++;
	cube = realloc(cube, sizeof(xint) * (n_cubes + 1));
	cube[n_cubes] = (xint) n_cubes*n_cubes*n_cubes;
	if (x < 2) return; // x = 0 or 1 is useless

	if (++pq_len >= pq_cap) {
		if (!(pq_cap *= 2)) pq_cap = 2;
		pq = realloc(pq, sizeof(*pq) * pq_cap);
	}

	sum_t tmp = (sum_t) { x, 1, cube[x] + 1 };
	// upheap
	uint i, j;
	for (i = pq_len; i >= 1 && pq[j = i>>1].value > tmp.value; i = j)
		pq[i] = pq[j];

	pq[i] = tmp;
}

void next_sum(void)
{
redo:	while (!pq_len || pq[1].value >= cube[n_cubes]) add_cube();

	sum_t tmp = pq[0] = pq[1];	// pq[0] always stores last seen value
	if (++tmp.y >= tmp.x) {		// done with this x; throw it away
		tmp = pq[pq_len--];
		if (!pq_len) goto redo;	// refill empty heap
	} else
		tmp.value += cube[tmp.y] - cube[tmp.y-1];

	uint i, j;
	// downheap
	for (i = 1; (j = i<<1) <= pq_len; pq[i] = pq[j], i = j) {
		if (j < pq_len && pq[j+1].value < pq[j].value) ++j;
		if (pq[j].value >= tmp.value) break;
	}
	pq[i] = tmp;
}

uint next_taxi(sum_t *hist)
{
	do next_sum(); while (pq[0].value != pq[1].value);

	uint len = 1;
	hist[0] = pq[0];
	do {
		hist[len++] = pq[1];
		next_sum();
	} while (pq[0].value == pq[1].value);

	return len;
}

int main(void)
{
	uint i, l;
	sum_t x[10];
	for (i = 1; i <= 2006; i++) {
		l = next_taxi(x);
		if (25 < i && i < 2000) continue;
		printf("%4u:%10llu", i, x[0].value);
		while (l--) printf(" = %4u^3 + %4u^3", x[l].x, x[l].y);
		putchar('\n');
	}
	return 0;
}


>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute('''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.Cursor object at 0x013265C0>
>>>


#lang at-exp racket

(require db)
(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create))

(define (add! name street city state zip)
  (query-exec postal
    @~a{INSERT INTO addresses (name, street, city, state, zip)
        VALUES (?, ?, ?, ?, ?)}
    name street city state zip))

(unless (table-exists? postal "addresses")
  (query-exec postal
    @~a{CREATE TABLE addresses(
          id INTEGER PRIMARY KEY,
          name   TEXT NOT NULL,
          street TEXT NOT NULL,
          city   TEXT NOT NULL,
          state  TEXT NOT NULL,
          zip    TEXT NOT NULL)}))

(add! "FSF Inc."
      "51 Franklin St"
      "Boston"
      "MA"
      "02110-1301")
(add! "The White House"
      "1600 Pennsylvania Avenue NW"
      "Washington"
      "DC"
      "20500")
(add! "National Security Council"
      "1700 Pennsylvania Avenue NW"
      "Washington"
      "DC"
      "20500")

(printf "Addresses:\n")
(for ([r (query-rows postal "SELECT * FROM addresses")])
  (printf "  ~a.\n" (string-join (cdr (vector->list r)) ", ")))
(newline)

(printf "By State+ZIP:\n")
(for ([z (query-rows postal "SELECT * FROM addresses"
                     #:group #("state" "zip"))])
  (printf "  ~a, ~a:\n" (vector-ref z 0) (vector-ref z 1))
  (for ([r (vector-ref z 2)])
    (printf "    ~a.\n" (string-join (cdr (vector->list r)) ", "))))

(disconnect postal)


use DBIish;

my $dbh = DBIish.connect('SQLite', :database<addresses.sqlite3>);

my $sth = $dbh.do(q:to/STATEMENT/);
    DROP TABLE IF EXISTS Address;
    CREATE TABLE Address (
        addrID      INTEGER PRIMARY KEY AUTOINCREMENT,
        addrStreet  TEXT NOT NULL,
        addrCity    TEXT NOT NULL,
        addrState   TEXT NOT NULL,
        addrZIP     TEXT NOT NULL
    )
    STATEMENT


╔════════╤════════════════════════════════════════════════════════════════════════╤══════╗
╟────────┘  Format of an entry in the USA address/city/state/zip code structure:  └──────╢
║                                                                                ║
║ The structure name can be any variable name,  but here it'll be shortened to make these║
║   comments and program easier to read;  its name will be:   @USA  or  @usa   (or both).║
║                                                                                ║
║ Each of the variable names beginning with an underscore (_) aren't to be used elsewhere║
║   in the program.  Other possibilities are to have a trailing underscore (or both)  or ║
║   some other special eye─catching character such as:    !   @   #   $   ?              ║
║                                                                                ║
║ Any field not specified will have a value of a  null   (which has a length of zero).   ║
║                                                                                ║
║ Any field may contain any number of characters,  this can be limited by the            ║
║   restrictions imposed by the standards  or  the USA legal definitions.                ║
║ Any number of fields could be added  (with testing for invalid fields).                ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.0             the number of entries in the   @USA  stemmed array.                ║
║                                                                                ║
║       nnn           is some positive integer of any length (no leading zeros).         ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._name     is the name of person, business,  or a lot description.            ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._addr1    is the 1st street address                                          ║
║  @USA.nnn._addr2    is the 2nd street address                                          ║
║  @USA.nnn._addr3    is the 3rd street address                                          ║
║  @USA.nnn._addrNN      ···  (any number,  but in sequential order).                    ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._state    is the USA postal code for the state, territory, etc.              ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._city     is the official city name,  it may include any character.          ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._zip      is the USA postal zip code  (five or ten digit format).            ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║  @USA.nnn._upHist   is the update history:  userID who did the update; date, timestamp.║
╚════════════════════════════════════════════════════════════════════════════════════════╝


# Project : Table creation/Postal addresses

load "stdlib.ring"
oSQLite = sqlite_init()

sqlite_open(oSQLite,"mytest.db")

sql = "CREATE TABLE ADDRESS ("  +
         "addrID INT NOT NULL," +
         "street CHAR(50) NOT NULL," +
         "city CHAR(25) NOT NULL," +
         "state CHAR(2), NOT NULL" +
         "zip CHAR(20) NOT NULL);"

sqlite_execute(oSQLite,sql)


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

my $kelvin = +prompt "Enter a temperature in Kelvin: ";
die "No such temperature!" if $kelvin < 0;

for %scale.sort {
    printf "%12s: %7.2f\n", .key, $kelvin * .value<factor> + .value<offset>;
}


/*REXX program  converts  temperatures  for a number (8)  of  temperature scales.       */
numeric digits 120                               /*be able to support some huge numbers.*/
parse arg tList                                  /*get the specified temperature list.  */

  do  until  tList=''                            /*process the list of temperatures.    */
  parse  var tList  x  ','  tList                /*temps are separated by commas.       */
  x= translate(x, '((', "[{")                    /*support other grouping symbols.      */
  x= space(x);      parse var x z '('            /*handle any comments  (if any).       */
  parse upper  var  z  z   ' TO '  ! .           /*separate the  TO  option from number.*/
  if !==''  then != 'ALL';   all= !=='ALL'       /*allow specification of "TO" opt*/
  if z==''     then call serr "no arguments were specified."                 /*oops-ay. */
  _= verify(z, '+-.0123456789')                  /*list of valid numeral/number thingys.*/
  n= z
  if _\==0  then do
                 if _==1  then call serr 'illegal temperature:'   z
                 n= left(z,  _ - 1)              /*pick off the number  (hopefully).    */
                 u= strip( substr(z, _) )        /*pick off the  temperature  unit.     */
                 end
            else u= 'k'                          /*assume kelvin as per task requirement*/

  if \datatype(n, 'N')  then call serr 'illegal number:'    n
  if \all  then do                               /*is there is a     TO  ααα     scale? */
                call name !                      /*process the   TO   abbreviation.     */
                != s n                           /*assign the full name to     !        */
                end                              /*!: now contains temperature full name*/
  call name u                                    /*allow alternate scale (miss)spellings*/

      select                                     /*convert ──► °Fahrenheit temperatures.*/
      when sn=='CELSIUS'          then F= n       *  9/5   +  32
      when sn=='DELISLE'          then F= 212 -(n *  6/5)
      when sn=='FAHRENHEIT'       then F= n
      when sn=='KELVIN'           then F= n       *  9/5   - 459.67
      when sn=='NEWTON'           then F= n       * 60/11  +  32
      when sn=='RANKINE'          then F= n                - 459.67    /*a single  R  is taken as Rankine.*/
      when sn=='REAUMUR'          then F= n       *  9/4   +  32
      when sn=='ROMER'            then F= (n-7.5) * 27/4   +  32
      otherwise              call serr  'illegal temperature scale: '    u
      end   /*select*/

  K = (F + 459.67)  *  5/9                       /*compute temperature to  kelvins.     */
  say right(' ' x, 79, "─")                      /*show the original value, scale, sep. */
  if all | !=='CELSIUS'           then say $(   ( F   -  32     )   *  5/9           )    'Celsius'
  if all | !=='DELISLE'           then say $(   ( 212 -  F      )   *  5/6           )    'Delisle'
  if all | !=='FAHRENHEIT'        then say $(     F                                  )    'Fahrenheit'
  if all | !=='KELVIN'            then say $(        K                               )    'kelvin's(K)
  if all | !=='NEWTON'            then say $(   ( F   -  32     )   *  11/60         )    'Newton'
  if all | !=='RANKINE'           then say $(     F   + 459.67                       )    'Rankine'
  if all | !=='REAUMUR'           then say $(   ( F   -  32     )   *  4/9           )    'Reaumur'
  if all | !=='ROMER'             then say $(   ( F   -  32     )   *  4/27    + 7.5 )    'Romer'
  end   /*until*/

exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s:    if arg(1)==1  then return arg(3);     return word( arg(2) 's',  1)
serr: say;   say '***error!***';    say;    say arg(1);    say;   exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
$:    procedure;           showDig= 8            /*only show  eight  significant digits.*/
      _= format( arg(1), , showDig) / 1          /*format number 8 digs past dec, point.*/
      p= pos(., _);        L= length(_)          /*find position of the decimal point.  */
                                                 /* [↓]  align integers with FP numbers.*/
      if p==0  then _= _ || left('', 5+showDig+1)    /*the number has no decimal point. */
               else _= _ || left('', 5+showDig-L+p)  /* "     "    "   a    "      "    */
      return right(_, 50)                        /*return the re-formatted number (arg).*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
name: parse arg y                                       /*abbreviations  ──►  shortname.*/
      yU= translate(y, 'eE', "éÉ");       upper yU      /*uppercase the temperature unit*/
      if left(yU, 7)=='DEGREES'  then yU= substr(yU, 8) /*redundant "degrees" after  #? */
      if left(yU, 6)=='DEGREE'   then yU= substr(yU, 7) /*   "      "degree"    "    "  */
      yU= strip(yU)                                     /*elide blanks at front and back*/
      _= length(yU)                                     /*obtain the    yU    length.   */
      if right(yU,1)=='S' & _>1  then yU= left(yU, _-1) /*elide trailing plural, if any.*/

             select                                     /*abbreviations  ──►  shortname.*/
             when abbrev('CENTIGRADE' , yU)    |,
                  abbrev('CENTRIGRADE', yU)    |,                     /* 50% misspelled.*/
                  abbrev('CETIGRADE'  , yU)    |,                     /* 50% misspelled.*/
                  abbrev('CENTINGRADE', yU)    |,
                  abbrev('CENTESIMAL' , yU)    |,
                  abbrev('CELCIU'     , yU)    |,                     /* 82% misspelled.*/
                  abbrev('CELCIOU'    , yU)    |,                     /*  4% misspelled.*/
                  abbrev('CELCUI'     , yU)    |,                     /*  4% misspelled.*/
                  abbrev('CELSUI'     , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELCEU'     , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELCU'      , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELISU'     , yU)    |,                     /*  1% misspelled.*/
                  abbrev('CELSU'      , yU)    |,                     /*  1% misspelled.*/
                  abbrev('CELSIU'     , yU)       then sn= 'CELSIUS'
             when abbrev('DELISLE'    , yU,2)     then sn= 'DELISLE'
             when abbrev('FARENHEIT'  , yU)    |,                     /* 39% misspelled.*/
                  abbrev('FARENHEIGHT', yU)    |,                     /* 15% misspelled.*/
                  abbrev('FARENHITE'  , yU)    |,                     /*  6% misspelled.*/
                  abbrev('FARENHIET'  , yU)    |,                     /*  3% misspelled.*/
                  abbrev('FARHENHEIT' , yU)    |,                     /*  3% misspelled.*/
                  abbrev('FARINHEIGHT', yU)    |,                     /*  2% misspelled.*/
                  abbrev('FARENHIGHT' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FAHRENHIET' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERENHEIGHT', yU)    |,                     /*  2% misspelled.*/
                  abbrev('FEHRENHEIT' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERENHEIT'  , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERINHEIGHT', yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARIENHEIT' , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARINHEIT'  , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARANHITE'  , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FAHRENHEIT' , yU)       then sn= 'FAHRENHEIT'
             when abbrev('KALVIN'     , yU)    |,                     /* 27% misspelled.*/
                  abbrev('KERLIN'     , yU)    |,                     /* 18% misspelled.*/
                  abbrev('KEVEN'      , yU)    |,                     /*  9% misspelled.*/
                  abbrev('KELVIN'     , yU)       then sn= 'KELVIN'
             when abbrev('NEUTON'     , yU)    |,                     /*100% misspelled.*/
                  abbrev('NEWTON'     , yU)       then sn= 'NEWTON'
             when abbrev('RANKINE'    , yU, 1)    then sn= 'RANKINE'
             when abbrev('REAUMUR'    , yU, 2)    then sn= 'REAUMUR'
             when abbrev('ROEMER'     , yU, 2) |,
                  abbrev('ROMER'      , yU, 2)    then sn= 'ROMER'
             otherwise                call serr  'illegal temperature scale:'   y
             end   /*select*/
      return


notes: "notes.txt"
if? empty? arg [
    if exists? notes -> print read notes
]
else [
    output: (to :string now) ++ "\n" ++
            "\t" ++ (join.with:" " to [:string] arg) ++ "\n"
    write.append notes output
]


Notes := "Notes.txt"

If 0 = 0 ; no arguments
{
    If FileExist(Notes) {
        FileRead, Content, %Notes%
        MsgBox, %Content%
    } Else
        MsgBox, %Notes% does not exist
    Goto, EOF
}

; date and time, colon, newline (CRLF), tab
Date := A_DD "/" A_MM "/" A_YYYY
Time := A_Hour ":" A_Min ":" A_Sec "." A_MSec
FileAppend, %Date% %Time%:`r`n%A_Tab%, %Notes%

; command line parameters, trailing newline (CRLF)
Loop, %0%
    FileAppend, % %A_Index% " ", %Notes%
FileAppend, `r`n, %Notes%

EOF:


/*REXX program counts the number of divisors (tau,  or sigma_0)  up to and including  N.*/
parse arg LO HI cols .                           /*obtain optional argument from the CL.*/
if   LO=='' |   LO==","  then  LO=   1           /*Not specified?  Then use the default.*/
if   HI=='' |   HI==","  then  HI=  LO + 100 - 1 /*Not specified?  Then use the default.*/
if cols=='' | cols==","  then cols= 20           /* "      "         "   "   "     "    */
w= 2 + (HI>45359)                                /*W:  used to align the output columns.*/
say 'The number of divisors  (tau)  for integers up to '    n    " (inclusive):";      say
say '─index─'   center(" tau (number of divisors) ",  cols * (w+1)  +  1,  '─')
$=;                                   c= 0       /*$:  the output list,  shown ROW/line.*/
                do j=LO  to HI;       c= c + 1   /*list # proper divisors (tau) 1 ──► N */
                $= $  right( tau(j), w)          /*add a tau number to the output list. */
                if c//cols \== 0  then iterate   /*Not a multiple of ROW? Don't display.*/
                idx= j - cols + 1                /*calculate index value (for this row).*/
                say center(idx, 7)    $;  $=     /*display partial list to the terminal.*/
                end   /*j*/

if $\==''  then say center(idx+cols, 7)    $     /*there any residuals left to display ?*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tau: procedure; parse arg x 1 y                  /*X  and  $  are both set from the arg.*/
     if x<6  then return 2 + (x==4) - (x==1)     /*some low #s should be handled special*/
     odd= x // 2                                 /*check if  X  is odd (remainder of 1).*/
     if odd  then       #= 2                     /*Odd?    Assume divisor count of  2.  */
             else do;   #= 4;   y= x % 2;   end  /*Even?      "      "      "    "  4.  */
                                                 /* [↑]  start with known number of divs*/
        do j=3  for x%2-3  by 1+odd  while j<y   /*for odd number,  skip even numbers.  */
        if x//j==0  then do                      /*if no remainder, then found a divisor*/
                         #= # + 2;   y= x % j    /*bump # of divisors;  calculate limit.*/
                         if j>=y  then do;   #= # - 1;   leave;   end   /*reached limit?*/
                         end                     /*                     ___             */
                    else if j*j>x  then leave    /*only divide up to   √ x              */
        end   /*j*/;               return #      /* [↑]  this form of DO loop is faster.*/


see "The tau functions for the first 100 positive integers are:" + nl

n = 0
num = 0
limit = 100
while num < limit
      n = n + 1
      tau = 0
      for m = 1 to n
          if n%m = 0
             tau = tau + 1
          ok
      next
      num = num + 1
      if num%10 = 1
         see nl
      ok
      tau = string(tau)
      if len(tau) = 1
         tau = " " + tau
      ok
      see "" + tau + " "
end


require 'prime'

def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}

(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}


#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>

template <typename T>
size_t indexOf(const std::vector<T> &v, const T &k) {
    auto it = std::find(v.cbegin(), v.cend(), k);

    if (it != v.cend()) {
        return it - v.cbegin();
    }
    return -1;
}

int main() {
    std::vector<size_t> cubes;

    auto dump = [&cubes](const std::string &title, const std::map<int, size_t> &items) {
        std::cout << title;
        for (auto &item : items) {
            std::cout << "\n" << std::setw(4) << item.first << " " << std::setw(10) << item.second;
            for (auto x : cubes) {
                auto y = item.second - x;
                if (y < x) {
                    break;
                }
                if (std::count(cubes.begin(), cubes.end(), y)) {
                    std::cout << " = " << std::setw(4) << indexOf(cubes, y) << "^3 + " << std::setw(3) << indexOf(cubes, x) << "^3";
                }
            }
        }
    };

    std::vector<size_t> sums;

    // create sorted list of cube sums
    for (size_t i = 0; i < 1190; i++) {
        auto cube = i * i * i;
        cubes.push_back(cube);
        for (auto j : cubes) {
            sums.push_back(cube + j);
        }
    }
    std::sort(sums.begin(), sums.end());

    // now seek consecutive sums that match
    auto nm1 = sums[0];
    auto n = sums[1];
    int idx = 0;
    std::map<int, size_t> task;
    std::map<int, size_t> trips;

    auto it = sums.cbegin();
    auto end = sums.cend();
    it++;
    it++;

    while (it != end) {
        auto np1 = *it;

        if (nm1 == np1) {
            trips.emplace(idx, n);
        }
        if (nm1 != n && n == np1) {
            if (++idx <= 25 || idx >= 2000 == idx <= 2006) {
                task.emplace(idx, n);
            }
        }
        nm1 = n;
        n = np1;

        it++;
    }

    dump("First 25 Taxicab Numbers, the 2000th, plus the next half-dozen:", task);

    std::stringstream ss;
    ss << "\n\nFound " << trips.size() << " triple Taxicabs under 2007:";
    dump(ss.str(), trips);

    return 0;
}


require 'pstore'
require 'set'

Address = Struct.new :id, :street, :city, :state, :zip

db = PStore.new("addresses.pstore")
db.transaction do
  db[:next] ||= 0       # Next available Address#id
  db[:ids] ||= Set[]    # Set of all ids in db
end


sqliteconnect #mem, ":memory:"  ' make handle #mem
mem$ = "
CREATE TABLE address (
  addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
  addrStreet TEXT NOT NULL,
  addrCity   TEXT NOT NULL,
  addrState  TEXT NOT NULL,
  addrZIP    TEXT NOT NULL
)"
#mem execute(mem$)


PROC SQL;
CREATE TABLE ADDRESS
(
ADDRID CHAR(8)
,STREET CHAR(50)
,CITY CHAR(25)
,STATE CHAR(2)
,ZIP  CHAR(20)
)
;QUIT;


(use sql-de-lite)

(define *db* (open-database "addresses"))

(exec ; create and run the SQL statement
  (sql *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-database *db*) ; finally, close database


k = 21.0 c = 0 r = 0 f = 0
convertTemp(k)
see "Kelvin : " + k + nl +
"Celcius : " + c + nl +
"Rankine : " + r + nl +
"Fahrenheit : " + f + nl

func convertTemp k
     c = k - 273.15
     r = k * 1.8
     f = r - 459.67


module TempConvert

  FROM_TEMP_SCALE_TO_K =
  {'kelvin'     => lambda{|t| t},
   'celsius'    => lambda{|t| t + 273.15},
   'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0},
   'rankine'    => lambda{|t| t * 5/9.0},
   'delisle'    => lambda{|t| 373.15 - t * 2/3.0},
   'newton'     => lambda{|t| t * 100/33.0 + 273.15},
   'reaumur'    => lambda{|t| t * 5/4.0 + 273.15},
   'roemer'     => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}}

  TO_TEMP_SCALE_FROM_K =
  {'kelvin'     => lambda{|t| t},
   'celsius'    => lambda{|t| t - 273.15},
   'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67},
   'rankine'    => lambda{|t| t * 9/5.0},
   'delisle'    => lambda{|t| (373.15 - t) * 3/2.0},
   'newton'     => lambda{|t| (t - 273.15) * 33/100.0},
   'reaumur'    => lambda{|t| (t - 273.15) * 4/5.0},
   'roemer'     => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}}

  SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|')

  def self.method_missing(meth, *args, &block)
    if valid_temperature_conversion?(meth) then
      convert_temperature(meth, *args)
    else
      super
    end
  end

  def self.respond_to_missing?(meth, include_private = false)
    valid_temperature_conversion?(meth) || super
  end

  def self.valid_temperature_conversion?(meth)
    !!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/)
  end

  def self.convert_temperature(meth, temp)
    from_scale, to_scale = meth.to_s.split("_to_")
    return temp.to_f if from_scale == to_scale # no kelvin roundtrip
    TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2)
  end

end


# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ]
# examples:
#   GAWK -f TAKE_NOTES.AWK Hello world
#   GAWK -f TAKE_NOTES.AWK A "B C" D
#   GAWK -f TAKE_NOTES.AWK
BEGIN {
    log_name = "NOTES.TXT"
    (ARGC == 1) ? show_log() : update_log()
    exit(0)
}
function show_log(  rec) {
    while (getline rec <log_name > 0) {
      printf("%s\n",rec)
    }
}
function update_log(  i,q) {
    print(strftime("%Y-%m-%d %H:%M:%S")) >>log_name
    printf("\t") >>log_name
    for (i=1; i<=ARGC-1; i++) {
      q = (ARGV[i] ~ / /) ? "\"" : ""
      printf("%s%s%s ",q,ARGV[i],q) >>log_name
    }
    printf("\n") >>log_name
}


// returns the highest power of i that is a factor of n,
// and n divided by that power of i
fn factor_exponent(n: i32, i: i32) -> (i32, i32) {
	if n % i == 0 {
		let (a, b) = factor_exponent(n / i, i);
		(a + 1, b)
	} else {
		(0, n)
	}
}

fn tau(n: i32) -> i32 {
	for i in 2..(n+1) {
		if n % i == 0 {
			let (count, next) = factor_exponent(n, i);
			return (count + 1) * tau(next);
		}
	}
	return 1;
}

fn main() {
	for i in 1..101 {
		print!("{} ", tau(i));
	}
}


import Foundation

// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
    var n = number
    var total = 1
    // Deal with powers of 2 first
    while (n & 1) == 0 {
        total += 1
        n >>= 1
    }
    // Odd prime factors up to the square root
    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 then it's prime
    if n > 1 {
        total *= 2
    }
    return total
}

let limit = 100
print("Count of divisors for the first \(limit) positive integers:")
for n in 1...limit {
    print(String(format: "%3d", divisorCount(number: n)), terminator: "")
    if n % 20 == 0 {
        print()
    }
}


    LET N = 0
 10 LET N = N + 1
    IF N < 3 THEN GOTO 100
    LET T = 2
    LET A = 1
 20 LET A = A + 1
    IF (N/A)*A = N THEN LET T = T + 1
    IF A<(N+1)/2 THEN GOTO 20
 30 PRINT "Tau(",N,") = ",T
    IF N<100 THEN GOTO 10
    END
100 LET T = N
    GOTO 30


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TaxicabNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            IDictionary<long, IList<Tuple<int, int>>> taxicabNumbers = GetTaxicabNumbers(2006);
            PrintTaxicabNumbers(taxicabNumbers);
            Console.ReadKey();
        }

        private static IDictionary<long, IList<Tuple<int, int>>> GetTaxicabNumbers(int length)
        {
            SortedList<long, IList<Tuple<int, int>>> sumsOfTwoCubes = new SortedList<long, IList<Tuple<int, int>>>();

            for (int i = 1; i < int.MaxValue; i++)
            {
                for (int j = 1; j < int.MaxValue; j++)
                {
                    long sum = (long)(Math.Pow((double)i, 3) + Math.Pow((double)j, 3));

                    if (!sumsOfTwoCubes.ContainsKey(sum))
                    {
                        sumsOfTwoCubes.Add(sum, new List<Tuple<int, int>>());
                    }

                    sumsOfTwoCubes[sum].Add(new Tuple<int, int>(i, j));

                    if (j >= i)
                    {
                        break;
                    }
                }

                // Found that you need to keep going for a while after the length, because higher i values fill in gaps
                if (sumsOfTwoCubes.Count(t => t.Value.Count >= 2) >= length * 1.1)
                {
                    break;
                }
            }

            IDictionary<long, IList<Tuple<int, int>>> values = (from t in sumsOfTwoCubes where t.Value.Count >= 2 select t)
                .Take(2006)
                .ToDictionary(u => u.Key, u => u.Value);

            return values;
        }

        private static void PrintTaxicabNumbers(IDictionary<long, IList<Tuple<int, int>>> values)
        {
            int i = 1;

            foreach (long taxicabNumber in values.Keys)
            {
                StringBuilder output = new StringBuilder().AppendFormat("{0,10}\t{1,4}", i, taxicabNumber);

                foreach (Tuple<int, int> numbers in values[taxicabNumber])
                {
                    output.AppendFormat("\t= {0}^3 + {1}^3", numbers.Item1, numbers.Item2);
                }

                if (i <= 25 || (i >= 2000 && i <= 2006))
                {
                    Console.WriteLine(output.ToString());
                }

                i++;
            }
        }
    }
}


require('DBI');

var db = %s'DBI'.connect('DBI:mysql:database:server','login','password');

var 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

var exec = db.prepare(statment);
exec.execute;


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


CREATE TABLE address_USA (
    address_ID INTEGER PRIMARY KEY,
    address_Street TEXT,
    address_City TEXT,
    address_State TEXT,
    address_Zip INTEGER
);


clear
gen str8 addrid=""
gen str50 street=""
gen str25 city=""
gen str2 state=""
gen str20 zip=""
save address


package require sqlite3

sqlite3 db address.db
db eval {
    CREATE TABLE address (
	addrID		INTEGER PRIMARY KEY AUTOINCREMENT,
	addrStreet	TEXT NOT NULL,
	addrCity	TEXT NOT NULL,
	addrState	TEXT NOT NULL,
	addrZIP		TEXT NOT NULL
    )
}


[loop]
input "Kelvin Degrees";kelvin
if kelvin <= 0 then end         ' zero or less ends the program
celcius     = kelvin - 273.15
fahrenheit  = kelvin * 1.8 - 459.67
rankine     = kelvin * 1.8
print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine"
goto [loop]


object TemperatureConversion extends App {

  def kelvinToCelsius(k: Double) = k + 273.15

  def kelvinToFahrenheit(k: Double) = k * 1.8 - 459.67

  def kelvinToRankine(k: Double) = k * 1.8

  if (args.length == 1) {
    try {
      val kelvin = args(0).toDouble
      if (kelvin >= 0) {
        println(f"K  $kelvin%2.2f")
        println(f"C  ${kelvinToCelsius(kelvin)}%2.2f")
        println(f"F  ${kelvinToFahrenheit(kelvin)}%2.2f")
        println(f"R  ${kelvinToRankine(kelvin)}%2.2f")
      } else println("%2.2f K is below absolute zero", kelvin)

    } catch {
      case e: NumberFormatException => System.out.println(e)
      case e: Throwable => {
        println("Some other exception type:")
        e.printStackTrace()
      }
    }
  } else println("Temperature not given.")
}


IF LEN(COMMAND$) THEN
    OPEN "notes.txt" FOR APPEND AS 1
    PRINT #1, DATE$, TIME$
    PRINT #1, CHR$(9); COMMAND$
    CLOSE
ELSE
    d$ = DIR$("notes.txt")
    IF LEN(d$) THEN
        OPEN d$ FOR INPUT AS 1
        WHILE NOT EOF(1)
            LINE INPUT #1, i$
            PRINT i$
        WEND
        CLOSE
    END IF
END IF


@echo off
if %1@==@ (
    if exist notes.txt more notes.txt
    goto :eof
)
echo %date% %time%:>>notes.txt
echo 	%*>>notes.txt


      REM!Exefile C:\NOTES.EXE, encrypt, console
      REM!Embed
      LF = 10

      SYS "GetStdHandle", -10 TO @hfile%(1)
      SYS "GetStdHandle", -11 TO @hfile%(2)
      SYS "SetConsoleMode", @hfile%(1), 0
      *INPUT 13
      *OUTPUT 14
      ON ERROR PRINT REPORT$ : QUIT ERR

      notes% = OPENUP(@dir$ + "NOTES.TXT")
      IF notes% = 0 notes% = OPENOUT(@dir$ + "NOTES.TXT")
      IF notes% = 0 PRINT "Cannot open or create NOTES.TXT" : QUIT 1

      IF @cmd$ = "" THEN
        WHILE NOT EOF#notes%
          INPUT #notes%, text$
          IF ASC(text$) = LF text$ = MID$(text$,2)
          PRINT text$
        ENDWHILE
      ELSE
        PTR#notes% = EXT#notes%
        PRINT #notes%,TIME$ : BPUT#notes%,LF
        PRINT #notes%,CHR$(9) + @cmd$ : BPUT#notes%,LF
      ENDIF

      CLOSE #notes%
      QUIT


module main;
  integer N, T, A;

  initial begin
    $display("The tau functions for the first 100 positive integers are:\n");
    for (N = 1; N <= 100; N=N+1) begin
        if (N < 3) T = N;
        else begin
            T = 2;
            for (A = 2; A <= (N+1)/2; A=A+1) begin
                if (N % A == 0) T = T + 1;
            end
        end

        $write(T);
        if (N % 10 == 0) $display("");
    end
      $finish ;
  end
endmodule


import "/math" for Int
import "/fmt" for Fmt

System.print("The tau functions for the first 100 positive integers are:")
for (i in 1..100) {
    Fmt.write("$2d  ", Int.divisors(i).count)
    if (i % 20 == 0) System.print()
}


int N, D, C;
[Format(3, 0);
for N:= 1 to 100 do
    [C:= 0;
    for D:= 1 to N do
        if rem(N/D) = 0 then C:= C+1;
    RlOut(0, float(C));
    if rem(N/20) = 0 then CrLf(0);
    ];
]


(ns test-project-intellij.core
  (:gen-class))

(defn cube [x]
  "Cube a number through triple multiplication"
  (* x x x))

(defn sum3 [[i j]]
   " [i j] -> i^3 + j^3"
  (+ (cube i) (cube j)))

(defn next-pair [[i j]]
  " Generate next [i j] pair of sequence  (producing lower triangle pairs) "
  (if (< j i)
    [i (inc j)]
    [(inc i) 1]))

;; Pair sequence generator [1 1] [2 1] [2 2] [3 1] [3 2] [3 3] ...
(def pairs-seq	(iterate next-pair [1 1]))

(defn dict-inc [m pair]
  " Add pair to pair map m, with the key of the map based upon the cubic sum (sum3) and the value appends the pair "
  (update-in m [(sum3 pair)] (fnil #(conj % pair) [])))

(defn enough? [m n-to-generate]
  " Checks if we have enough taxi numbers (i.e. if number in map >= count-needed "
  (->> m                                ; hash-map of sum of cube of numbers [key] and their pairs as value
       (filter #(if (> (count (second %)) 1) true false))   ; filter out ones which don't have more than 1 entry
       (count)                                              ; count the item remaining
       (<= n-to-generate)))                                ; true iff count-needed is less or equal to the nubmer filtered

(defn find-taxi-numbers [n-to-generate]
  " Generates 1st n-to-generate taxi numbers"
  (loop [m {}               ; Hash-map containing cube of pairs (key) and set of pairs that produce sum (value)
         p pairs-seq        ; select pairs from our pair sequence generator (i.e. [1 1] [2 1] [2 2] ...)
         num-tried 0        ; Since its expensve to count how many taxi numbers we have found
         check-after 1]     ; we only check if we have enough numbers every time (num-tried equals check-after)
                            ; num-tried increments by 1 each time we try the next pair and
                            ; check-after doubles if we don't have enough taxi numbers
    (if (and (= num-tried check-after) (enough? m n-to-generate)) ; check if we found enough taxi numbers
      (sort-by first (into [] (filter #(> (count (second %)) 1) m)))  ; sort the taxi numbers and this is the result
      (if (= num-tried check-after)                                   ; Check if we need to increase our count between checking
        (recur (dict-inc m (first p)) (rest p) (inc num-tried) (* 2 check-after))   ; increased count between checking
        (recur (dict-inc m (first p)) (rest p) (inc num-tried) check-after)))))     ; didn't increase the count

; Generate 1st 2006 taxi numbers
(def result (find-taxi-numbers 2006))

;; Show First 25
(defn show-result [n sample]
  " Prints one line of result "
  (print (format "%4d:%10d" n  (first sample)))
  (doseq [q  (second sample)
          :let [[i j] q]]
      (print (format " = %4d^3 + %4d^3" i j)))
  (println))

; 1st 25 taxi numbers
(doseq [n (range 1 26)
        :let [sample (nth result (dec n))]]
  (show-result n sample))

; taxi numbers from 2000th to 2006th
(doseq [n (range 2000 2007)
        :let [sample (nth result (dec n))]]
  (show-result n sample))

}


CREATE TABLE #Address (
    addrID       INT        NOT NULL   IDENTITY(1,1) PRIMARY KEY,
    addrStreet   VARCHAR(50) NOT NULL ,
    addrCity     VARCHAR(25) NOT NULL ,
    addrState    CHAR(2)     NOT NULL ,
    addrZIP      CHAR(10)    NOT NULL
)
DROP TABLE #Address


Option Explicit

Dim objFSO, DBSource

Set objFSO = CreateObject("Scripting.FileSystemObject")

DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"

With CreateObject("ADODB.Connection")
	.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
	.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
			"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
	.Close
End With


CLOSE DATABASES ALL
CREATE DATABASE usdata.dbc
SET NULL OFF
CREATE TABLE address.dbf ;
(id I AUTOINC NEXTVALUE 1 STEP 1 PRIMARY KEY COLLATE "Machine", ;
 street V(50), city V(25), state C(2), zipcode C(10))
CLOSE DATABASES ALL
*!* To use
CLOSE DATABASES ALL
OPEN DATABASE usdata.dbc
USE address.dbf SHARED


import "/dynamic" for Enum, Tuple
import "/fmt" for Fmt
import "/sort" for Cmp, Sort

var FieldType = Enum.create("FieldType", ["text", "num", "int", "bool"])

var Field = Tuple.create("Field", ["name", "fieldType", "maxLen"])

class Table {
    construct new(name, fields, keyIndex) {
        _name = name
        _fields = fields
        _keyIndex = keyIndex // the zero based index of the field to sort on
        _records = []
        _fmt = ""
        for (f in _fields) {
            var c = f.name.count
            var l = f.maxLen.max(c)
            if (f.fieldType == FieldType.text ||f.fieldType == FieldType.bool) {
                l = -l
            }
            _fmt = _fmt + "$%(l)s  "
        }
        _fmt = _fmt.trimEnd()
    }

    name { _name }

    showFields() {
        System.print("Fields for %(_name) table:\n")
        Fmt.print("$-20s $4s  $s", "name", "type", "maxlen")
        System.print("-" * 33)
        for (f in _fields) {
           Fmt.print("$-20s $-4s  $d", f.name, FieldType.members[f.fieldType], f.maxLen)
        }
    }

    cmp_ { Fn.new { |r1, r2|
        return (Num.fromString(r1[_keyIndex]) - Num.fromString(r2[_keyIndex])).sign
    }}

    addRecord(record) {
        var items = record.split(", ")
        _records.add(items)
        Sort.insertion(_records, cmp_) // move new record into sorted order
    }

    showRecords() {
        System.print("Records for %(_name) table:\n")
        var h = Fmt.slwrite(_fmt, _fields.map { |f| f.name }.toList)
        System.print(h)
        System.print("-" * h.count)
        for (r in _records) {
            Fmt.lprint(_fmt, r)
        }
    }

    removeRecord(key) {
        for (i in 0..._records.count) {
            if (_records[i][_keyIndex] == key.toString) {
               _records.removeAt(i)
               return
            }
        }
    }

    findRecord(key) {
       for (i in 0..._records.count) {
            if (_records[i][_keyIndex] == key.toString) {
               return _records[i].join(", ")
            }
        }
        return null
    }
}

var fields = []
fields.add(Field.new("id", FieldType.int, 2))
fields.add(Field.new("name", FieldType.text, 25))
fields.add(Field.new("street", FieldType.text, 50))
fields.add(Field.new("city", FieldType.text, 15))
fields.add(Field.new("state", FieldType.text, 2))
fields.add(Field.new("zipCode", FieldType.text, 10))

// create table
var table = Table.new("Addresses", fields, 0)

// add records in unsorted order
table.addRecord("2, FSF Inc., 51 Franklin Street, Boston, MA, 02110-1301")
table.addRecord("1, The White House, The Oval Office 1600 Pennsylvania Avenue NW, Washington, DC, 20500")
table.addRecord("3, National Security Council, 1700 Pennsylvania Avenue NW, Washington, DC, 20500")

// show the table's fields
table.showFields()
System.print()
// show the table's records in sorted order
table.showRecords()

// find a record by key
System.print("\nThe record with an id of 2 is:")
System.print(table.findRecord(2))

// delete a record by key
table.removeRecord(1)
System.print("\nThe record with an id of 1 will be deleted, leaving:\n")
table.showRecords()


fn main() -> std::io::Result<()> {
    print!("Enter temperature in Kelvin to convert: ");
    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    match input.trim().parse::<f32>() {
        Ok(kelvin) => {
            if kelvin < 0.0 {
                println!("Negative Kelvin values are not acceptable.");
            } else {
                println!("{} K", kelvin);
                println!("{} °C", kelvin - 273.15);
                println!("{} °F", kelvin * 1.8 - 459.67);
                println!("{} °R", kelvin * 1.8);
            }
        }

        _ => println!("Could not parse the input to a number."),
    }

    Ok(())
}


(import (scheme base)
        (scheme read)
        (scheme write))

(define (kelvin->celsius k)
  (- k 273.15))

(define (kelvin->fahrenheit k)
  (- (* k 1.8) 459.67))

(define (kelvin->rankine k)
  (* k 1.8))

;; Run the program
(let ((k (begin (display "Kelvin    : ") (flush-output-port) (read))))
  (when (number? k)
    (display "Celsius   : ") (display (kelvin->celsius k)) (newline)
    (display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline)
    (display "Rankine   : ") (display (kelvin->rankine k)) (newline)))


#include <stdio.h>
#include <time.h>

#define note_file "NOTES.TXT"

int main(int argc, char**argv)
{
	FILE *note = 0;
	time_t tm;
	int i;
	char *p;

	if (argc < 2) {
		if ((note = fopen(note_file, "r")))
			while ((i = fgetc(note)) != EOF)
				putchar(i);

	} else if ((note = fopen(note_file, "a"))) {
		tm = time(0);
		p = ctime(&tm);

		/* skip the newline */
		while (*p) fputc(*p != '\n'?*p:'\t', note), p++;

		for (i = 1; i < argc; i++)
			fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
	}

	if (note) fclose(note);
	return 0;
}


using System;
using System.IO;
using System.Text;

namespace RosettaCode
{
  internal class Program
  {
    private const string FileName = "NOTES.TXT";

    private static void Main(string[] args)
    {
      if (args.Length==0)
      {
        string txt = File.ReadAllText(FileName);
        Console.WriteLine(txt);
      }
      else
      {
        var sb = new StringBuilder();
        sb.Append(DateTime.Now).Append("\n\t");
        foreach (string s in args)
          sb.Append(s).Append(" ");
        sb.Append("\n");

        if (File.Exists(FileName))
          File.AppendAllText(FileName, sb.ToString());
        else
          File.WriteAllText(FileName, sb.ToString());
      }
    }
  }
}


void main() /*@safe*/ {
    import std.stdio, std.range, std.algorithm, std.typecons, std.string;

    auto iCubes = iota(1u, 1201u).map!(x => tuple(x, x ^^ 3));
    bool[Tuple!(uint, uint)][uint] sum2cubes;
    foreach (i, immutable i3; iCubes)
        foreach (j, immutable j3; iCubes[i .. $])
            sum2cubes[i3 + j3][tuple(i, j)] = true;

    const taxis = sum2cubes.byKeyValue.filter!(p => p.value.length > 1)
                  .array.schwartzSort!(p => p.key).release;

    foreach (/*immutable*/ const r; [[0, 25], [2000 - 1, 2000 + 6]]) {
        foreach (immutable i, const t; taxis[r[0] .. r[1]])
            writefln("%4d: %10d =%-(%s =%)", i + r[0] + 1, t.key,
                     t.value.keys.sort().map!q{"%4d^3 + %4d^3".format(a[])});
        writeln;
    }
}


const NM="address.db";
dbExec(NM,"create table address (street, city, state, zip);");


$ include "seed7_05.s7i";
  include "float.s7i";

const func float: celsius (in float: kelvin) is
  return kelvin - 273.15;

const func float: fahrenheit (in float: kelvin) is
  return kelvin * 1.8 - 459.67;

const func float: rankine (in float: kelvin) is
  return kelvin * 1.8;

const proc: main is func
  local
    var float: kelvin is 0.0;
  begin
    write("Enter temperature in kelvin: ");
    readln(kelvin);
    writeln("K: " <& kelvin             digits 2 lpad 7);
    writeln("C: " <& celsius(kelvin)    digits 2 lpad 7);
    writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7);
    writeln("R: " <& rankine(kelvin)    digits 2 lpad 7);
  end func;


var scale = Hash(
    Celcius    => Hash.new(factor => 1  , offset => -273.15 ),
    Rankine    => Hash.new(factor => 1.8, offset =>    0    ),
    Fahrenheit => Hash.new(factor => 1.8, offset => -459.67 ),
);

var kelvin = Sys.readln("Enter a temperature in Kelvin: ").to_n;
kelvin >= 0 || die "No such temperature!";

scale.keys.sort.each { |key|
    printf("%12s:%8.2f\n", key, kelvin*scale{key}{:factor} + scale{key}{:offset});
}


#include <fstream>
#include <iostream>
#include <ctime>
using namespace std;

#define note_file "NOTES.TXT"

int main(int argc, char **argv)
{
	if(argc>1)
	{
		ofstream Notes(note_file, ios::app);
		time_t timer = time(NULL);
		if(Notes.is_open())
		{
			Notes << asctime(localtime(&timer)) << '\t';
			for(int i=1;i<argc;i++)
				Notes << argv[i] << ' ';
			Notes << endl;
			Notes.close();
		}
	}
	else
	{
		ifstream Notes(note_file, ios::in);
		string line;
		if(Notes.is_open())
		{
			while(!Notes.eof())
			{
				getline(Notes, line);
				cout << line << endl;
			}
			Notes.close();
		}
	}
}


(ns rosettacode.notes
  (:use [clojure.string :only [join]]))

(defn notes [notes]
  (if (seq notes)
    (spit
     "NOTES.txt"
     (str (java.util.Date.) "\n" "\t"
          (join " " notes) "\n")
     :append true)
    (println (slurp "NOTES.txt"))))

(notes *command-line-args*)


$ close /nolog sums_of_cubes
$ on control_y then $ goto clean
$ open /write sums_of_cubes sums_of_cubes.txt
$ i = 1
$ loop1:
$  write sys$output i
$  j = 1
$  loop2:
$   sum = i * i * i + j * j * j
$   if sum .lt. 0
$   then
$    write sys$output "overflow at ", j
$    goto next_i
$   endif
$   write sums_of_cubes f$fao( "!10SL,!10SL,!10SL", sum, i, j )
$   j = j + 1
$   if j .le. i then $ goto loop2
$ next_i:
$  i = i + 1
$  if i .le. 1289 then $ goto loop1  ! cube_root of 2^31-1
$ close sums_of_cubes
$ sort sums_of_cubes.txt sorted_sums_of_cubes.txt
$ close /nolog sorted_sums_of_cubes
$ open sorted_sums_of_cubes sorted_sums_of_cubes.txt
$ count = 0
$ read sorted_sums_of_cubes prev_prev_line  ! need to detect when there are more than just 2 different sums, e.g. 456
$ prev_prev_sum = f$element( 0, ",", f$edit( prev_prev_line, "collapse" ))
$ read sorted_sums_of_cubes prev_line
$ prev_sum = f$element( 0,",", f$edit( prev_line, "collapse" ))
$ loop3:
$  read /end_of_file = done sorted_sums_of_cubes line
$  sum = f$element( 0, ",", f$edit( line, "collapse" ))
$  if sum .eqs. prev_sum
$  then
$   if sum .nes. prev_prev_sum then $ count = count + 1
$   int_sum = f$integer( sum )
$   i1 = f$integer( f$element( 1, ",", prev_line ))
$   j1 = f$integer( f$element( 2, ",", prev_line ))
$   i2 = f$integer( f$element( 1, ",", line ))
$   j2 = f$integer( f$element( 2, ",", line ))
$   if count .le. 25 .or. ( count .ge. 2000 .and. count .le. 2006 ) then -
$    write sys$output f$fao( "!4SL:!11SL =!5SL^3 +!5SL^3 =!5SL^3 +!5SL^3", count, int_sum, i1, j1, i2, j2 )
$  endif
$  prev_prev_line = prev_line
$  prev_prev_sum = prev_sum
$  prev_line = line
$  prev_sum = sum
$  goto loop3
$ done:
$ close sorted_sums_of_cubes
$ exit
$
$ clean:
$ close /nolog sorted_sums_of_cubes
$ close /nolog sums_of_cubes


func KtoC(kelvin : Double)->Double{

    return kelvin-273.15
}

func KtoF(kelvin : Double)->Double{

    return ((kelvin-273.15)*1.8)+32
}

func KtoR(kelvin : Double)->Double{

    return ((kelvin-273.15)*1.8)+491.67
}

var k// input
print("\(k) Kelvin")
var c=KtoC(kelvin : k)
print("\(c) Celsius")
var f=KtoF(kelvin : k)
print("\(f) Fahrenheit")
var r=KtoR(kelvin : k)
print("\(r) Rankine")


proc temps {k} {
    set c [expr {$k - 273.15}]
    set r [expr {$k / 5.0 * 9.0}]
    set f [expr {$r - 459.67}]
    list $k $c $f $r
}


#!/bin/ksh
# Temperature conversion
typeset tt[1]=0.00 tt[2]=273.15 tt[3]=373.15
for i in {1..3}
do
    ((t=tt[i]))
    echo $i
    echo "Kelvin:     $t K"
    echo "Celsius:    $((t-273.15)) C"
    echo "Fahrenheit: $((t*18/10-459.67)) F"
    echo "Rankine:    $((t*18/10)) R"
done


% This program uses the "get_argv" function that is supplied iwth
% PCLU in "useful.lib".

NOTEFILE = "notes.txt"

% Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM]
format_date = proc (d: date) returns (string)
    ds: stream := stream$create_output()
    stream$putzero(ds, int$unparse(d.month), 2)
    stream$putc(ds, '/')
    stream$putzero(ds, int$unparse(d.day), 2)
    stream$putc(ds, '/')
    stream$putzero(ds, int$unparse(d.year), 4)
    stream$putc(ds, ' ')

    hour: int := d.hour // 12
    if hour=0 then hour:=12 end
    ampm: string := "AM"
    if d.hour>=12 then ampm := "PM" end

    stream$putzero(ds, int$unparse(hour), 2)
    stream$putc(ds, ':')
    stream$putzero(ds, int$unparse(d.minute), 2)
    stream$putc(ds, ':')
    stream$putzero(ds, int$unparse(d.second), 2)
    stream$putc(ds, ' ')
    stream$puts(ds, ampm)
    return(stream$get_contents(ds))
end format_date

% Add a note to the file
add_note = proc (note: sequence[string])
    fn: file_name := file_name$parse(NOTEFILE)
    out: stream := stream$open(fn, "append")
    stream$putl(out, format_date(now()))

    c: char := '\t'
    for part: string in sequence[string]$elements(note) do
        stream$putc(out, c)
        stream$puts(out, part)
        c := ' '
    end
    stream$putc(out, '\n')
    stream$close(out)
end add_note

% Show the notes file, if it exists
show_notes = proc ()
    po: stream := stream$primary_output()
    fn: file_name := file_name$parse(NOTEFILE)
    begin
        inp: stream := stream$open(fn, "read")
        while true do
            stream$putl(po, stream$getl(inp))
            except when end_of_file: break end
        end
        stream$close(inp)
    end except when not_possible(s: string): end
end show_notes

% Add a note if one is given, show the notes otherwise
start_up = proc ()
    note: sequence[string] := get_argv()
    if sequence[string]$empty(note)
        then show_notes()
        else add_note(note)
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. NOTES.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT OPTIONAL notes ASSIGN TO "NOTES.TXT"
               ORGANIZATION LINE SEQUENTIAL
               FILE STATUS note-status.

       DATA DIVISION.
       FILE SECTION.
       FD  notes.
       01  note-record       PIC X(256).

       LOCAL-STORAGE SECTION.
       01  note-status       PIC 99.
           88  notes-ok      VALUE 0 THRU 9.

       01  date-now.
           03  current-year  PIC 9(4).
           03  current-month PIC 99.
           03  current-day   PIC 99.

       01  time-now.
           03  current-hour  PIC 99.
           03  current-min   PIC 99.
           03  current-sec   PIC 99.

       01  args              PIC X(256).

       PROCEDURE DIVISION.
       DECLARATIVES.
       note-error SECTION.
           USE AFTER STANDARD ERROR PROCEDURE ON notes.

           DISPLAY "Error using NOTES.TXT. Error code: " note-status
           .
       END DECLARATIVES.

       main.
           ACCEPT args FROM COMMAND-LINE

*          *> If there are no args, display contents of NOTES.TXT.
           IF args = SPACES
               OPEN INPUT notes

               PERFORM FOREVER
*                  *> READ has no syntax highlighting, but END-READ does.
*                  *> Go figure.
                   READ notes
                       AT END
                           EXIT PERFORM

                       NOT AT END
                           DISPLAY FUNCTION TRIM(note-record)
                   END-READ
               END-PERFORM
           ELSE
               OPEN EXTEND notes

*              *> Write date and time to file.
               ACCEPT date-now FROM DATE YYYYMMDD
               ACCEPT time-now FROM TIME
               STRING current-year "-" current-month "-" current-day
                   " " current-hour ":" current-min ":" current-sec
                   INTO note-record
               WRITE note-record

*              *> Write arguments to file as they were passed.
               STRING X"09", args INTO note-record
               WRITE note-record
           END-IF

           CLOSE notes

           GOBACK
           .


(require '(heap compile))

(define (scube a b) (+ (* a a a) (* b b b)))
(compile 'scube "-f") ; "-f" means : no bigint, no rational used

;; is n - a^3 a cube  b^3?
;; if yes return b, else #f
(define (taxi? n a (b 0))
	(set! b (cbrt (- n (* a a a)))) ;; cbrt is ∛
	(when (and (< b a) (integer? b)) b))
(compile 'taxi? "-f")

#|-------------------
looking for taxis
--------------------|#
;; remove from heap until heap-top >= a
;; when twins are removed, it is a taxicab number : push it
;; at any time (top stack) = last removed

(define (clean-taxi H limit: a  min-of-heap: htop)
		(when (and htop (> a htop))
				(when (!= (stack-top S) htop) (pop S))
				(push S htop)
				(heap-pop H)
				(clean-taxi H  a (heap-top H))))
(compile 'clean-taxi "-f")

;; loop on a and b, b <=a , until n taxicabs found
(define (taxicab (n 2100))
	(for ((a (in-naturals)))
		(clean-taxi H (* a a a) (heap-top H))
		#:break (> (stack-length S) n)
		(for ((b a))
			(heap-push H (scube a b)))))

#|------------------
printing taxis
---------------------|#
;; string of all decompositions
(define (taxi->string i n)
	(string-append (format "%d. %d " (1+ i) n)
	(for/string ((a (cbrt n)))
		#:when (taxi? n a)
		(format " = %4d^3 + %4d^3" a (taxi? n a)))))

(define (taxi-print taxis (nfrom 0) (nto 26))
		(for ((i (in-naturals nfrom)) (taxi (sublist taxis nfrom nto)))
		(writeln (taxi->string i (first taxi)))))


decl double k
while true
    out "Temp. in Kelvin? " console
    set k (in double console)
    out "K\t" k endl "C\t" (- k 273.15) endl console
    out "F\t" (- (* k 1.8) 459.67) endl "R\t" (* k 1.8) endl endl console
end while


Option Explicit

Sub Main_Conv_Temp()
Dim K As Single, Result As Single
    K = 21
    Debug.Print "Input in Kelvin      : " & Format(K, "0.00")
    Debug.Print "Output in Celsius    : " & IIf(ConvTemp(Result, K, "C"), Format(Result, "0.00"), False)
    Debug.Print "Output in Fahrenheit : " & IIf(ConvTemp(Result, K, "F"), Format(Result, "0.00"), False)
    Debug.Print "Output in Rankine    : " & IIf(ConvTemp(Result, K, "R"), Format(Result, "0.00"), False)
    Debug.Print "Output error         : " & IIf(ConvTemp(Result, K, "T"), Format(Result, "0.00"), False)
End Sub

Function ConvTemp(sngReturn As Single, Kelv As Single, InWhat As String) As Boolean
Dim ratio As Single

    ConvTemp = True
    ratio = 9 / 5
    Select Case UCase(InWhat)
        Case "C": sngReturn = Kelv - 273.15
        Case "F": sngReturn = (Kelv * ratio) - 459.67
        Case "R": sngReturn = Kelv * ratio
        Case Else: ConvTemp = False
    End Select
End Function


WScript.StdOut.Write "Enter the temperature in Kelvin:"
tmp = WScript.StdIn.ReadLine

WScript.StdOut.WriteLine "Kelvin: " & tmp
WScript.StdOut.WriteLine "Fahrenheit: " & fahrenheit(CInt(tmp))
WScript.StdOut.WriteLine "Celsius: " & celsius(CInt(tmp))
WScript.StdOut.WriteLine "Rankine: " & rankine(CInt(tmp))

Function fahrenheit(k)
    fahrenheit = (k*1.8)-459.67
End Function

Function celsius(k)
    celsius = k-273.15
End Function

Function rankine(k)
    rankine = (k-273.15)*1.8+491.67
End Function


(defparameter *notes* "NOTES.TXT")

(defun format-date-time (stream)
  (multiple-value-bind (second minute hour date month year) (get-decoded-time)
    (format stream "~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
            year month date hour minute second)))

(defun notes (args)
  (if args
      (with-open-file (s *notes* :direction :output
                                 :if-exists :append
                                 :if-does-not-exist :create)
        (format-date-time s)
        (format s "~&~A~{~A~^ ~}~%" #\Tab args))
      (with-open-file (s *notes* :if-does-not-exist nil)
        (when s
          (loop for line = (read-line s nil)
                while line
                do (write-line line))))))

(defun main ()
  (notes (uiop:command-line-arguments)))


void main(in string[] args) {
    import std.stdio, std.file, std.datetime, std.range;

    immutable filename = "NOTES.TXT";

    if (args.length == 1) {
        if (filename.exists && filename.isFile)
            writefln("%-(%s\n%)", filename.File.byLine);
    } else {
        auto f = File(filename, "a+");
        f.writefln("%s", cast(DateTime)Clock.currTime);
        f.writefln("\t%-(%s %)", args.dropOne);
    }
}


#DEFINE ABSZC 273.16
#DEFINE ABSZF 459.67
LOCAL k As Double, c As Double, f As Double, r As Double, n As Integer, ;
cf As String
n = SET("Decimals")
cf = SET("Fixed")
SET DECIMALS TO 2
SET FIXED ON
CLEAR
DO WHILE .T.
    k = VAL(INPUTBOX("Degrees Kelvin:", "Temperature"))
    IF k <= 0
    EXIT
    ENDIF
    ? "K:", k
    c = k - ABSZC
    ? "C:", c
    f = 1.8*c + 32
    ? "F:", f
    r = f + ABSZF
    ? "R:", r
    ?
ENDDO
SET FIXED &cf
SET DECIMALS TO n


import "/fmt" for Fmt

var tempConv = Fn.new { |k|
    var c = k - 273.15
    var f = c * 1.8 + 32
    var r = f + 459.67
    System.print("%(Fmt.f(7, k, 2))˚ Kelvin")
    System.print("%(Fmt.f(7, c, 2))˚ Celsius")
    System.print("%(Fmt.f(7, f, 2))˚ Fahrenheit")
    System.print("%(Fmt.f(7, r, 2))˚ Rankine")
    System.print()
}

var ks = [0, 21, 100]
for (k in ks) tempConv.call(k)


program notes;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils,
  IOUtils;

const
  FILENAME = 'NOTES.TXT';
  TAB = #9;

var
  sw: TStreamWriter;
  i : integer;

begin
  if ParamCount = 0 then
  begin
    if TFile.Exists(FILENAME) then
      write(TFile.ReadAllText(FILENAME));
  end
  else
  begin
    if TFile.Exists(FILENAME) then
      sw := TFile.AppendText(FILENAME)
    else
      sw := TFile.CreateText(FILENAME);

    sw.Write(FormatDateTime('yyyy-mm-dd hh:nn',Now));
    sw.Write(TAB);
    for i := 1 to ParamCount do
    begin
      sw.Write(ParamStr(i));
      if i < ParamCount then
        sw.Write(' ');
    end;
    sw.WriteLine;
    sw.Free;
  end;
end.


#!/usr/bin/env rune

def f := <file:notes.txt>
def date := makeCommand("date")

switch (interp.getArgs()) {
    match [] {
        if (f.exists()) {
            for line in f { print(line) }
        }
    }
    match noteArgs {
        def w := f.textWriter(true)
        w.print(date()[0], "\t", " ".rjoin(noteArgs), "\n")
        w.close()
    }
}


defmodule Taxicab do
  def numbers(n \\ 1200) do
    (for i <- 1..n, j <- i..n, do: {i,j})
    |> Enum.group_by(fn {i,j} -> i*i*i + j*j*j end)
    |> Enum.filter(fn {_,v} -> length(v)>1 end)
    |> Enum.sort
  end
end

nums = Taxicab.numbers |> Enum.with_index
Enum.each(nums, fn {x,i} ->
  if i in 0..24 or i in 1999..2005 do
    IO.puts "#{i+1} : #{inspect x}"
  end
end)


variable taxicablist
variable searched-cubessum
73 constant max-constituent \ uses magic numbers

: cube dup dup * * ;
: cubessum cube swap cube + ;

: ?taxicab ( a b -- c d true | false )
\ does exist an (c, d) such that c^3+d^3 = a^3+b^3 ?
  2dup cubessum searched-cubessum !
  dup 1- rot 1+ do   \ c is possibly in [a+1 b-2]
    dup i 1+ do      \ d is possibly in [c+1 b-1]
      j i cubessum searched-cubessum @ = if drop j i true unloop unloop exit then
    loop
  loop drop false ;

: swap-taxi ( n -- )
  dup 5 cells + swap do
    i @     i 5 cells - @     i !     i 5 cells - !
  cell +loop ;

: bubble-taxicablist
  here 5 cells - taxicablist @ = if exit then        \ not for the first one
  taxicablist @ here 5 cells - do
    i @     i 5 cells - @     > if unloop exit then  \ no (more) need to reorder
    i swap-taxi
  5 cells -loop ;

: store-taxicab ( a b c d -- )
  2dup cubessum , swap , , swap , ,
  bubble-taxicablist ;

: build-taxicablist
  here taxicablist !
  max-constituent 3 - 1 do         \ a in [ 1 ; max-3 ]
    i 3 + max-constituent swap do  \ b in [ a+3 ; max ]
      j i ?taxicab if j i store-taxicab then
    loop
  loop ;

: .nextcube cell + dup @ . ." ^3 " ;
: .taxi
  dup @ .
  ." = " .nextcube ." + " .nextcube ." = " .nextcube ." + " .nextcube
  drop ;

: taxicab 5 cells * taxicablist @ + ;

: list-taxicabs ( n -- )
  0 do
    cr I 1+ . ." : "
    I taxicab .taxi
  loop ;

build-taxicablist
25 list-taxicabs


(DEFUN CONVERT-TEMPERATURE ()
    (SETQ *FLONUM-FORMAT* "%.2f")
    (DISPLAY "Enter a temperature in Kelvin.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE K (READ))
    (DISPLAY `(K = ,K))
    (NEWLINE)
    (DISPLAY `(C = ,(- K 273.15)))
    (NEWLINE)
    (DISPLAY `(F = ,(- (* K 1.8) 459.67)))
    (NEWLINE)
    (DISPLAY `(R = ,(* K 1.8))))


defmodule Take_notes do
  @filename "NOTES.TXT"

  def main( [] ), do: display_notes
  def main( arguments ), do: save_notes( arguments )

  def display_notes, do: IO.puts File.read!(@filename)

  def save_notes( arguments ) do
    notes = "#{inspect :calendar.local_time}\n\t" <> Enum.join(arguments, " ")
    File.open!(@filename, [:append], fn(file) -> IO.puts(file, notes) end)
  end
end

Take_notes.main(System.argv)


#! /usr/bin/env escript

main( Arguments ) ->
	display_notes( Arguments ),
	save_notes( Arguments ).

display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] );
display_notes( _Arguments ) -> ok.

file() -> "NOTES.TXT".

file_contents() -> file_contents( file:read_file(file()) ).

file_contents( {ok, Binary} ) -> Binary;
file_contents( {error, _Error} ) -> <<>>.

save_notes( [] ) -> ok;
save_notes( Arguments ) ->
	Date = io_lib:format( "~p~n", [calendar:local_time()] ),
	Notes = [Date ++ "\t" | [io_lib:format( "~s ", [X]) || X <- Arguments]],
	Existing_contents = file_contents(),
	file:write_file( file(), [Existing_contents, Notes, "\n"] ).


! A non-bruteforce approach
     PROGRAM POOKA
      IMPLICIT NONE
!
! PARAMETER definitions
!
      INTEGER , PARAMETER  ::  NVARS = 25
!
! Local variables
!
      REAL  ::  f1
      REAL  ::  f2
      INTEGER  ::  hits
      INTEGER  ::  s
      INTEGER  ::  TAXICAB

      hits = 0
      s = 0
      f1 = SECOND()
      DO WHILE ( hits<NVARS )
         s = s + 1
         hits = hits + TAXICAB(s)
      END DO
      f2 = SECOND()
      PRINT * , 'elapsed time = ' , f2 - f1 , 'For ' , NVARS , ' Variables'
      STOP
      END PROGRAM POOKA

      FUNCTION TAXICAB(N)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  N
      INTEGER  ::  TAXICAB
      INTENT (IN) N
!
! Local variables
!
      INTEGER  ::  holder
      INTEGER  ::  oldx
      INTEGER  ::  oldy
      INTEGER  ::  s
      INTEGER  ::  x
      INTEGER  ::  y
      real*8,parameter :: xpon=(1.0D0/3.0D0)
!
      x = 0
      holder = 0
      oldx = 0
      oldy = 0
      TAXICAB = 0
      y = INT(N**xpon)
      DO WHILE ( x<=y )
         s = x**3 + y**3
         IF( s<N )THEN
            x = x + 1
         ELSE IF( s>N )THEN
            y = y - 1
         ELSE
            IF( holder==s )THEN ! Print the last value and this one that correspond
               WRITE(6 , 34)s , '(' , x**3 , y**3 , ')' , '(' , oldx**3 , oldy**3 , ')'
 34            FORMAT(1x , i12 , 10x , 1A1 , i12 , 2x , i12 , 1A1 , 10x , 1A1 , i12 , 2x ,&
                    & i12 , 1A1)
               TAXICAB = 1  ! Indicate that we found a Taxi Number
            END IF
            holder = s      ! Set to the number that appears a potential cab number
            oldx = x       ! Retain the values for the 2 cubes
            oldy = y
            x = x + 1       ! Keep looking
            y = y - 1
         END IF
      END DO
      RETURN
      END FUNCTION TAXICAB


10 REM Translation of traditional basic version
20 INPUT "Kelvin Degrees? ";k
30 IF k <= 0 THEN STOP: REM A value of zero or less will end program
40 LET c = k - 273.15
50 LET f = k * 1.8 - 459.67
60 LET r = k * 1.8
70 PRINT k; " Kelvin is equivalent to"
80 PRINT c; " Degrees Celsius"
90 PRINT f; " Degrees Fahrenheit"
100 PRINT r; " Degrees Rankine"
110 GO TO 20


constant cmd = command_line()
constant filename = "notes.txt"
integer fn
object line
sequence date_time

if length(cmd) < 3 then
    fn = open(filename,"r")
    if fn != -1 then
        while 1 do
            line = gets(fn)
            if atom(line) then
                exit
            end if
            puts(1,line)
        end while
        close(fn)
    end if
else
    fn = open(filename,"a") -- if such file doesn't exist it will be created
    date_time = date()
    date_time = date_time[1..6]
    date_time[1] += 1900
    printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date_time)
    line = "\t"
    for n = 3 to length(cmd) do
        line &= cmd[n] & ' '
    end for
    line[$] = '\n'
    puts(fn,line)
    close(fn)
end if


open System;;
open System.IO;;

let file_path = "notes.txt";;

let show_notes () =
    try
        printfn "%s" <| File.ReadAllText(file_path)
    with
        _ -> printfn "Take some notes first!";;

let take_note (note : string) =
    let now = DateTime.Now.ToString() in
    let note = sprintf "%s\n\t%s" now note in
    use file_stream = File.AppendText file_path in (* 'use' closes file_stream automatically when control leaves the scope *)
        file_stream.WriteLine note;;

[<EntryPoint>]
let main args =
    match Array.length args with
        | 0 -> show_notes()
        | _ -> take_note <| String.concat " " args;
    0;;


' version 11-10-2016
' compile with: fbc -s console

' Brute force

' adopted from "Sorting algorithms/Shell" sort Task
Sub shellsort(s() As String)
  ' sort from lower bound to the highter bound
  Dim As UInteger lb = LBound(s)
  Dim As UInteger ub = UBound(s)
  Dim As Integer done, i, inc = ub - lb

  Do
    inc = inc / 2.2
    If inc < 1 Then inc = 1

    Do
      done = 0
      For i = lb To ub - inc
        If s(i) > s(i + inc) Then
          Swap s(i), s(i + inc)
          done = 1
        End If
      Next
    Loop Until done = 0

  Loop Until inc = 1

End Sub

' ------=< MAIN >=------

Dim As UInteger x, y, count, c, sum
Dim As UInteger cube(1290)
Dim As String result(), str1, str2, str3
Dim As String buf11 = Space(11), buf5 = Space(5)
ReDim result(900000)    ' ~1291*1291\2

' set up the cubes
Print : Print " Calculate cubes"
For x = 1 To 1290
  cube(x) = x*x*x
Next

' combine and store
Print : Print " Combine cubes"
For x = 1 To 1290
  For y = x To 1290
    sum = cube(x)+cube(y)
    RSet buf11, Str(sum) : str1 = buf11
    RSet buf5, Str(x) : str2 = buf5
    RSet buf5, Str(y) : Str3 = buf5
    result(count)=buf11 + " = " + str2 + " ^ 3 + " + str3 + " ^ 3"
    count = count +1
  Next
Next

count= count -1
ReDim Preserve result(count) ' trim the array

Print : Print " Sort (takes some time)"
shellsort(result())   ' sort

Print : Print " Find the Taxicab numbers"
c = 1 ' start at index 1
For x = 0 To count -1
  ' find sums that match
  If Left(result(x), 11) = Left(result(x + 1), 11) Then
    result(c) = result(x)
    y = x +1
    Do    ' merge the other solution(s)
      result(c) = result(c) + Mid(result(y), 12)
      y = y +1
    Loop Until Left(result(x), 11) <> Left(result(y), 11)
    x = y -1 ' let x point to last match result
    c = c +1
  End If
Next

c = c -1
Print : Print " "; c; " Taxicab numbers found"
ReDim Preserve result(c) ' trim the array again

cls
Print : Print " Print first 25 numbers" : Print
For x = 1 To 25
  Print result(x)
Next

Print : Print " The 2000th to the 2006th" : Print
For x = 2000 To 2006
  Print result(x)
Next

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


#! /usr/bin/env factor
USING: kernel calendar calendar.format io io.encodings.utf8 io.files
sequences command-line namespaces ;

command-line get [
    "notes.txt" utf8 file-contents print
] [
    " " join "\t" prepend
    "notes.txt" utf8 [
        now timestamp>ymdhms print
        print flush
    ] with-file-appender
] if-empty


class Notes
{
  public static Void main (Str[] args)
  {
    notesFile := File(`notes.txt`) // the backticks make a URI
    if (args.isEmpty)
    {
      if (notesFile.exists)
      {
        notesFile.eachLine |line| { echo (line) }
      }
    }
    else
    {
      // notice the following uses a block so the 'printLine/close'
      // operations are all applied to the same output stream for notesFile
      notesFile.out(true) // 'true' to append to file
      {
        printLine ( DateTime.now.toLocale("DD-MM-YY hh:mm:ss").toStr )
        printLine ( "\t" + args.join(" ") )
        close
      }
    }
  }
}


vocabulary note-words
get-current also note-words definitions

\ -- notes.txt
variable file
: open       s" notes.txt" r/w open-file if
             s" notes.txt" r/w create-file throw then file ! ;
: appending  file @ file-size throw file @ reposition-file throw ;
: write      file @ write-file throw ;
: close      file @ close-file throw ;

\ -- SwiftForth console workaround
9 constant TAB
: type ( c-addr u -- )
  bounds ?do
    i [email protected] dup TAB = if drop 8 spaces else emit then
  loop ;

\ -- dump notes.txt
create buf 4096 allot
: dump ( -- )
  cr begin buf 4096 file @ read-file throw dup while
    buf swap type
  repeat drop ;

\ -- time and date
: time   @time (time) ;
: date   @date (date) ;

\ -- add note
: cr     s\" \n" write ;
: tab    s\" \t" write ;
: space  s"  " write ;
: add-note ( c-addr u -- ) appending
  date write space time write cr
  tab ( note ) write cr ;

set-current

\ -- note
: note ( "note" -- )
  open 0 parse dup if add-note
  else 2drop dump then close ;
previous


program notes
implicit none
integer                      :: i, length, iargs, lun, ios
integer,dimension(8)         :: values
character(len=:),allocatable :: arg
character(len=256)           :: line
character(len=1),parameter   :: tab=char(9)
   iargs = command_argument_count()
   open(file='notes.txt',newunit=lun,action='readwrite',position='append',status='unknown')
   if(iargs.eq.0)then
      rewind(lun)
      do
         read(lun,'(a)',iostat=ios)line
         if(ios.ne.0)exit
         write(*,'(a)')trim(line)
      enddo
   else
      call date_and_time(VALUES=values)
      write(lun,'(*(g0))')values(1),"-",values(2),"-",values(3),"T",values(5),":",values(6),":",values(7)
      write(lun,'(a)',advance='no')tab
      do i=1,iargs
         call get_command_argument(number=i,length=length)
         arg=repeat(' ',length)
         call get_command_argument(i, arg)
         write(lun,'(a,1x)',advance='no')arg
      enddo
      write(lun,*)
   endif
end program notes


package main

import (
	"container/heap"
	"fmt"
	"strings"
)

type CubeSum struct {
	x, y  uint16
	value uint64
}

func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }

type CubeSumHeap []*CubeSum

func (h CubeSumHeap) Len() int            { return len(h) }
func (h CubeSumHeap) Less(i, j int) bool  { return h[i].value < h[j].value }
func (h CubeSumHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *CubeSumHeap) Push(x interface{}) { (*h) = append(*h, x.(*CubeSum)) }
func (h *CubeSumHeap) Pop() interface{} {
	x := (*h)[len(*h)-1]
	*h = (*h)[:len(*h)-1]
	return x
}

type TaxicabGen struct {
	n int
	h CubeSumHeap
}

var cubes []uint64 // cubes[i] == i*i*i
func cubesExtend(i int) {
	for n := uint64(len(cubes)); n <= uint64(i); n++ {
		cubes = append(cubes, n*n*n)
	}
}

func (g *TaxicabGen) min() CubeSum {
	for len(g.h) == 0 || g.h[0].value > cubes[g.n] {
		g.n++
		cubesExtend(g.n)
		heap.Push(&g.h, &CubeSum{uint16(g.n), 1, cubes[g.n] + 1})
	}
	// Note, we use g.h[0] to "peek" at the min heap entry.
	c := *(g.h[0])
	if c.y+1 <= c.x {
		// Instead of Pop and Push we modify in place and fix.
		g.h[0].y++
		g.h[0].fixvalue()
		heap.Fix(&g.h, 0)
	} else {
		heap.Pop(&g.h)
	}
	return c
}

// Originally this was just: type Taxicab [2]CubeSum
// and we always returned two sums. Now we return all the sums.
type Taxicab []CubeSum

func (t Taxicab) String() string {
	var b strings.Builder
	fmt.Fprintf(&b, "%12d", t[0].value)
	for _, p := range t {
		fmt.Fprintf(&b, " =%5d³ +%5d³", p.x, p.y)
	}
	return b.String()
}

func (g *TaxicabGen) Next() Taxicab {
	a, b := g.min(), g.min()
	for a.value != b.value {
		a, b = b, g.min()
	}
	//return Taxicab{a,b}

	// Originally this just returned Taxicab{a,b} and we didn't look
	// further into the heap. Since we start by looking at the next
	// pair, that is okay until the first Taxicab number with four
	// ways of expressing the cube, which doesn't happen until the
	// 97,235th Taxicab:
	//     6963472309248 = 16630³ + 13322³ = 18072³ + 10200³
	//                   = 18948³ +  5436³ = 19083³ +  2421³
	// Now we return all ways so we need to peek into the heap.
	t := Taxicab{a, b}
	for g.h[0].value == b.value {
		t = append(t, g.min())
	}
	return t
}

func main() {
	const (
		low  = 25
		mid  = 2e3
		high = 4e4
	)
	var tg TaxicabGen
	firstn := 3 // To show the first triple, quadruple, etc
	for i := 1; i <= high+6; i++ {
		t := tg.Next()
		switch {
		case len(t) >= firstn:
			firstn++
			fallthrough
		case i <= low || (mid <= i && i <= mid+6) || i >= high:
			//fmt.Printf("h:%-4d  ", len(tg.h))
			fmt.Printf("%5d: %v\n", i, t)
		}
	}
}


If Len(Command) Then
    Open "notes.txt" For Append As #1
    Print #1, Date, Time
    Print #1, Chr(9); Command
    Close
Else
    If Open("notes.txt" For Input As #1) = 0 Then
        Dim As String lin
        Print "Contenido del archivo:"
        Do While Not Eof(1)
            Line Input #1, lin
            Print lin
        Loop
    Else
        Open "notes.txt" For Output As #1
        Print "Archivo 'NOTES.TXT' creado"
    End If
End If
Close #1
Sleep


'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'

Public Sub Main()
Dim sContents As String                                                     'To store the file contents
Dim sArgs As String[] = Args.All                                            'To store all the Command line Arguments

If Not Exist(User.home &/ "NOTES.TXT") Then                                 'If NOTES.TXT doesn't already exist in the current directory then..
  File.Save(User.home &/ "NOTES.TXT", "")                                   'a new NOTES.TXT file should be created.
  Print "New file 'NOTES.TXT' created."                                     'A meassge
Endif

sContents = File.Load(User.home &/ "NOTES.TXT")                             'Get the contents of the file

If Args.count < 2 Then                                                      'If NOTES has arguments (other than the file name)
  Print sContents                                                           'Print the file contents
Else
  sContents &= Format(Now, "dddd dd mmmm, yyyy, hh:nn:ss") & gb.NewLine &   'The current date and time are appended to the local NOTES.TXT followed by a newline and..
     gb.Tab & sArgs.Join(" ") & gb.NewLine                                  'Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline
  Print sContents                                                           'Displays the current contents of the local NOTES.TXT
  File.Save(User.home &/ "NOTES.TXT", sContents)                            'Write contents to NOTES.TXT
Endif

End


import Data.List (groupBy, sortOn, tails, transpose)
import Data.Function (on)

--------------------- TAXICAB NUMBERS --------------------

taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]]
taxis nCubes =
  filter ((> 1) . length) $
  groupBy (on (==) fst) $
  sortOn fst
    [ (fst x + fst y, (x, y))
    | (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes]
    , y <- t ]

--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_ putStrLn $
  concat <$>
  transpose
    (((<$>) =<< flip justifyRight ' ' . maximum . (length <$>)) <$>
     transpose (taxiRow <$> (take 25 xs <> take 7 (drop 1999 xs))))
  where
    xs = zip [1 ..] (taxis 1200)
    justifyRight n c = (drop . length) <*> (replicate n c <>)

------------------------- DISPLAY ------------------------
taxiRow :: (Int, [(Int, ((Int, Int), (Int, Int)))]) -> [String]
taxiRow (n, [(a, ((axc, axr), (ayc, ayr))), (b, ((bxc, bxr), (byc, byr)))]) =
  concat
    [ [show n, ". ", show a, " = "]
    , term axr axc " + "
    , term ayr ayc "  or  "
    , term bxr bxc " + "
    , term byr byc []
    ]
  where
    term r c l = ["(", show r, "^3=", show c, ")", l]


package main

import (
	"fmt"
	"io"
	"os"
	"strings"
	"time"
)

func addNote(fn string, note string) error {
	f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return err
	}
	_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
	// To be extra careful with errors from Close():
	if cErr := f.Close(); err == nil {
		err = cErr
	}
	return err
}

func showNotes(w io.Writer, fn string) error {
	f, err := os.Open(fn)
	if err != nil {
		if os.IsNotExist(err) {
			return nil // don't report "no such file"
		}
		return err
	}
	_, err = io.Copy(w, f)
	f.Close()
	return err
}

func main() {
	const fn = "NOTES.TXT"
	var err error
	if len(os.Args) > 1 {
		err = addNote(fn, strings.Join(os.Args[1:], " "))
	} else {
		err = showNotes(os.Stdout, fn)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}


def notes = new File('./notes.txt')
if (args) {
    notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
} else {
    println notes.text
}


cubes=: 3^~1+i.100 NB. first 100 cubes
triples=: /:~ ~. ,/ (+ , /:[email protected],)"0/~cubes NB. ordered pairs of cubes (each with their sum)
candidates=: ;({."#. <@(0&#`({[email protected]{.(;,)<@}."1)@.(1<#))/. ])triples

NB. we just want the first 25 taxicab numbers
25{.(,.~ <@>:@[email protected]#) candidates
┌──┬──────┬────────────┬─────────────┐
│1 │1729  │1 1728      │729 1000     │
├──┼──────┼────────────┼─────────────┤
│2 │4104  │8 4096      │729 3375     │
├──┼──────┼────────────┼─────────────┤
│3 │13832 │8 13824     │5832 8000    │
├──┼──────┼────────────┼─────────────┤
│4 │20683 │1000 19683  │6859 13824   │
├──┼──────┼────────────┼─────────────┤
│5 │32832 │64 32768    │5832 27000   │
├──┼──────┼────────────┼─────────────┤
│6 │39312 │8 39304     │3375 35937   │
├──┼──────┼────────────┼─────────────┤
│7 │40033 │729 39304   │4096 35937   │
├──┼──────┼────────────┼─────────────┤
│8 │46683 │27 46656    │19683 27000  │
├──┼──────┼────────────┼─────────────┤
│9 │64232 │4913 59319  │17576 46656  │
├──┼──────┼────────────┼─────────────┤
│10│65728 │1728 64000  │29791 35937  │
├──┼──────┼────────────┼─────────────┤
│11│110656│64 110592   │46656 64000  │
├──┼──────┼────────────┼─────────────┤
│12│110808│216 110592  │19683 91125  │
├──┼──────┼────────────┼─────────────┤
│13│134379│1728 132651 │54872 79507  │
├──┼──────┼────────────┼─────────────┤
│14│149389│512 148877  │24389 125000 │
├──┼──────┼────────────┼─────────────┤
│15│165464│8000 157464 │54872 110592 │
├──┼──────┼────────────┼─────────────┤
│16│171288│4913 166375 │13824 157464 │
├──┼──────┼────────────┼─────────────┤
│17│195841│729 195112  │10648 185193 │
├──┼──────┼────────────┼─────────────┤
│18│216027│27 216000   │10648 205379 │
├──┼──────┼────────────┼─────────────┤
│19│216125│125 216000  │91125 125000 │
├──┼──────┼────────────┼─────────────┤
│20│262656│512 262144  │46656 216000 │
├──┼──────┼────────────┼─────────────┤
│21│314496│64 314432   │27000 287496 │
├──┼──────┼────────────┼─────────────┤
│22│320264│5832 314432 │32768 287496 │
├──┼──────┼────────────┼─────────────┤
│23│327763│27000 300763│132651 195112│
├──┼──────┼────────────┼─────────────┤
│24│373464│216 373248  │157464 216000│
├──┼──────┼────────────┼─────────────┤
│25│402597│74088 328509│175616 226981│
└──┴──────┴────────────┴─────────────┘


import System.Environment (getArgs)
import System.Time (getClockTime)

main :: IO ()
main = do
  args <- getArgs
  if null args
    then catch (readFile "notes.txt" >>= putStr)
               (\_ -> return ())
    else
      do ct <- getClockTime
         appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n"


SYSTEM(RUN) ! start this script in RUN-mode

CHARACTER notes="Notes.txt", txt*1000

! Remove file name from the global variable $CMD_LINE:
EDIT(Text=$CMD_LINE, Mark1, Right=".hic ", Right=4, Mark2, Delete)

IF($CMD_LINE == ' ') THEN
  READ(FIle=notes, LENgth=Lnotes)
  IF( Lnotes ) THEN
    WINDOW(WINdowhandle=hdl, TItle=notes)
    WRITE(Messagebox="?Y") "Finished ?"
  ENDIF
ELSE
  WRITE(Text=txt, Format="UWWW CCYY-MM-DD HH:mm:SS, A") 0, $CRLF//$TAB//TRIM($CMD_LINE)//$CRLF
  OPEN(FIle=notes, APPend)
  WRITE(FIle=notes, CLoSe=1) txt
ENDIF

ALARM(999) ! quit HicEst immediately


procedure write_out_notes (filename)
  file := open (filename, "rt") | stop ("no notes file yet")
  every write (!file)
end

procedure add_to_notes (filename, strs)
  file := open (filename, "at")  | # append to file if it exists
          open (filename, "cat") | # create the file if not there
          stop ("unable to open " || filename)
  writes (file, ctime(&now) || "\n\t")
  every writes (file, !strs || " ")
  write (file, "")
end

procedure main (args)
  notes_file := "notes.txt"
  if *args = 0
    then write_out_notes (notes_file)
    else add_to_notes (notes_file, args)
end


import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

class CubeSum implements Comparable<CubeSum> {
	public long x, y, value;

	public CubeSum(long x, long y) {
		this.x = x;
		this.y = y;
		this.value = x*x*x + y*y*y;
	}

	public String toString() {
		return String.format("%4d^3 + %4d^3", x, y);
	}

	public int compareTo(CubeSum that) {
		return value < that.value ? -1 : value > that.value ? 1 : 0;
	}
}

class SumIterator implements Iterator<CubeSum> {
	PriorityQueue<CubeSum> pq = new PriorityQueue<CubeSum>();
	long n = 0;

	public boolean hasNext() { return true; }
	public CubeSum next() {
		while (pq.size() == 0 || pq.peek().value >= n*n*n)
			pq.add(new CubeSum(++n, 1));

		CubeSum s = pq.remove();
		if (s.x > s.y + 1) pq.add(new CubeSum(s.x, s.y+1));

		return s;
	}
}

class TaxiIterator implements Iterator<List<CubeSum>> {
	Iterator<CubeSum> sumIterator = new SumIterator();
	CubeSum last = sumIterator.next();

	public boolean hasNext() { return true; }
	public List<CubeSum> next() {
		CubeSum s;
		List<CubeSum> train = new ArrayList<CubeSum>();

		while ((s = sumIterator.next()).value != last.value)
			last = s;

		train.add(last);

		do { train.add(s); } while ((s = sumIterator.next()).value == last.value);
		last = s;

		return train;
	}
}

public class Taxi {
	public static final void main(String[] args) {
		Iterator<List<CubeSum>> taxi = new TaxiIterator();

		for (int i = 1; i <= 2006; i++) {
			List<CubeSum> t = taxi.next();
			if (i > 25 && i < 2000) continue;

			System.out.printf("%4d: %10d", i, t.get(0).value);
			for (CubeSum s: t)
				System.out.print(" = " + s);
			System.out.println();
		}
	}
}


require 'files strings'

notes=: monad define
 if. #y do.
   now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY'
   'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y
 elseif. -. _1 -: txt=. fread 'notes.txt' do.
   smoutput txt
 end.
)

notes 2}.ARGV
exit 0


import java.io.*;
import java.nio.channels.*;
import java.util.Date;

public class TakeNotes {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
            ps.println(new Date());
            ps.print("\t" + args[0]);
            for (int i = 1; i < args.length; i++)
                ps.print(" " + args[i]);
            ps.println();
            ps.close();
        } else {
            FileChannel fc = new FileInputStream("notes.txt").getChannel();
            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
            fc.close();
        }
    }
}


var n3s = [],
    s3s = {}
for (var n = 1, e = 1200; n < e; n += 1) n3s[n] = n * n * n
for (var a = 1; a < e - 1; a += 1) {
    var a3 = n3s[a]
    for (var b = a; b < e; b += 1) {
        var b3 = n3s[b]
        var s3 = a3 + b3,
            abs = s3s[s3]
        if (!abs) s3s[s3] = abs = []
        abs.push([a, b])
    }
}

var i = 0
for (var s3 in s3s) {
    var abs = s3s[s3]
    if (abs.length < 2) continue
    i += 1
    if (abs.length == 2 && i > 25 && i < 2000) continue
    if (i > 2006) break
    document.write(i, ': ', s3)
    for (var ab of abs) {
        document.write(' = ', ab[0], '3+', ab[1], '3')
    }
    document.write('
')
}


var notes = 'NOTES.TXT';

var args = WScript.Arguments;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;

if (args.length == 0) {
    if (fso.FileExists(notes)) {
        var f = fso.OpenTextFile(notes, ForReading);
        WScript.Echo(f.ReadAll());
        f.Close();
    }
}
else {
    var f = fso.OpenTextFile(notes, ForAppending, true);
    var d = new Date();
    f.WriteLine(d.toLocaleString());
    f.Write("\t");
    // note that WScript.Arguments is not an array, it is a "collection"
    // it does not have a join() method.
    for (var i = 0; i < args.length; i++) {
        f.Write(args(i) + " ");
    }
    f.WriteLine();
    f.Close();
}


using Dates

const filename = "NOTES.TXT"

if length(ARGS) == 0
    fp = open(filename, "r")
    println(read(fp, String))
else
    fp = open(filename, "a+")
    write(fp, string(DateTime(now()), "\n\t", join(ARGS, " "), "\n"))
end
close(fp)


// version 1.2.10

import java.io.File
import java.util.Date
import java.text.SimpleDateFormat

fun main(args: Array<String>) {
    val f = File("NOTES.TXT")
    // create file if it doesn't exist already
    f.createNewFile()
    if (args.size == 0) {
        println(f.readText())
    }
    else {
        val df = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
        val dt = df.format(Date())
        val notes = "$dt\n\t${args.joinToString(" ")}\n"
        f.appendText(notes)
    }
}


# Output: an array of the form [i^3 + j^3, [i, j]] sorted by the sum.
# Only cubes of 1 to ($in-1) are considered; the listing is therefore truncated
# as it might not capture taxicab numbers greater than $in ^ 3.
def sum_of_two_cubes:
  def cubed: .*.*.;
  . as $in
  | (cubed + 1) as $limit
  | [range(1;$in) as $i | range($i;$in) as $j

  | [ ($i|cubed) + ($j|cubed), [$i, $j] ] ] | sort
  | map( select( .[0] < $limit ) );

# Output a stream of triples [t, d1, d2], in order of t,
# where t is a taxicab number, and d1 and d2 are distinct
# decompositions [i,j] with i^3 + j^3 == t.
# The stream includes each taxicab number once only.
#
def taxicabs0:
  sum_of_two_cubes as $sums
  | range(1;$sums|length) as $i
  | if $sums[$i][0] == $sums[$i-1][0]
      and ($i==1 or $sums[$i][0] != $sums[$i-2][0])
    then [$sums[$i][0], $sums[$i-1][1], $sums[$i][1]]
    else empty
    end;

# Output a stream of $n taxicab triples: [t, d1, d2] as described above,
# without repeating t.
def taxicabs:
  # If your jq includes until/2 then the following definition
  # can be omitted:
  def until(cond; next):
    def _until: if cond then . else (next|_until) end;  _until;
  . as $n
  | [10, ($n / 10 | floor)] | max as $increment
  | [20, ($n / 2 | floor)] | max
  | [ ., [taxicabs0] ]
  | until( .[1] | length >= $m; (.[0] + $increment) | [., [taxicabs0]] )
  | .[1][0:$n] ;


using Printf, DataStructures, IterTools

function findtaxinumbers(nmax::Integer)
    cube2n = Dict{Int,Int}(x ^ 3 => x for x in 0:nmax)
    sum2cubes = DefaultDict{Int,Set{NTuple{2,Int}}}(Set{NTuple{2,Int}})
    for ((c1, _), (c2, _)) in product(cube2n, cube2n)
        if c1 ≥ c2
            push!(sum2cubes[c1 + c2], (cube2n[c1], cube2n[c2]))
        end
    end

    taxied = collect((k, v) for (k, v) in sum2cubes if length(v) ≥ 2)
    return sort!(taxied, by = first)
end
taxied = findtaxinumbers(1200)

for (ith, (cube, set)) in zip(1:25, taxied[1:25])
    @printf "%2i: %7i = %s\n" ith cube join(set, ", ")
    # println(ith, ": ", cube, " = ", join(set, ", "))
end
println("...")
for (ith, (cube, set)) in zip(2000:2006, taxied[2000:2006])
    @printf "%-4i: %i = %s\n" ith cube join(set, ", ")
end

# version 2
function findtaxinumbers(nmax::Integer)
    cubes, crev = collect(x ^ 3 for x in 1:nmax), Dict{Int,Int}()
    for (x, x3) in enumerate(cubes)
        crev[x3] = x
    end
    sums = collect(x + y for x in cubes for y in cubes if y < x)
    sort!(sums)

    idx = 0
    for i in 2:(endof(sums) - 1)
        if sums[i-1] != sums[i] && sums[i] == sums[i+1]
            idx += 1
            if 25 < idx < 2000 || idx > 2006 continue end
            n, p = sums[i], NTuple{2,Int}[]
            for x in cubes
                n < 2x && break
                if haskey(crev, n - x)
                    push!(p, (crev[x], crev[n - x]))
                end
            end
            @printf "%4d: %10d" idx n
            for x in p @printf(" = %4d ^ 3 + %4d ^ 3", x...) end
            println()
        end
    end
end

findtaxinumbers(1200)


#!/usr/bin/lasso9

local(
	arguments	= $argv -> asarray,
	notesfile	= file('notes.txt')
)

#arguments -> removefirst

if(#arguments -> size) => {

	#notesfile -> openappend
	#notesfile -> dowithclose => {
		#notesfile -> writestring(date -> format(`YYYY-MM-dd HH:mm:SS`) + '\n')
		#notesfile -> writestring('\t' + #arguments -> join(', ') + '\n')
	}

else
	#notesfile -> exists ? stdout(#notesfile -> readstring)
}


filename = "NOTES.TXT"

if #arg == 0 then
    fp = io.open( filename, "r" )
    if fp ~= nil then
        print( fp:read( "*all*" ) )
        fp:close()
    end
else
    fp = io.open( filename, "a+" )

    fp:write( os.date( "%x %X\n" ) )

    fp:write( "\t" )
    for i = 1, #arg do
	fp:write( arg[i], " " )
    end
    fp:write( "\n" )

    fp:close()
end


If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"];
 Print[ReadString[str, EndOfFile]]; Close[str],
 str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]];
 WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]];
 Close[str]]


 function notes(varargin)
    % NOTES can be used for taking notes
    % usage:
    %    notes    displays the content of the file NOTES.TXT
    %    notes arg1 arg2 ...
    %             add the current date, time and arg# to NOTES.TXT
    %

    filename = 'NOTES.TXT';
    if nargin==0
	fid = fopen(filename,'rt');
	if fid<0, return; end;
	while ~feof(fid)
		fprintf('%s\n',fgetl(fid));
	end;
	fclose(fid);
    else
        fid = fopen(filename,'a+');
	if fid<0, error('cannot open %s\n',filename); end;
        fprintf(fid, '%s\n\t%s', datestr(now),varargin{1});
        for k=2:length(varargin)
            fprintf(fid, ', %s', varargin{k});
	end;
	fprintf(fid,'\n');
	fclose(fid);
    end;


// version 1.0.6

import java.util.PriorityQueue

class CubeSum(val x: Long, val y: Long) : Comparable<CubeSum> {
    val value: Long = x * x * x + y * y * y

    override fun toString() = String.format("%4d^3 + %3d^3", x, y)

    override fun compareTo(other: CubeSum) = value.compareTo(other.value)
}

class SumIterator : Iterator<CubeSum> {
    private val pq = PriorityQueue<CubeSum>()
    private var n = 0L

    override fun hasNext() = true

    override fun next(): CubeSum {
        while (pq.size == 0 || pq.peek().value >= n * n * n)
            pq.add(CubeSum(++n, 1))
        val s: CubeSum = pq.remove()
        if (s.x > s.y + 1) pq.add(CubeSum(s.x, s.y + 1))
        return s
    }
}

class TaxiIterator : Iterator<MutableList<CubeSum>> {
    private val sumIterator = SumIterator()
    private var last: CubeSum = sumIterator.next()

    override fun hasNext() = true

    override fun next(): MutableList<CubeSum> {
        var s: CubeSum = sumIterator.next()
        val train = mutableListOf<CubeSum>()
        while (s.value != last.value) {
            last = s
            s = sumIterator.next()
        }
        train.add(last)
        do {
            train.add(s)
            s = sumIterator.next()
        }
        while (s.value == last.value)
        last = s
        return train
    }
}

fun main(args: Array<String>) {
    val taxi = TaxiIterator()
    for (i in 1..2006) {
        val t = taxi.next()
        if (i in 26 until 2000) continue
        print(String.format("%4d: %10d", i, t[0].value))
        for (s in t) print("  = $s")
        println()
    }
}


:- module notes.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module list, time.

main(!IO) :-
    io.command_line_arguments(Args, !IO),
    ( if Args = [] then print_notes(!IO) else add_note(Args, !IO) ).

:- pred print_notes(io::di, io::uo) is det.

print_notes(!IO) :-
   io.open_input(notes_filename, InputRes, !IO),
   (
        InputRes = ok(Input),
        io.input_stream_foldl_io(Input, io.write_char, WriteRes, !IO),
        (
            WriteRes = ok
        ;
            WriteRes = error(WriteError),
            print_io_error(WriteError, !IO)
        ),
        io.close_input(Input, !IO)
   ;
        InputRes = error(_InputError)
   ).

:- pred add_note(list(string)::in, io::di, io::uo) is det.

add_note(Words, !IO) :-
   io.open_append(notes_filename, OutputRes, !IO),
   (
       OutputRes = ok(Output),
       time(Time, !IO),
       io.write_string(Output, ctime(Time), !IO),
       io.write_char(Output, '\t', !IO),
       io.write_list(Output, Words, " ", io.write_string, !IO),
       io.nl(Output, !IO),
       io.close_output(Output, !IO)
   ;
       OutputRes = error(OutputError),
       print_io_error(OutputError, !IO)
   ).

:- pred print_io_error(io.error::in, io::di, io::uo) is det.

print_io_error(Error, !IO) :-
   io.stderr_stream(Stderr, !IO),
   io.write_string(Stderr, io.error_message(Error), !IO),
   io.set_exit_status(1, !IO).

:- func notes_filename = string.

notes_filename = "NOTES.TXT".

:- end_module notes.


import os, times, strutils

if paramCount() == 0:
  try: stdout.write readFile("notes.txt")
  except IOError: discard
else:
  var f = open("notes.txt", fmAppend)
  f.writeLine getTime()
  f.writeLine "\t", commandLineParams().join(" ")
  f.close()


#! /usr/bin/env ocaml
#load "unix.cma"

let notes_file = "notes.txt"

let take_notes() =
  let gmt = Unix.gmtime (Unix.time()) in
  let date =
    Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d"
      (1900 + gmt.Unix.tm_year) (1 + gmt.Unix.tm_mon) gmt.Unix.tm_mday
      gmt.Unix.tm_hour gmt.Unix.tm_min gmt.Unix.tm_sec
  in
  let oc = open_out_gen [Open_append; Open_creat; Open_text] 0o644 notes_file in
  output_string oc (date ^ "\t");
  output_string oc (String.concat " " (List.tl(Array.to_list Sys.argv)));
  output_string oc "\n";
;;

let dump_notes() =
  if not(Sys.file_exists notes_file)
  then (prerr_endline "no local notes found"; exit 1);
  let ic = open_in notes_file in
  try while true do
    print_endline (input_line ic)
  done with End_of_file ->
    close_in ic

let () =
  if Array.length Sys.argv = 1
  then dump_notes()
  else take_notes()


sums, taxis, limit = {}, {}, 1200
for i = 1, limit do
  for j = 1, i-1 do
    sum = i^3 + j^3
    sums[sum] = sums[sum] or {}
    table.insert(sums[sum], i.."^3 + "..j.."^3")
  end
end
for k,v in pairs(sums) do
  if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end
end
table.sort(taxis, function(a,b) return a.sum<b.sum end)
for i=1,2006 do
  if i<=25 or i>=2000 or taxis[i].num==3 then
    print(string.format("%4d%s: %10d = %s", i, taxis[i].num==3 and "*" or " ", taxis[i].sum, taxis[i].terms))
  end
end
print("* n=3")


functor
import
   Application
   Open
   OS
   System
define
   fun {TimeStamp}
      N = {OS.localTime}
   in
      (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec
   end

   fun {Join X|Xr Sep}
      {FoldL Xr fun {$ Z X} Z#Sep#X end X}
   end

   case {Application.getArgs plain}
   of nil then
      try
         F = {New Open.file init(name:"notes.txt")}
      in
         {System.printInfo {F read(list:$ size:all)}}
         {F close}
      catch _ then skip end
   [] Args then
      F = {New Open.file init(name:"notes.txt" flags:[write text create append])}
   in
      {F write(vs:{TimeStamp}#"\n")}
      {F write(vs:"\t"#{Join Args " "}#"\n")}
      {F close}
   end
   {Application.exit 0}
end