import DateTime as dt;
import Algorithms as algo;
import Text as text;

class Calendar {
  _monthNames_ = none;
  _dayNames_ = none;
  constructor() {
    t = dt.now();
    _monthNames_ = algo.materialize( algo.map( algo.range( 1, 13 ), @[t]( m ) { dt.format( "%B", t.set_date( 1, m, 1 ) ); } ), tuple );
    _dayNames_ = algo.materialize( algo.map( algo.range( 1, 8 ), @[t]( d ) { dt.format( "%a", t.set_date( 1, 1, d ) )[:2]; } ), tuple );
  }
  print_year( year_, cols_ ) {
    t = dt.now();
    print( "{:^66d}\n".format( year_ ) );
    for ( rm : algo.range( 12 / cols_ ) ) {
      m = rm * cols_;
      print( text.repeat( "{:^22s}", cols_ ).format( _monthNames_[m:m + cols_]... ) + "\n" );
      day = [];
      daysInMonth = [];
      for ( mc : algo.range( cols_ ) ) {
        print( " {} {} {} {} {} {} {} ".format( _dayNames_... ) );
        t.set_date( year_, m + mc + 1, 1 );
        day.push( - t.get_day_of_week() + 1 );
        daysInMonth.push( t.get_days_in_month() );
      }
      print( "\n" );
      haveDay = true;
      while ( haveDay ) {
        haveDay = false;
        for ( mc : algo.range( cols_ ) ) {
          for ( d : algo.range( 7 ) ) {
            if ( ( day[mc] > 0 ) && ( day[mc] <= daysInMonth[mc] ) ) {
              print( " {:2d}".format( day[mc] ) );
              haveDay = true;
            } else {
              print( "   " );
            }
            day[mc] += 1;
          }
          print( " " );
        }
        print( "\n" );
      }
    }
  }
}

main( argv_ ) {
  cal = Calendar();
  cols = size( argv_ ) > 2 ? integer( argv_[2] ) : 3;
  if ( 12 % cols != 0 ) {
    cols = 3;
  }
  cal.print_year(
    size( argv_ ) > 1
      ? integer( argv_[1] )
      : dt.now().get_year(),
    cols
  );
}


procedure main(A)
   printCalendar(\A[1]|1969)
end

procedure printCalendar(year)          #: Print a 3 column x 80 char calendar
   cols := 3                                        # fixed width
   mons := []                                       # table of months
   "January February March April May June " ||
   "July August September October November December " ?
          while put(mons, tab(find(" "))) do move(1)

   write(center("[Snoopy Picture]",cols * 24 + 4))  # mandatory ..
   write(center(year,cols * 24 + 4), "\n")          # ... headers

   M := list(cols)                                  # coexpr container
   every  mon := 0 to 9 by cols do {                # go through months by cols
      writes("    ")
      every i := 1 to cols do {
         writes(center(mons[mon+i],24))             # header months
         M[i] := create CalendarFormatWeek(year,mon + i)  # formatting coexpr
         }
      write()
      every 1 to 7 do {                             # 1 to max rows
         every c := 1 to cols do {                  # for each column
            writes("    ")
            every 1 to 7 do writes(right(@M[c],3))  # each row day element
            }
         write()
         }
      }
   return
end

link datetime

procedure CalendarFormatWeek(year,m)                #: Format Week for Calendar
   static D
   initial D := [31,28,31,30,31,30,31,31,30,31,30,31]

   every suspend "Su"|"Mo"|"Tu"|"We"|"Th"|"Fr"|"Sa"          # header
   every 1 to (d := (julian(m,1,year)+1)%7) do suspend ""    # lead day alignment
   every suspend 1 to D[m] do d +:= 1                        # days
   if m = 2 & IsLeapYear(year) then suspend (d +:= 1, 29)    # LY adjustment
   every d to (6*7) do suspend ""                            # trailer alignment
end


require 'dates format'               NB. J6.x
require 'dates general/misc/format'  NB. J7.x
calBody=: (1 1 }. _1 _1 }. ":)@([email protected](<[email protected]%&22)@[ ]\ [email protected]])
calTitle=: (<: - 22&|)@[ center '[Insert Snoopy here]' , '' ,:~ ":@]
formatCalendar=: calTitle , calBody


import java.text.*;
import java.util.*;

public class CalendarTask {

    public static void main(String[] args) {
        printCalendar(1969, 3);
    }

    static void printCalendar(int year, int nCols) {
        if (nCols < 1 || nCols > 12)
            throw new IllegalArgumentException("Illegal column width.");

        Calendar date = new GregorianCalendar(year, 0, 1);

        int nRows = (int) Math.ceil(12.0 / nCols);
        int offs = date.get(Calendar.DAY_OF_WEEK) - 1;
        int w = nCols * 24;

        String[] monthNames = new DateFormatSymbols(Locale.US).getMonths();

        String[][] mons = new String[12][8];
        for (int m = 0; m < 12; m++) {

            String name = monthNames[m];
            int len = 11 + name.length() / 2;
            String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len);

            mons[m][0] = String.format(format, name, "");
            mons[m][1] = " Su Mo Tu We Th Fr Sa";
            int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH);

            for (int d = 1; d < 43; d++) {
                boolean isDay = d > offs && d <= offs + dim;
                String entry = isDay ? String.format(" %2s", d - offs) : "   ";
                if (d % 7 == 1)
                    mons[m][2 + (d - 1) / 7] = entry;
                else
                    mons[m][2 + (d - 1) / 7] += entry;
            }
            offs = (offs + dim) % 7;
            date.add(Calendar.MONTH, 1);
        }

        System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]");
        System.out.printf("%" + (w / 2 + 4) + "s%n%n", year);

        for (int r = 0; r < nRows; r++) {
            for (int i = 0; i < 8; i++) {
                for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++)
                    System.out.printf("   %s", mons[c][i]);
                System.out.println();
            }
            System.out.println();
        }
    }
}


/**
 * Given a width, return a function that takes a string, and
 * pads it at both ends to the given width
 * @param {number} width
 * @returns {function(string): string}
 */
const printCenter = width =>
    s => s.padStart(width / 2 + s.length / 2, ' ').padEnd(width);

/**
 * Given an locale string and options, return a function that takes a date
 * object, and retrurns the date formatted to the locale and options.
 * @param {string} locale
 * @param {DateTimeFormatOptions} options
 * @returns {function(Date): string}
 */
const localeName = (locale, options) => {
  const formatter = new Intl.DateTimeFormat(locale, options);
  return date => formatter.format(date);
};

/**
 * Increment the date by number.
 * @param {Date} date
 * @param {number} inc
 * @returns {Date}
 */
const addDay = (date, inc = 1) => {
  const res = new Date(date.valueOf());
  res.setDate(date.getDate() + inc);
  return res;
}

/**
 * Given a date, build a string of the week, and return it along with
 * the mutated date object.
 * @param {Date} date
 * @returns {[boolean, Date, string]}
 */
const makeWeek = date => {
  const month = date.getMonth();
  let [wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
  const line = Array(7).fill('  ').map((e, i) => {
    if (i === wdi && m === month) {
      const result = (md + '').padStart(2, ' ');
      date = addDay(date);
      [wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
      return result;
    } else {
      return e;
    }
  }).join(' ');
  return [month !== m, date, line];
}

/**
 * Print a nicely formatted calender for the given year in the given locale.
 * @param {number} year The required year of the calender
 * @param {string} locale The locale string. Defaults to US English.
 * @param {number} cols The number of columns for the months. Defaults to 3.
 * @param {number} coll_space The space between the columns. Defaults to 5.
 */
const cal = (year, locale = 'en-US', cols = 3, coll_space = 5) => {
  const MONTH_LINES = 9;  // Number of lines that make up a month.
  const MONTH_COL_WIDTH = 20;  // Character width of a month
  const COL_SPACE = ' '.padStart(coll_space);
  const FULL_WIDTH = MONTH_COL_WIDTH * cols + coll_space * (cols - 1);

  const collArr = Array(cols).fill('');
  const monthName = localeName(locale, {month: 'long'});
  const weekDayShort = localeName(locale, {weekday: 'short'});
  const monthCenter = printCenter(MONTH_COL_WIDTH);
  const pageCenter = printCenter(FULL_WIDTH);

  // Get the weekday in the given locale.
  const sun = new Date(Date.UTC(2017, 0, 1)); // A sunday
  const weekdays = Array(7).fill('').map((e, i) =>
      weekDayShort(addDay(sun, i)).padStart(2, ' ').substring(0, 2)).join(' ');

  // The start date.
  let date = new Date(Date.UTC(year, 0, 1, 0, 0, 0));
  let nextMonth = true;
  let line = '';
  const fullYear = date.getUTCFullYear();

  // The array into which each of the lines are populated.
  const accumulate = [];

  // Populate the month table heading and columns.
  const preAmble = date => {
    accumulate.push(monthCenter(' '))
    accumulate.push(monthCenter(monthName(date)));
    accumulate.push(weekdays);
  };

  // Accumulate the week lines for the year.
  while (date.getUTCFullYear() === fullYear) {
    if (nextMonth) {
      if (accumulate.length % MONTH_LINES !== 0) {
        accumulate.push(monthCenter(' '))
      }
      preAmble(date);
    }
    [nextMonth, date, line] = makeWeek(date);
    accumulate.push(line);
  }

  // Print the calendar.
  console.log(pageCenter(String.fromCodePoint(0x1F436)));
  console.log(pageCenter(`--- ${fullYear} ---`));
  accumulate.reduce((p, e, i) => {
    if (!p.includes(i)) {
      const indexes = collArr.map((e, ci) => i + ci * MONTH_LINES);
      console.log(indexes.map(e => accumulate[e]).join(COL_SPACE));
      p.push(...indexes);
    }
    return p;
  }, []);
};

cal(1969, 'en-US', 3);


using Dates

const pagesizes = Dict( "lpr" => [132, 66], "tn3270" => [80, 43])

pagefit(prn) = haskey(pagesizes, prn) ?
    [div(pagesizes[prn][1], 22), div(pagesizes[prn][2], 12)] : [1, 1]
pagecols(prn) = haskey(pagesizes, prn) ? pagesizes[prn][1] : 20

function centerobject(x, cols)
    content = string(x)
    rpad(lpad(content, div(cols + length(content), 2)), cols)
end

function ljustlines(x, cols)
    arr = Vector{String}()
    for s in split(x, "\n")
        push!(arr, rpad(s, cols)[1:cols])
    end
    join(arr, "\n")
end

function formatmonth(yr, mo)
    dt = Date("$yr-$mo-01")
    dayofweekfirst = dayofweek(dt)
    numweeklines = 1
    str = centerobject(monthname(dt), 20) * "\nMo Tu We Th Fr Sa Su\n"
    str *= " " ^ (3 * (dayofweekfirst - 1)) * lpad(string(1), 2)
    for i = 2:daysinmonth(dt)
        if (i + dayofweekfirst + 5) % 7 == 0
            str *= "\n" * lpad(i, 2)
            numweeklines += 1
        else
            str *= lpad(string(i), 3)
        end
    end
    str *= numweeklines < 6 ? "\n\n\n" : "\n\n"
    ljustlines(str, 20)
end

function formatyear(displayyear, printertype)
    calmonths = [formatmonth(displayyear, mo) for mo in 1:12]
    columns = pagecols(printertype)
    monthsperline = pagefit(printertype)[1]
    joinspaces = max( (monthsperline > 1) ?
        div(columns - monthsperline * 20, monthsperline - 1) : 1, 1)
    str = "\n" * centerobject(displayyear, columns) * "\n"
    monthcal = [split(formatmonth(displayyear, i), "\n") for i in 1:12]
    for i in 1:monthsperline:length(calmonths) - 1
        for j in 1:length(monthcal[1])
            monthlines = map(x->monthcal[x][j], i:i + monthsperline - 1)
            str *= rpad(join(monthlines, " " ^ joinspaces), columns) * "\n"
        end
        str *= "\n"
    end
    str
end

function lineprintcalendar(years)
    for year in years, printer in keys(pagesizes)
        println(formatyear(year, printer))
    end
end

lineprintcalendar(1969)


import java.io.PrintStream
import java.text.DateFormatSymbols
import java.text.MessageFormat
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Locale

internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) {
    if (nCols < 1 || nCols > 12)
        throw IllegalArgumentException("Illegal column width.")
    val w = nCols * 24
    val nRows = Math.ceil(12.0 / nCols).toInt()

    val date = GregorianCalendar(year, 0, 1)
    var offs = date.get(Calendar.DAY_OF_WEEK) - 1

    val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ")
    val mons = Array(12) { Array(8) { "" } }
    DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name ->
        val len = 11 + name.length / 2
        val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len)
        mons[m][0] = String.format(format, name, "")
        mons[m][1] = days
        val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH)
        for (d in 1..42) {
            val isDay = d > offs && d <= offs + dim
            val entry = if (isDay) String.format(" %2s", d - offs) else "   "
            if (d % 7 == 1)
                mons[m][2 + (d - 1) / 7] = entry
            else
                mons[m][2 + (d - 1) / 7] += entry
        }
        offs = (offs + dim) % 7
        date.add(Calendar.MONTH, 1)
    }

    printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]")
    printf("%" + (w / 2 + 4) + "s%n%n", year)

    for (r in 0 until nRows) {
        for (i in 0..7) {
            var c = r * nCols
            while (c < (r + 1) * nCols && c < 12) {
                printf("   %s", mons[c][i])
                c++
            }
            println()
        }
        println()
    }
}

fun main(args: Array<String>) {
    System.out.printCalendar(1969, 3, Locale.US)
}


rem Adapted from LB examples included with software
[start]
    prompt "Enter year(yyyy)?";year
    if year<1900 then notice "1900 or later":goto [start]
    ax=1:gx=8:ay=3:gy=10
    locate 52,1:print year
    for mr = 0 to 3
        for mc = 0 to 2
            mt=mt+1
            aDate$ = str$(mt)+"/01/"+str$(year)
            px = ax+mc*gx
            py = ay+mr*gy
            gosub [printout]
        next mc
    next mr
    gosub [snoopy]
end

[printout]
    locate 4*px-3+int((30-len(monthname$(aDate$)))/2),py
    print monthname$(aDate$)
    FirstDay=date$(word$(aDate$,1,"/")+"/1/"+word$(aDate$,3,"/"))
    LastDay$=date$(date$(word$(date$(FirstDay+32),1,"/")+"/1/"+word$(date$(FirstDay+32),3,"/"))-1)
    dow=val(word$("3 4 5 x 6 7 x 1 2",int((FirstDay/7-int(FirstDay/7))*10)+1))
    locate px*4-3, py+1
    print " Su Mo  Tu  We  Th  Fr  Sa"
    for i=1 to val(mid$(LastDay$,4,2))
        y=int((i+dow-2)/7)
        x=px+(i+dow-2)-y*7
        x=4*x
        locate x-4,py+y+2
        print using("###",i)
    next i
return

[snoopy]
    locate ax, ay+4*gy
    print space$(4*gx);"           ,-~~-.___."
    print space$(4*gx);"          / ()=(()   \"
    print space$(4*gx);"         (   (        0"
    print space$(4*gx);"          \._\, ,----'"
    print space$(4*gx);"     ##XXXxxxxxxx"
    print space$(4*gx);"            /  ---'~;"
    print space$(4*gx);"           /    /~|-"
    print space$(4*gx);"    _____=(   ~~  |______ "
    print space$(4*gx);"   /_____________________\ "
    print space$(4*gx);"  /_______________________\"
    print space$(4*gx);" /_________________________\"
    print space$(4*gx);"/___________________________\"
    print space$(4*gx);"   |____________________|"
    print space$(4*gx);"   |____________________|"
    print space$(4*gx);"   |____________________|"
    print space$(4*gx);"   |                    |"
return

function monthname$(aDate$)
    month=val(aDate$)
    monthname$=word$("January February March April May June July August September October November December",month)
end function


----------------------------------------
-- @desc      Class "Calendar"
-- @file      parent script "Calendar"
----------------------------------------
property _months
property _weekdayStr
property _refDateObj
property _year
property _calStr

on new (me)
  me._months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  me._weekdayStr = "Mo Tu We Th Fr Sa Su"
  me._refDateObj = date(1905,1,2)
  return me
end

on make (me, year)
  me._year = year
  me._calStr = ""
  -- prefill cal string with spaces
  emptyLine = bytearray(68,32).readRawString(68)&RETURN
  repeat with i = 1 to 38
    put emptyLine after _calStr
  end repeat
  me._write (string(year), 32, 1)
  repeat with i = 1 to 12
    me._writeMonth(i)
  end repeat
  return me._calStr
end

on _writeMonth (me, monthNum)
  xOffset = (monthNum-1) mod 3 * 24
  yOffset = (monthNum-1)/3 * 9 + 2
  pre = (20 - me._months[monthNum].length)/2
  me._write(me._months[monthNum], 1+xOffset+pre, 1+yOffset)
  me._write(me._weekdayStr, 1+xOffset, 2+yOffset)
  y = 3
  x = ((date(me._year, monthNum, 1) - me._refDateObj) mod 7)+1
  repeat with i = 1 to 31
    if date(me._year, monthNum, i).month<>monthNum then exit repeat
    dayStr = string(i)
    if i<10 then put " " before dayStr
    me._write(dayStr, x*3-2+xOffset, y+yOffset)
    if x=7 then
      y = y+1
      x = 1
    else
      x = x+1
    end if
  end repeat
end

on _write (me, str, x, y)
  put str into char x to x+str.length-1 of line y of _calStr
end


function print_cal(year)
  local months={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
                "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}
  local daysTitle="MO TU WE TH FR SA SU"
  local daysPerMonth={31,28,31,30,31,30,31,31,30,31,30,31}
  local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
  if year%4==0 and year%100~=0 or year%400==0 then
    daysPerMonth[2]=29
  end
  local sep=5
  local monthwidth=daysTitle:len()
  local calwidth=3*monthwidth+2*sep

  function center(str, width)
    local fill1=math.floor((width-str:len())/2)
    local fill2=width-str:len()-fill1
    return string.rep(" ",fill1)..str..string.rep(" ",fill2)
  end

  function makeMonth(name, skip,days)
    local cal={
      center(name,monthwidth),
      daysTitle
    }
    local curday=1-skip
    while #cal<9 do
      line={}
      for i=1,7 do
        if curday<1 or curday>days then
          line[i]="  "
        else
          line[i]=string.format("%2d",curday)
        end
        curday=curday+1
      end
      cal[#cal+1]=table.concat(line," ")
    end
    return cal
  end

  local calendar={}
  for i,month in ipairs(months) do
    local dpm=daysPerMonth[i]
    calendar[i]=makeMonth(month, startday, dpm)
    startday=(startday+dpm)%7
  end

  print(center("[SNOOPY]",calwidth),"\n")
  print(center("--- "..year.." ---",calwidth),"\n")

  for q=0,3 do
    for l=1,9 do
      line={}
      for m=1,3 do
        line[m]=calendar[q*3+m][l]
      end
      print(table.concat(line,string.rep(" ",sep)))
    end
  end
end

print_cal(1969)


Module Calendar (Year, LocaleId) {
      Function GetMax(Year, Month) {
            a=date(str$(Year)+"-"+str$(Month)+"-1")
            max=32
            do {
                  max--
                  m=val(str$(cdate(a,0,0,max), "m"))
            } until m=Month
             =max+1
      }
      Function SkipMo(Year, Month) {
            a=date(str$(Year)+"-"+str$(Month)+"-1")
            =(val(str$(a, "w"))-8) mod 7 +7
      }
      Function Title$(a$) {
            =Ucase$(left$(a$,1))+Lcase$(Mid$(a$, 2))
      }
      locale LocaleId
      Cursor 0,Height-1  ' last line, so each new line scroll all lines up
      Print Over $(2), Year
      Print
      For j=0 to 3 {
            Print
            For i=1 to 3 {
                  Month=i+j*3
                  Print  Part @((i-1)*29-1), $(2,22), Title$(Ucase$(locale$(55+Month)))
            }
            Print
            Dim Skip(1 to 3), Count(1 to 3), D(1 to 3)=1
            For i=1 to 3 {
                  Month=i+j*3
                  if i>1 Then Print String$(" ",8);
                  For k=42 to 48 :Print Title$(Ucase$(Left$(locale$(k),2)));" ";:Next k
                  Skip(i)=SkipMo(Year, Month)
                  Count(i)=GetMax(Year, Month)
            }
            Print
            For i=1 to 3 {
                      if i>1 Then Print String$(" ",8);
                      For k=1 to 7 {
                        skip(i)--
                        if  skip(i)>0 Then Print "   "; :continue
                        Count(i)--
                        Print format$("{0::-2} ", d(i));
                        d(i)++
                  }
            }
            Print
            Print @(0)
            For m=1 to 5 {
                  For i=1 to 3 {
                        if i>1 Then Print String$(" ",8);
                        For k=1 to 7 {
                              Count(i)--
                              if Count(i)<0 Then Print "   "; : Continue
                              Print format$("{0::-2} ", d(i));
                              d(i)++
                        }
                  }
            Print
            }
      }
}
Form 80,43
Calendar 1969, 1033 ' English
k=Key$ ' wait key
Calendar 2018, 1032  ' Greek


DataGrid[
  rowHeights:{__Integer},
  colWidths:{__Integer},
  spacings:{_Integer,_Integer},
  borderWidths:{{_Integer,_Integer},{_Integer,_Integer}},
  options_Association,
  data:{__List?MatrixQ}]:=
  With[
    (*Need to make sure we have sensible defaults for the decoration options.*)
    {alignment=Lookup[options,"alignment",{0,0}],
     background=Lookup[options,"background"," "],
     dividers=Lookup[options,"dividers",{" "," "," "}],
     border=Lookup[options,"border"," "],
     dims={Length[rowHeights],Length[colWidths]}},
    (*Pad the data so that it will fit into the specified rectangle (list of lists).*)
    With[{augmentedData=PadRight[data,[email protected]@dims,{{{background}}}]},
      (*Create a matrix of dimensions based on desired rectangle. Once we have a matrix of cells we can "thread" these two matrices and use that data to coerce each cell into its final dimensions.*)
      With[{cellDims=ArrayReshape[Outer[List,rowHeights,colWidths],{[email protected]@dims,2}]},
        (*MatrixAlign, defined below, rescales and aligns each cell's data.*)
        With[{undecoratedGrid=Partition[MapThread[MatrixAlign[alignment,#1,background][#2]&, {cellDims,augmentedData}],dims[[2]]]},
          (*Add the spacing to each row.*)
          With[{dividedRows=MapThread[Transpose[Riffle[#2,{ConstantArray[dividers[[2]],{#1,spacings[[2]]}]},{2,-2,2}]]&, {rowHeights,undecoratedGrid}]},
            (*Add the spacing between rows.*)
            With[{dividedColumn=Riffle[dividedRows,{Transpose[Riffle[ConstantArray[dividers[[1]],{spacings[[1]],#}]&/@colWidths,{ConstantArray[dividers[[3]],spacings]},{2,-2,2}]]},{2,-2,2}]},
              (*Assemble all cell rows into actual character rows. We now have one large matrix.*)
              With[{dividedGrid=Catenate[Map[Flatten,dividedColumn,{2}]]},
                (*Add borders.*)
                ArrayPad[dividedGrid,borderWidths,border]]]]]]]];

DataGrid[dims:{_Integer,_Integer},spacings_,borderWidths_,options_,data:{__List?MatrixQ}]:=
(*Calculate the max height for each row and max width for each column, and then just call the previous DataGrid function above.*)
  With[
    {[email protected][Max[Part[#,All,All,1]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{1,dims[[2]]}],
     [email protected][Max[Part[#,All,All,2]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{dims[[1]],1}]},
    DataGrid[rowHeights,colWidths,spacings,borderWidths,options,data]];

(*This could probably be simplified, but I like having all of the aligment options explicit and separate for testability.*)
MatrixAlign[{-1,-1},dims_,pad_]:=PadRight[#,dims,pad]&;
MatrixAlign[{-1,0},dims_,pad_]:=PadRight[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{-1,1},dims_,pad_]:=PadRight[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,-1},dims_,pad_]:=CenterArray[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{0,0},dims_,pad_]:=CenterArray[#,dims,pad]&;
MatrixAlign[{0,1},dims_,pad_]:=CenterArray[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,-1},dims_,pad_]:=PadLeft[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,0},dims_,pad_]:=PadLeft[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&;
MatrixAlign[{1,1},dims_,pad_]:=PadLeft[#,dims,pad]&;

(*While the grid functions make no assumptions about the format of the data, we will be using them with string/character data, and we will eventually want to output a calendar as a single large string. AsString gives us a standard method for transforming a matrix of characters into a string with rows delimited by newlines.*)
AsString[matrix_List?MatrixQ]:=StringRiffle[matrix,"\n",""];


(*Mathematica makes it easy to get month names and day names for several standard calendars.*)
MonthNames[]:=MonthNames["Gregorian"];
MonthNames[calType_]:=Lookup[CalendarData[calType,"PropertyAssociation"],"MonthNames"];

WeekdayNames[]:=WeekdayNames["Gregorian"];
WeekdayNames[calType_]:=Lookup[CalendarData[calType,"PropertyAssociation"],"DayNames"];

(*Since month boundaries don't align with week boundaries on most calendars, we need to pad month data with empty cells. I was tempted to create a function that would generate offsets for a given year on a given calendar, but even that required too many decisions on the part of the calendar maker to be feasible. So, I removed all of the calendar semantics. If you provide the fixed small group length (week length), the initial offset, and the list of the large group lengths (month lengths), this function will give you the offsets you need for each large group (month).*)
Offsets[groupLength_,firstOffset_,lengths_List]:=FoldPairList[{#1,Mod[#1+#2,groupLength]}&,firstOffset,lengths];


WidestFitDimensions[
  targetWidth_Integer,
  columnSpacings_Integer,
  leftRightBorderWidths:{_Integer,_Integer},
  data:{__List?MatrixQ}]:=
  With[
    {widths=Last/@Dimensions/@data,
     fullWidthOfRow=Total[ArrayPad[Riffle[#,columnSpacings],leftRightBorderWidths,1]]&},
    With[
      {fullWidthOfGrid=Max[fullWidthOfRow/@#]&},
      With[
        {isTooLarge=(targetWidth<fullWidthOfGrid[#])&},
        With[
          {bestFitGrid=
             NestWhile[Partition[widths,[email protected]@#,[email protected]@#,{1,1},0]&,
               {widths},isTooLarge[#]&,1,[email protected]]},
          <|"dimensions"->[email protected],"width"->[email protected]|>]]]];


import times
import strformat

proc printCalendar(year, nCols: int) =
  var rows = 12 div nCols
  var date = initDateTime(1, mJan, year, 0, 0, 0, utc())
  if rows mod nCols != 0:
    inc rows
  var offs = getDayOfWeek(date.monthday, date.month, date.year).int
  var mons: array[12, array[8, string]]
  for m in 0..11:
    mons[m][0] = &"{$date.month:^21}"
    mons[m][1] = " Su Mo Tu We Th Fr Sa"
    var dim = getDaysInMonth(date.month, date.year)
    for d in 1..42:
      var day = d > offs and d <= offs + dim
      var str = if day: &" {d-offs:2}" else: "   "
      mons[m][2 + (d - 1) div 7] &= str
    offs = (offs + dim) mod 7
    date = date + months(1)
  var snoopyString, yearString: string
  formatValue(snoopyString, "[Snoopy Picture]", "^" & $(nCols * 24 + 4))
  formatValue(yearString, $year, "^" & $(nCols * 24 + 4))
  echo snoopyString, "\n" , yearString, "\n"
  for r in 0..<rows:
    var s: array[8, string]
    for c in 0..<nCols:
      if r * nCols + c > 11:
        break
      for i, line in mons[r * nCols + c]:
        s[i] &= &"   {line}"
    for line in s:
      if line == "":
        break
      echo line
    echo ""

printCalendar(1969, 3)


#load "unix.cma"

let lang = "en"  (* language: English *)

let usage () =
  Printf.printf "Usage:\n%s\n" Sys.argv.(0)

let month_pattern =
  [
    [  0;  4;  8 ];
    [  1;  5;  9 ];
    [  2;  6; 10 ];
    [  3;  7; 11 ];

    (*
    [  0;  1;  2;  3;  4;  5 ];
    [  6;  7;  8;  9; 10; 11 ];

    [  0;  1;  2;  3 ];
    [  4;  5;  6;  7 ];
    [  8;  9; 10; 11 ];
    *)
  ]

let month_langs = [
  "en", [|
    "January"; "February"; "March"; "April";
    "May"; "June"; "July"; "August"; "September";
    "October"; "November"; "December";
  |];
  "fr", [|
    "janvier"; "février"; "mars"; "avril"; "mai";
    "juin"; "juillet"; "août"; "septembre";
    "octobre"; "novembre"; "décembre";
  |];
]

let days_lang = [
  "en", [| "Monday"; "Tuesday"; "Wednesday";
    "Thursday"; "Friday"; "Saturday"; "Sunday" |];
  "fr", [| "lundi"; "mardi"; "mercredi";
    "jeudi"; "vendredi"; "samedi"; "dimanche" |];
]

let titles_lang = [
  "en", "( Snoopy's best pic )";
  "fr", "( Le meilleur profil de Snoopy )";
]

let days = List.assoc lang days_lang
let month = List.assoc lang month_langs
let title = List.assoc lang titles_lang

let monday_first = 6, [| 0; 1; 2; 3; 4; 5; 6 |]
let sunday_first = 0, [| 6; 0; 1; 2; 3; 4; 5 |]

let off, days_order = sunday_first
let off, days_order = monday_first

let shorten n s =
  let len = String.length s in
  if n >= len then s else
    let n = if s.[n-1] = '\xC3' then n+1 else n in
    if n >= len then s else
      (String.sub s 0 n)

let pad size c s =
  let len = String.length s in
  let n1 = (size - len) / 2 in
  let n2 = size - len - n1 in
  String.make n1 c ^ s ^
  String.make n2 c

let days = Array.map (shorten 2) days

let indices ofs =
  (ofs / 7, ofs mod 7)

let t_same t1 t2 =
  ( t1.Unix.tm_year = t2.Unix.tm_year &&
    t1.Unix.tm_mon  = t2.Unix.tm_mon &&
    t1.Unix.tm_mday = t2.Unix.tm_mday )

let current_year () =
  let t = Unix.localtime (Unix.time ()) in
  (t.Unix.tm_year + 1900)

let make_month t year month =
  let empty_day = 0 in
  let m = Array.make_matrix 6 7 empty_day in
  let ofs = ref 0 in
  for day = 1 to 31 do
    let tm =
      { t with
        Unix.tm_year = year - 1900;
        Unix.tm_mon = month;
        Unix.tm_mday = day;
      }
    in
    let _, this = Unix.mktime tm in
    if !ofs = 0 then ofs := (this.Unix.tm_wday + off) mod 7;
    if t_same this tm then
      let i, j = indices !ofs in
      m.(i).(j) <- day;
    incr ofs;
  done;
  (m)

let cal ~year =
  let empty = [| [| |] |] in
  let months = Array.make 12 empty in
  let t = Unix.gmtime 0.0 in
  for mon = 0 to 11 do
    months.(mon) <- make_month t year mon;
  done;
  (months)

let print_month_label mp =
  List.iter (fun i ->
    let mon = pad 20 ' ' month.(i) in
    Printf.printf " %s " mon
  ) mp;
  print_newline ()

let print_day_label mp =
  List.iter (fun _ ->
    Array.iter (fun i ->
      Printf.printf " %s" days.(i)
    ) days_order
    ; print_string " "
  ) mp;
  print_newline ()

let print_mon m mp =
  print_month_label mp;
  print_day_label mp;
  for w = 0 to pred 6 do
    print_string begin
      String.concat " " begin
        List.map (fun i ->
          let b = Buffer.create 132 in
          for d = 0 to pred 7 do
            match m.(i).(w).(d) with
            | 0 -> Buffer.add_string b "   "
            | d -> Printf.kprintf (Buffer.add_string b) " %2d" d
          done;
          (Buffer.contents b)
        ) mp
      end
    end
    ; print_string "\n"
  done

let print_cal ~y:m =
  List.iter (fun mon_row ->
    print_mon m mon_row
  ) month_pattern

let print_header lbl =
  let n = List.length (List.hd month_pattern) in
  let year_lbl = pad (23*n-7) ' ' lbl in
  Printf.printf " %s\n" year_lbl

let print_calendar ~year =
  print_header title;
  print_header (string_of_int year);
  print_cal (cal ~year)

let () =
  let args = List.tl (Array.to_list Sys.argv) in
  match args with
  | [] ->
      let year = current_year () in
      print_calendar ~year

  | ["--year"; _year] ->
      let year = int_of_string _year in
      print_calendar ~year

  | _ ->
      usage ()


#!/usr/bin/perl -l

use strict; # https://rosettacode.org/wiki/Calendar
use warnings;
use Time::Local;

my $year = shift // 1969;
my $width = shift // 80;
my $columns = int +($width + 2) / 22 or die "width too short at $width";
print map { center($_, $width), "\n" } '<reserved for snoopy>', $year;
my @months = qw( January February March April May June
  July August September October November December );
my @days = qw( 31 28 31 30 31 30 31 31 30 31 30 31 );
(gmtime 86400 + timegm 1,1,1,28,1,$year)[3] == 29 and $days[1]++;
my @blocks = map # block per month
  {
  my $m = center($months[$_], 20) . "\nSu Mo Tu We Th Fr Sa\n" .
    "00 00 00 00 00 00 00\n" x 6;
  $m =~ s/00/  / for 1 .. (gmtime timegm 1,1,1,1,$_,$year )[6]; # day of week
  $m =~ s/00/ center($_, 2) /e for 1 .. $days[$_];
  $m =~ s/00/  /g;
  [ split /\n/, $m ]
  } 0 .. 11;
while( my @row = splice @blocks, 0, $columns ) # print by rows of months
  {
  print center(join('  ', map shift @$_, @row), $width) for 1 .. @{$row[0]};
  }

sub center
  {
  my ($string, $w) = @_;
  sprintf "%${w}s", $string . ' ' x ($w - length($string) >> 1);
  }


with javascript_semantics
constant year = 1969

include builtins\timedate.e

function centre(string s, integer width)
    integer gap = width-length(s),
            left = floor(gap/2),
            right = gap-left
    return repeat(' ',left) & s & repeat(' ',right)
end function

function one_month(integer year, integer month, bool sun_to_sat)
    string weekdays = iff(sun_to_sat?"Su Mo Tu We Th Fr Sa"
                                    :"Mo Tu We Th Fr Sa Su"),
           line = repeat(' ',20)
    sequence ldm = adjust_timedate(iff(month=12?{year+1,1,1,0,0,0,0,0}
                                               :{year,month+1,1,0,0,0,0,0}),
                                   timedelta(days:=-1)),
             res = {centre(format_timedate(ldm,"Mmmm"),20),weekdays}
    integer dow = day_of_week(year,month,1)
    if sun_to_sat then dow = remainder(dow,7)+1 end if
    integer lastday = ldm[DT_DAY],
            p = dow*3-2
    for d=1 to lastday do
        line[p..p+1] = sprintf("%2d",d)
        p += 3
        if dow=7 or d=lastday then
            res = append(res,line)
            line = repeat(' ',20)
            dow = 1
            p = 1
        else
            dow += 1
        end if
    end for
    return res
end function

procedure print_calendar(integer year, width, bool sun_to_sat=false)
    sequence months = repeat(0,12)
    integer wide = floor((width+2)/22)
    printf(1,centre("[Spot Reserved For Snoopy]",width)&"\n")
    printf(1,centre(sprintf("%d",year),width)&"\n")
    for month=1 to 12 do
        months[month] = one_month(year,month,sun_to_sat)
    end for
    for month=1 to 12 by wide do
        for k=1 to 9 do -- (more than enough)
            integer any = 0
            string line = ""
            for j=0 to wide-1 do
                if length(line) then
                    line &= "  "
                end if
                if k>length(months[month+j]) then
                    line &= repeat(' ',20)
                else
                    line &= months[month+j][k]
                    any = 1
                end if
            end for
            if any=0 then exit end if
            printf(1,centre(line,width)&"\n")
        end for
    end for
end procedure

print_calendar(year,80)
printf(1,join(repeat("1234567890",8),"")&"\n")
print_calendar(year,132,true)
printf(1,join(repeat("1234567890",13),"")&"12\n")


include ..\Utilitys.pmt

32 var space

def bksp    /# -- backspace #/
    8 tochar print
enddef

def floor
    .5 + int
enddef

def center
    tostr align
enddef

def startday    /# year -- day of the week of january 1 #/
    1 - >ps
    tps 365 * tps 4 / floor + tps 100 / floor - ps> 400 / floor + 7 mod
enddef

def bisiesto? /# year -- true if leap #/
    dup 4 mod not over 100 mod and swap 400 mod not or
enddef

def snoopy
    0 tcolor 15 bcolor
    "snoopy.txt" "r" fopen var f

    true
    while
        f fgets
        dup -1 == if
            drop
            f fclose
            false
        else
            print
            true
        endif
    endwhile

    15 tcolor 0 bcolor
enddef

( "JANUARY" "FEBRUARY" "MARCH" "APRIL" "MAY" "JUNE" "JULY" "AUGUST" "SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER" ) var months
"MO TU WE TH FR SA SU" var daysTitle
( 31 28 31 30 31 30 31 31 30 31 30 31 ) var daysPerMonth
daysTitle len nip var monthwidth

def makeMonth var days >ps
    monthwidth center daysTitle 2 tolist

    1 ps> - 1 + >ps

    true
    while
      ( )
      7 for drop
        tps 1 < tps days > or if
            " "
        else
            tps
        endif
        2 align 0 put
        ps> 1 + >ps
      endfor
      0 put
      len 8 <
    endwhile
    ps> drop
enddef

def print_cal >ps
    tps bisiesto? if daysPerMonth 29 2 set var daysPerMonth endif
    5 space over repeat var spaces

    snoopy

    3 monthwidth * swap 2 * +
    "--- " tps tostr " ---" chain chain swap center ? nl

    ps> startday var inicio

    ( )

    12 for >ps
        months tps get nip inicio
        daysPerMonth ps> get nip >ps
        tps makeMonth 0 put
        inicio ps> + 7 mod var inicio
    endfor

    ( 0 3 ) for var i
        8 for var k
            3 for var j
                i 3 * j + get
                k get
                list? if
                    10 tcolor
                    len for
                        get print " " print
                    endfor
                    drop
                    bksp
                else
                    11 tcolor
                    print
                endif
                drop
                spaces print
            endfor
            nl
        endfor
        nl
    endfor
    drop
enddef

2020 print_cal


FALSE    DC     X'00'
TRUE     DC     X'FF'


(de cal (Year)
   (prinl "====== " Year " ======")
   (for Dat (range (date Year 1 1) (date Year 12 31))
      (let D (date Dat)
         (tab (3 3 4 8)
            (when (= 1 (caddr D))
               (get *Mon (cadr D)) )
            (caddr D)
            (day Dat *Day)
            (when (=0 (% (inc Dat) 7))
               (pack "Week " (week Dat)) ) ) ) ) )

(cal 1969)


#!/bin/env pike

int main(int argc, array(string) argv)
{
    object cal = Calendar;
    object year;
    string region = "us";

    array date = argv[1..];
    if (sizeof(date) && objectp(Calendar[date[0]]) && Calendar[date[0]]->Day)
    {
        cal = Calendar[date[0]];
        date = Array.shift(date)[1];
    }

    if (sizeof(date) && (int)date[0])
    {
        year = cal.Year((int)date[0]);
        date = Array.shift(date)[1];
    }

    if (sizeof(date))
        region = date[0];

    if (!year)
        year = cal.Year();

    print_year(year, region);
}

array make_month(object month, int field_width, void|string region)
{
    array out =({});
    mapping holidays = ([]);
    object today = Calendar.Day();

    if (region)
        holidays = Calendar.Events.find_region(region)->scan_events(month);

    array weekday_names =
        sprintf("%*.*s", field_width, field_width, month->week()->days()->week_day_shortname()[*]);

    out += ({ ({ month->month_name(), month->month_no(), month->year_name() }) });
    out += ({ weekday_names });
    out += showday(month->weeks()->days()[*][*], month, today, holidays, field_width);

    out += ({ ({ " "*field_width })*sizeof(weekday_names) });

    return out;
}

string print_month(object _month, void|int field_width, void|string region)
{
    if (!field_width)
        field_width = 2;
    array month = make_month(_month, field_width, region);
    string out = "";

    out += sprintf("%|*s\n", (field_width+1)*sizeof(month[1])-1, sprintf("%s", month[0][0]));
    out += sprintf((month[1..][*]*" ")*"\n");
    return out;
}

string print_year(object year, void|string region)
{
        array output = ({});
        int day_width = 2;
        int columns = Stdio.stdout.tcgetattr()->columns;
        int month_width = sizeof(make_month(year->month(), day_width)[1]) * (day_width+1) - 1;
        if (columns < month_width)
            columns = month_width;

        // try to find an optimal good looking solution to spread the months
        // across the terminal width
        // for the common calendar of 12 months this is easy but we need to
        // account for caledars that have more than 12 months
        float max_width = (float)((columns+2)/(month_width+2));
        float max_height = ceil(year->number_of_months()/max_width);
        float w = max_width;

        while(ceil(year->number_of_months()/(w-1)) == max_height)
            w--;

        foreach(print_month(year->months()[*], day_width, region)/w;; array row)
        {
            array rows = row[*]/"\n";
            int l = max(@sizeof(rows[*]));
            foreach(rows; int i;)
            {
                // the last line of each month is an empty line.
                // repeat the line as many times as needed to make the months equally long
                rows[i]+=({ rows[i][-1] })*(l-sizeof(rows[i]));
            }
            rows = Array.transpose(rows);
            output += rows[*]*"  ";
        }
        write("%*|s\n", sizeof(output[1]), year->format_nice());
        write(output * "\n");
        write("\n");
}

string showday(object day, object month, object today, mapping holidays, int field_width)
{
    string dayname;
    if (day->month() == month)
    {
        dayname = (string)day->month_day();
        dayname = " "*(sizeof((string)month->number_of_days())-sizeof(dayname))+dayname;
        if (day == today)
            dayname = sprintf("%|*.*s", field_width, field_width, dayname);
        else
            dayname = sprintf("%|*.*s", field_width, field_width, dayname);
        if (holidays[day])
            dayname = sprintf("%|s", dayname);
    }
    else
        dayname = " "*field_width;
    return dayname;
}


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program boolean.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ FALSE,  0      // or other value
.equ TRUE,   1      // or other value
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessTrue:    .asciz "The value is true.\n"
szMessFalse:   .asciz "The value is false.\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                            // entry of program

    mov x0,0
    //mov x0,#1                  //uncomment pour other test
    cmp x0,TRUE
    bne 1f
                                 // value true
    ldr x0,qAdrszMessTrue
    bl affichageMess
    b 100f
1:   // value False
    ldr x0,qAdrszMessFalse
    bl affichageMess

100:                             // standard end of the program */
    mov x0,0                     // return code
    mov x8,EXIT                  // request to exit program
    svc 0                        // perform the system call
qAdrszMessTrue:         .quad szMessTrue
qAdrszMessFalse:        .quad szMessFalse
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC Test(BYTE v)
  PrintF("Variable v has value %B%E",v)
  IF v THEN
    PrintE("Condition IF v is satisfied.")
  ELSE
    PrintE("Condition IF v is not satisfied.")
  FI
  IF v=0 THEN
    PrintE("Condition IF v=0 is satisfied.")
  ELSE
    PrintE("Condition IF v=0 is not satisfied.")
  FI
  IF v<>0 THEN
    PrintE("Condition IF v<>0 is satisfied.")
  ELSE
    PrintE("Condition IF v<>0 is not satisfied.")
  FI
  IF v#0 THEN
    PrintE("Condition IF v#0 is satisfied.")
  ELSE
    PrintE("Condition IF v#0 is not satisfied.")
  FI
  PutE()
RETURN

PROC Main()
  Test(0)
  Test(1)
  Test(86)
RETURN


calendar: procedure (year) options (main);
   declare year character (4) varying;
   declare (a, b, c) (0:5,0:6) character (3);
   declare name_month(12) static character (9) varying initial (
      'JANUARY', 'FEBRUARY', 'MARCH',     'APRIL',   'MAY',      'JUNE',
      'JULY',    'AUGUST',   'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER');
   declare i fixed;
   declare (mm, mmp1, mmp2) pic '99';

   put edit (center('CALENDAR FOR ' || YEAR, 67)) (a);
   put skip (2);

   do mm = 1 to 12 by 3;
      mmp1 = mm + 1; mmp2 = mm + 2;
      call prepare_month('01' || mm   || YEAR, a);
      call prepare_month('01' || mmp1 || YEAR, b);
      call prepare_month('01' || mmp2 || YEAR, c);

      put skip edit (center(name_month(mm),   23),
                     center(name_month(mmp1), 23),
                     center(name_month(mmp2), 23) ) (a);
      put skip edit ((3)'  M  T  W  T  F  S  S  ') (a);
      do i = 0 to 5;
         put skip edit (a(i,*), b(i,*), c(i,*)) (7 a, x(2));
      end;
   end;

prepare_month: procedure (start, month);
   declare month(0:5,0:6) character (3);
   declare start character (8);
   declare i pic 'ZZ9';
   declare offset fixed;
   declare (j, day) fixed binary (31);
   declare (this_month, next_month, k) fixed binary;

   day = days(start, 'DDMMYYYY');
   offset = weekday(day) - 1;
   if offset  = 0 then offset = 7;
   month = '';
   do j = day by 1;
      this_month = substr(daystodate(j,   'DDMMYYYY'), 3, 2);
      next_month = substr(daystodate(j+1, 'DDMMYYYY'), 3, 2);
      if this_month^= next_month then leave;
   end;
   i = 1;
   do k = offset-1 to offset+j-day-1;
      month(k/7, mod(k,7)) = i; i = i + 1;
   end;
end prepare_month;

end calendar;


BOOL f = FALSE, t = TRUE;
[]BOOL ft = (f, t);
STRING or = " or ";
FOR key TO UPB ft DO
  BOOL val = ft[key];
  UNION(VOID, INT) void = (val|666|EMPTY);
  REF STRING ref = (val|HEAP STRING|NIL);
  INT int = ABS val;
  REAL real = ABS val;
  COMPL compl = ABS val;
  BITS bits = BIN ABS val; # or bitspack(val); #
  BYTES bytes = bytes pack((val|"?"|null char)*bytes width);
  CHAR char = (val|"?"|null char);
  STRING string = (val|"?"|"");

  print((((val | "TRUE" | "FALSE" ), ": ", val, or, (val|flip|flop), new line)));
  print(("  void: ", " => ", (void|(VOID):FALSE|TRUE), new line));
  print(("   ref: ", " => ", ref ISNT REF STRING(NIL), new line));
  print(("   int: ", int     , " => ", int /= 0, new line));
  print(("  real: ", real    , " => ", real /= 0, new line));
  print((" compl: ", compl   , " => ", compl /= 0, new line));
  print(("  bits: ", bits    , " => ", ABS bits /= 0, or, bits /= 2r0, or,
                     bits width ELEM bits, or, []BOOL(bits)[bits width], new line));
  print((" bytes: """, STRING(bytes)    , """ => ", 1 ELEM bytes /= null char, or,
                       STRING(bytes) /= null char*bytes width, or,
                       STRING(bytes)[1] /= null char, new line));
  print(("  char: """, char  , """ => ", ABS char /= 0 , or, char /= null char, new line));
  print(("string: """, string  , """ => ", string /= "", or, UPB string /= 0, new line));
  print((new line))
OD


Param([int]$Year = 1969)
Begin {
    $COL_WIDTH = 21
    $COLS = 3
    $MONTH_COUNT = 12
    $MONTH_LINES = 9

    Function CenterStr([string]$s, [int]$lineSize) {
        $padSize = [int](($lineSize - $s.Length) / 2)
        ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ')
    }

    Function MonthLines([int]$month) {
        $dt = [System.DateTime]::new($Year, $month, 1)
        $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH
        $line += 'Su Mo Tu We Th Fr Sa'
        $line += $('   ' * $dt.DayOfWeek.value__)
        $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) }))
        $line = $line.PadRight($MONTH_LINES * $COL_WIDTH)
        New-Object –TypeName PSObject –Prop(@{
            'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] }
            'Dt'=$dt})
    }
}
Process {
    Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4))
    $(0..($MONTH_COUNT / $COLS - 1)) | %{
        $fm = $_ * $COLS
        $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 }
        $months = $monthNums | %{ MonthLines $_ }
        $(0..($MONTH_LINES - 1)) | %{
            $ml = $_
            Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {'  '}) + $months[$_].Lines[$ml] }))
        }
    }
}


1 > 2     --> false
not false --> true

{true as integer, false as integer, 1 as boolean, 0 as boolean}
          --> {1, 0, true, false}

true = 1  --> false


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

/* Constantes    */
@ The are no TRUE or FALSE constants in ARM Assembly
.equ FALSE,  0      @ or other value
.equ TRUE,   1      @ or other value
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szMessTrue: .asciz "The value is true.\n"
szMessFalse: .asciz "The value is false.\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    mov r0,#0
    //mov r0,#1   @uncomment pour other test
    cmp r0,#TRUE
    bne 1f
    @ value true
    ldr r0,iAdrszMessTrue
    bl affichageMess
    b 100f
1:   @ value False
    ldr r0,iAdrszMessFalse
    bl affichageMess

100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessTrue:		.int szMessTrue
iAdrszMessFalse:		.int szMessFalse
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */


% Write out the calender, because format can actually span multiple lines, it is easier
% to write out the static parts in place and insert the generated parts into that format.
write_calendar(Year) :-
	month_x3_format(Year, 1, 2, 3, F1_3),
	month_x3_format(Year, 4, 5, 6, F4_6),
	month_x3_format(Year, 7, 8, 9, F7_9),
	month_x3_format(Year, 10, 11, 12, F10_12),

	format('

                                      ~w

            January                  February                   March
      Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa
~w

             April                     May                      June
      Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa
~w

              July                    August                  September
      Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa
~w

            October                  November                 December
      Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa     Su Mo Tu We Th Fr Sa
~w
', [Year, F1_3, F4_6, F7_9, F10_12]), !.

% Generate the data for a row of months and then create an atom one row at a time
% for all of the months.
month_x3_format(Year, M1, M2, M3, F) :-
	calc_month_rows(Year, M1, M1r),
	calc_month_rows(Year, M2, M2r),
	calc_month_rows(Year, M3, M3r),
	month_x3_format(M1r, M2r, M3r, F).

month_x3_format(M1, M2, M3, '') :- maplist(=('   '), M1), maplist(=('   '), M2), maplist(=('   '), M3).
month_x3_format(M1, M2, M3, F) :-
		month_format('      ', M1, M1r, F1),
		month_format(F1, M2, M2r, F2),
		month_format(F2, M3, M3r, F3),
		atom_concat(F3, '\n', F4),
		month_x3_format(M1r, M2r, M3r, Fr),
		atom_concat(F4, Fr, F).

month_format(Orig, [Su,Mo,Tu,We,Th,Fr,Sa|R], R, F) :-
	maplist(day_format, [Su,Mo,Tu,We,Th,Fr,Sa], Formatted),
	format(atom(F2), '~w~w~w~w~w~w~w    ', Formatted),
	atom_concat(Orig, F2, F).

day_format('   ', '   ') :- !.
day_format(D, F) :- D < 10, format(atom(F), '~w  ', D).
day_format(D, F) :- D >= 10, format(atom(F), '~w ', D).

% Calculate the days of a month, this is done by getting the first day of the month,
% then offsetting that with spaces from the start and then adding 1-NumDaysinMonth and
% finally spaces until the end. The maximum possible size is used and then truncated later.
calc_month_rows(Year, Month, Result) :-
	length(Result, 42), % max 6 rows of 7 days
	month_days(Month, Year, DaysInMonth),
	day_of_the_week(date(Year, Month, 1), FirstWeekDay),
	day_offset(FirstWeekDay, Offset),
	day_print_map(DaysInMonth, Offset, Result).

day_print_map(DaysInMonth, 0, [1|R]) :-
	day_print_map2(DaysInMonth, 2, R).
day_print_map(DaysInMonth, Offset, ['   '|R]) :-
	dif(Offset, 0),
	succ(NewOffset, Offset),
	day_print_map(DaysInMonth, NewOffset, R).

day_print_map2(D, D, [D|R])	:- day_print_map(R).
day_print_map2(D, N, [N|R]) :- dif(D,N), succ(N, N1), day_print_map2(D, N1, R).

day_print_map([]).
day_print_map(['   '|R]) :- day_print_map(R).

% Figure out the number of days in a month based on whether it is a leap year or not.
month_days(2, Year, Days) :-
	is_leap_year(Year) -> Days = 29
	; Days = 28.
month_days(Month, _, Days) :-
	dif(Month, 2),
	nth1(Month, [31, _, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Days).

% Figure out the space offset based on the day the month starts on.
day_offset(D, D) :- dif(D, 7).
day_offset(7, 0).

% Test for leap years
is_leap_year(Year) :-
	0 is Year mod 100 -> 0 is Year mod 400
	; 0 is Year mod 4.


a: true
b: false

if? a [ print "yep" ] else [ print "nope" ]

if? b -> print "nope"
else  -> print "yep"


BEGIN {
   # Do not put quotes round the numeric values, or the tests will fail
   a = 1    # True
   b = 0    # False

   # Boolean evaluations
   if (a) { print "first test a is true" }        # This should print
   if (b) { print "second test b is true" }       # This should not print
   if (!a) { print "third test a is false" }      # This should not print
   if (!b) { print "forth test b is false" }      # This should print

   # Boolean evaluation using comparison against zero
   if (a == 0) { print "fifth test a is false" }  # This should not print
   if (b == 0) { print "sixth test b is false" }  # This should print
   if (a != 0) { print "seventh test a is true" } # This should print
   if (b != 0) { print "eighth test b is true" }  # This should not print

 }


#lang racket
(require racket/date net/base64 file/gunzip)
(define (calendar yr)
  (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n)))))
  (define months
    (for/list ([mn (in-naturals 1)]
               [mname '(January February March April May June July
                        August September October November December)])
      (define s (find-seconds 0 0 12 1 mn yr))
      (define pfx (date-week-day (seconds->date s)))
      (define days
        (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))])
          (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s)
                    60 60 24))))
      (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa"
             (map string-join
                  (nsplit 7 `(,@(make-list pfx "  ")
                              ,@(for/list ([d days])
                                  (~a (+ d 1) #:width 2 #:align 'right))
                              ,@(make-list (- 42 pfx days) "  ")))))))
  (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP
             sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj
             ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="]
        [o (open-output-string)])
    (inflate (open-input-bytes (base64-decode s)) o)
    (display (regexp-replace #rx"~a" (get-output-string o) (~a yr))))
  (for-each displayln
    (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)])
                   (regexp-replace #rx" +$" (string-join s "   ") ""))
                 (λ(s) (equal? "" s)))))

(calendar 1969)


10 LET A%=0
20 LET B%=NOT(A%)
30 PRINT "THIS VERSION OF BASIC USES"
40 PRINT B%; " AS ITS TRUE VALUE"
50 IF A% THEN PRINT "TEST ONE DOES NOT PRINT"
60 IF B% THEN PRINT "TEST TWO DOES PRINT"
70 IF A%=0 THEN PRINT "TEST THREE (FALSE BY COMPARISON) DOES PRINT"
80 IF B%=0 THEN PRINT "TEST FOUR (FALSE BY COMPARISON) DOES NOT PRINT"
90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT"
100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT"
110 END


@echo off

::true
set "a=x"
::false
set "b="

if defined a (
	echo a is true
) else (
	echo a is false
)
if defined b (
	echo b is true
) else (
	echo b is false
)

pause>nul


my $months-per-row = 3;
my @weekday-names  = <Mo Tu We Th Fr Sa Su>;
my @month-names    = <Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec>;

my Int() $year = @*ARGS.shift || 1969;
say fmt-year($year);

sub fmt-year ($year) {
    my @month-strs;
    @month-strs[$_] = [fmt-month($year, $_).lines] for 1 .. 12;
    my @C = ' ' x 30 ~ $year, '';
    for 1, 1+$months-per-row ... 12 -> $month {
        while @month-strs[$month] {
            for ^$months-per-row -> $column {
                @C[*-1] ~= @month-strs[$month+$column].shift ~ ' ' x 3 if @month-strs[$month+$column];
            }
            @C.push: '';
        }
        @C.push: '';
    }
    @C.join: "\n";
}

sub fmt-month ($year, $month) {
    my $date = Date.new($year,$month,1);
    @month-names[$month-1].fmt("%-20s\n") ~ @weekday-names ~ "\n" ~
    (('  ' xx $date.day-of-week - 1), (1..$date.days-in-month)».fmt('%2d')).flat.rotor(7, :partial).join("\n") ~
    (' ' if $_ < 7) ~ ('  ' xx 7-$_).join(' ') given Date.new($year, $month, $date.days-in-month).day-of-week;
}


do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year]
foreach m system/locale/months [
  prin rejoin ["^/^/     " m "^/^/ "]
  foreach day system/locale/days [prin join copy/part day 2 " "]
  print ""  f: to-date rejoin ["1-"m"-"y]  loop f/weekday - 1 [prin "   "]
  repeat i 31 [
    if attempt [c: to-date rejoin [i"-"m"-"y]][
      prin join either 1 = length? form i ["  "][" "] i
      if c/weekday = 7 [print ""]
    ]
  ]
] ask "^/^/Press [ENTER] to Continue..."]


foreach(var 1 42 ON yes True y Princess
            0 OFF no False n Princess-NOTFOUND)
  if(var)
    message(STATUS "${var} is true.")
  else()
    message(STATUS "${var} is false.")
  endif()
endforeach(var)


h1 = {foo: "bar"}
h2 = {foo: "bar"}

true_expressions = [
  true
  1
  h1? # because h1 is defined above
  not false
  !false
  []
  {}
  1 + 1 == 2
  1 == 1 # simple value equality
  true or false
]

false_expressions = [
  false
  not true
  undeclared_variable?
  0
  ''
  null
  undefined
  h1 == h2 # despite having same key/values
  1 == "1" # different types
  false and true
]


bdos		equ	5
putchar		equ	2
rawio		equ	6
puts		equ	9
cstat		equ	11
reads		equ	10

		org	100h
		mvi	c,puts
		lxi	d,signon	; Print name
		call	bdos
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Initialize the RNG with keyboard input
		mvi	c,puts
		lxi	d,entropy	; Ask for randomness
		call	bdos
		mvi	b,9		; 9 times,
randloop:	mvi	c,3		; read 3 keys.
		lxi	h,xabcdat + 1
randkey:	push	b		; Read a key
		push	h
randkeywait:	mvi	c,rawio
		mvi	e,0FFh
		call	bdos
		ana	a
		jz	randkeywait
		pop	h
		pop	b
		xra	m		; XOR it with the random memory
		mov	m,a
		inx	h
		dcr	c
		jnz	randkey		; Go get more characters
		dcr	b
		jnz	randloop
		mvi	c,puts
		lxi 	d,done		; Tell the user we're done
		call	bdos
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Generate 4-digit secret code
		lxi	h,secret
		mvi	b,4
gencode:	push	h
		push	b
		call	randcode
		pop	b
		pop	h
		mov	m,a
		inx	h
		dcr	b
		jnz	gencode
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; User makes a guess
readguess:	mvi	c,puts		; Ask for guess
		lxi	d,guess
		call	bdos
		mvi	c,reads		; Read guess
		lxi	d,bufdef
		call	bdos
		call	newline		; Print newline
		mvi	b,4		; Check input
		lxi	h,buf
validate:	mov	a,m
		cpi	'9' + 1		; >9?
		jnc	inval		; = invalid
		cpi	'1'		; <1?
		jc	inval		; = invalid
		sui	'0'		; Make ASCII digit into number
		mov	m,a
		inx	h
		dcr	b
		jnz	validate
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Count bulls
		mvi	c,puts
		lxi	d,bulls		; Output "Bulls:"
		call	bdos
		lxi	d,secret
		lxi	h,buf
		lxi	b,4		; No bulls, counter = 4
bullloop:	ldax	d		; Get secret digit
		cmp	m		; Match to buffer digit
		cz	countmatch
		inx	h
		inx	d
		dcr	c
		jnz	bullloop
		push	b		; Keep bulls for cow count,
		push	b		; and for final check.
		call	printcount
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Count cows
		mvi	c,puts
		lxi	d,cows		; Output ", Cows:"
		call	bdos
		pop	psw		; Retrieve the bulls (into A reg)
		cma			; Negate amount of bulls
		inr	a
		mov	b,a		; Use it as start of cow count
		mvi	d,4		; For all 4 secret digits..
		lxi	h,secret
cowouter:	mov	a,m		; Grab secret digit to test
		push	h		; Store secret position
		mvi	e,4		; For all 4 input digits...
		lxi	h,buf
cowinner:	cmp	m		; Compare to current secret digit
		cz	countmatch
		inx	h
		dcr	e		; While there are more digits in buf
		jnz	cowinner	; Test next digit
		pop	h		; Restore secret position
		inx	h		; Look at next secret digit
		dcr	d		; While there are digits left
		jnz	cowouter
		push	b		; Keep cow count
		call	printcount
		call	newline
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Check win condition
		pop	psw		; Cow count (in A)
		pop	b		; Bull count (in B)
		ana	a		; To win, there must be 0 cows...
		jnz	readguess
		mvi	a,4		; And 4 bulls.
		cmp	b
		jnz	readguess
		mvi	c,puts
		lxi	d,win
		jmp	bdos
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Increment bull/cow counter
countmatch:	inr	b
		ret
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Print a newline
newline:	mvi	c,puts
		lxi	d,nl
		jmp 	bdos
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Output counter as ASCII
printcount:	mvi	a,'0'
		add	b
		mvi	c,putchar
		mov	e,a
		jmp	bdos
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; User entered invalid input
inval:		mvi	c,puts
		lxi	d,invalid
		call	bdos
		jmp	readguess
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Generate random number 1-9 that isn't in key
randcode:	call	xabcrand
		ani	0fh	; Low nybble
		ana	a	; 0 = invalid
		jz	randcode
		cpi	10	; >9 = invalid
		jnc	randcode
		;; Check if it is a duplicate
		mvi	b,4
		lxi	h,secret
checkdup:	cmp	m
		jz	randcode
		inx	h
		dcr	b
		jnz	checkdup
		ret
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; The "X ABC" 8-bit random number generator
		;; (Google that to find where it came from)
xabcrand:       lxi     h,xabcdat
                inr     m       ; X++
                mov     a,m     ; X,
                inx     h       ;
                xra     m       ; ^ C,
                inx     h       ;
                xra     m       ; ^ A,
                mov     m,a     ; -> A
                inx     h
                add     m       ; + B,
                mov     m,a     ; -> B
                rar             ; >>1
                dcx     h
                xra     m       ; ^ A,
                dcx     h
                add     m       ; + C
                mov     m,a     ; -> C
                ret
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Strings
signon:		db	'Bulls and Cows',13,10,'$'
entropy:	db	'Please mash the keyboard to generate entropy...$'
done:		db	'done.',13,10,13,10,'$'
bulls:		db	'Bulls: $'
cows:		db	', Cows: $'
guess:		db	'Guess: $'
invalid: 	db	'Invalid input.',13,10,'$'
win:		db	'You win!',13,10,'$'
nl:		db	13,10,'$'
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;; Variables
xabcdat:	ds	4	; RNG state
secret:		ds	4	; Holds the secret code
bufdef:		db	4,0	; User input buffer
buf:		ds	4


# Project : Calendar

load "guilib.ring"
load "stdlib.ring"

new qapp
       {
        win1 = new qwidget() {

                   day = list(12)
                   pos = newlist(12,37)
                   month = list(12)
                   week = list(7)
                   weekday = list(7)
                   button = newlist(7,6)
                   monthsnames = list(12)
                   week = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
                   months = ["January", "February", "March", "April", "May", "June", "July",
                                   "August", "September", "October", "November", "December"]
                   daysnew = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]]
                   mo = [4,0,0,3,5,1,3,6,2,4,0,2]
                   mon = [31,28,31,30,31,30,31,31,30,31,30,31]
                   m2 = (((1969-1900)%7) + floor((1969 - 1900)/4) % 7) % 7
                   for n = 1 to 12
                        month[n] = (mo[n] + m2) % 7
                        x = (month[n] + 1) % 7 + 1
                       for m = 1 to len(daysnew)
                            if daysnew[m][1] = x
                              nr = m
                           ok
                       next
                       day[n] = daysnew[nr][2]
                  next
                  for m = 1 to 12
                       for n = 1 to day[m] - 1
                            pos[m][n] = "  "
                       next
                  next
                  for m = 1 to 12
                       for  n = day[m] to 37
                             if n < (mon[m] + day[m])
                                pos[m][n] = n - day[m] + 1
                             else
                                pos[m][n] = "  "
                             ok
                       next
                  next
                  setwindowtitle("Calendar")
                  setgeometry(100,100,650,800)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,800,600)
                              settext("")
                  }
                 year = new qpushbutton(win1)
                                                  {
                                                  setgeometry(280,20,60,20)
                                                  year.settext("1969")
                                                  }
                 for n = 1 to 4
                      nr = (n-1)*3+1
                     showmonths(nr)
                 next
                 for n = 1 to 12
                     showweeks(n)
                 next
                 for n = 1 to 12
                     showdays(n)
                 next
                 show()
        }
        exec()
        }

func showmonths(m)
       for n = m to m + 2
            monthsnames[n] = new qpushbutton(win1)
                                        {
                                        if n%3 = 1
                                           col = 120
                                           rownr = floor(n/3)
                                           if rownr = 0
                                              rownr = n/3
                                           ok
                                           if n = 1
                                              row = 40
                                           else
                                              row = 40+rownr*180
                                           ok
                                        else
                                           colnr = n%3
                                           if colnr = 0
                                              colnr = 3
                                           ok
                                           rownr = floor(n/3)
                                           if n%3 = 0
                                              rownr = floor(n/3)-1
                                           ok
                                           col = 120 + (colnr-1)*160
                                           row = 40 + rownr*180
                                        ok
                                        setgeometry(col,row,60,20)
                                        monthsnames[n].settext(months[n])
                                        }
       next

func showweeks(n)
        for m = 1 to 7
             col = m%7
             if col = 0 col = 7 ok
             weekday[m] = new qpushbutton(win1)
                                  {
                                  colnr = n % 3
                                  if colnr = 0
                                     colnr = 3
                                  ok
                                  rownr = floor(n/3)
                                  if n%3 = 0
                                     rownr = floor(n/3)-1
                                  ok
                                  colbegin = 60 + (colnr-1)*160
                                  rowbegin = 60 + (rownr)*180
                                  setgeometry(colbegin+col*20,rowbegin,20,20)
                                  weekday[m].settext(week[m])
                                  }
        next

func showdays(ind)
        rownr = floor(ind/3)
        if ind%3 = 0
           rownr = floor(ind/3)-1
        ok
        rowbegin = 60+rownr*180
        for m = 1 to 6
             for n = 1 to 7
                  col = n%7
                  if col = 0 col = 7 ok
                  row = m
                   button[n][m] = new qpushbutton(win1)
                                         {
                                          if ind%3 = 1
                                             colbegin = 60
                                          elseif ind%3 = 2
                                             colbegin = 220
                                          else
                                             colbegin = 380
                                          ok
                                          setgeometry(colbegin+col*20,rowbegin+row*20,20,20)
                                          nr = (m-1)*7+n
                                          if nr <= 37
                                             if pos[ind][nr] != "  "
                                                button[n][m].settext(string(pos[ind][nr]))
                                             ok
                                          ok
                                          }
             next
        next


VAR
   b,c: BOOLEAN;
...
   b := TRUE;
   c := FALSE;
...


if false
  puts "false"
elsif nil
  puts "nil"
elsif Pointer(Nil).new 0
  puts "null pointer"
elsif true && "any other value"
  puts "finally true!"
end


#t // <boolean> true
#f // <boolean> false


DEFINE DIGNUM="4"

TYPE Score=[BYTE bulls,cows,err]

PROC Generate(CHAR ARRAY secret)
  DEFINE DIGCOUNT="9"
  CHAR ARRAY digits(DIGCOUNT)
  BYTE i,j,d,tmp,count

  FOR i=0 TO DIGCOUNT-1
  DO
    digits(i)=i+'1
  OD

  secret(0)=DIGNUM
  count=DIGCOUNT
  FOR i=1 TO DIGNUM
  DO
    d=Rand(count)
    secret(i)=digits(d)
    count==-1
    digits(d)=digits(count)
  OD
RETURN

PROC CheckScore(CHAR ARRAY code,guess Score POINTER res)
  BYTE i,j

  res.bulls=0
  res.cows=0
  IF guess(0)#DIGNUM THEN
    res.err=1
    RETURN
  FI
  res.err=0
  FOR i=1 TO DIGNUM
  DO
    IF guess(i)=code(i) THEN
      res.bulls==+1
    ELSE
      FOR j=1 TO DIGNUM
      DO
        IF j#i AND guess(j)=code(i) THEN
          res.cows==+1
          EXIT
        FI
      OD
    FI
  OD
RETURN

PROC Main()
  CHAR ARRAY code(DIGNUM+1),guess(255)
  Score res

  Generate(code)
  PrintE("Bull and cows game.") PutE()
  Print("I choose a 4-digit number from digits 1 to 9 without repetition. ")
  PrintE("Your goal is to guess it.") PutE()
  PrintE("Enter your guess:")
  DO
    InputS(guess)
    CheckScore(code,guess,res)
    Put(28) ;cursor up
    PrintF("%S -> ",guess)
    IF res.err THEN
      Print("Wrong input")
    ELSE
      PrintF("Bulls=%B Cows=%B",res.bulls,res.cows)
      IF res.bulls=DIGNUM THEN
        PutE() PutE()
        PrintE("You win!")
        EXIT
      FI
    FI
    PrintE(", try again:")
  OD
RETURN


with Ada.Text_IO;  use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Bulls_And_Cows is
   package Random_Natural is new Ada.Numerics.Discrete_Random (Natural);
   Number : String (1..4);
begin
   declare -- Generation of number
      use Random_Natural;
      Digit    : String   := "123456789";
      Size     : Positive := 9;
      Dice     : Generator;
      Position : Natural;
   begin
      Reset (Dice);
      for I in Number'Range loop
         Position := Random (Dice) mod Size + 1;
         Number (I) := Digit (Position);
         Digit (Position..Size - 1) := Digit (Position + 1..Size);
         Size := Size - 1;
      end loop;
   end;
   loop -- Guessing loop
      Put ("Enter four digits:");
      declare
         Guess : String  := Get_Line;
         Bulls : Natural := 0;
         Cows  : Natural := 0;
      begin
         if Guess'Length /= 4 then
            raise Data_Error;
         end if;
         for I in Guess'Range loop
            for J in Number'Range loop
               if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then
                  raise Data_Error;
               end if;
               if Number (I) = Guess (J) then
                  if I = J then
                     Bulls := Bulls + 1;
                  else
                     Cows := Cows + 1;
                  end if;
               end if;
            end loop;
         end loop;
         exit when Bulls = 4;
         Put_Line (Integer'Image (Bulls) & " bulls," & Integer'Image (Cows) & " cows");
      exception
         when Data_Error => Put_Line ("You should enter four different digits 1..9");
      end;
   end loop;
end Bulls_And_Cows;


require 'date'

# Creates a calendar of _year_. Returns this calendar as a multi-line
# string fit to _columns_.
def cal(year, columns)

  # Start at January 1.
  #
  # Date::ENGLAND marks the switch from Julian calendar to Gregorian
  # calendar at 1752 September 14. This removes September 3 to 13 from
  # year 1752. (By fortune, it keeps January 1.)
  #
  date = Date.new(year, 1, 1, Date::ENGLAND)

  # Collect calendars of all 12 months.
  months = (1..12).collect do |month|
    rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"]

    # Make array of 42 days, starting with Sunday.
    days = []
    date.wday.times { days.push "  " }
    while date.month == month
      days.push("%2d" % date.mday)
      date += 1
    end
    (42 - days.length).times { days.push "  " }

    days.each_slice(7) { |week| rows.push(week.join " ") }
    next rows
  end

  # Calculate months per row (mpr).
  #  1. Divide columns by 22 columns per month, rounded down. (Pretend
  #     to have 2 extra columns; last month uses only 20 columns.)
  #  2. Decrease mpr if 12 months would fit in the same months per
  #     column (mpc). For example, if we can fit 5 mpr and 3 mpc, then
  #     we use 4 mpr and 3 mpc.
  mpr = (columns + 2).div 22
  mpr = 12.div((12 + mpr - 1).div mpr)

  # Use 20 columns per month + 2 spaces between months.
  width = mpr * 22 - 2

  # Join months into calendar.
  rows = ["[Snoopy]".center(width), "#{year}".center(width)]
  months.each_slice(mpr) do |slice|
    slice[0].each_index do |i|
      rows.push(slice.map {|a| a[i]}.join "  ")
    end
  end
  return rows.join("\n")
end

ARGV.length == 1 or abort "usage: #{$0} year"

# Guess width of terminal.
#  1. Obey environment variable COLUMNS.
#  2. Try to require 'io/console' from Ruby 1.9.3.
#  3. Try to run `tput co`.
#  4. Assume 80 columns.
columns = begin Integer(ENV["COLUMNS"] || "")
          rescue
            begin require 'io/console'; IO.console.winsize[1]
            rescue LoadError
              begin Integer(`tput cols`)
              rescue
                80; end; end; end

puts cal(Integer(ARGV[0]), columns)


STRING digits = "123456789";

[4]CHAR chosen;
STRING available := digits;
FOR i TO UPB chosen DO
    INT c = ENTIER(random*UPB available)+1;
    chosen[i] := available[c];
    available := available[:c-1]+available[c+1:]
OD;

COMMENT print((chosen, new line)); # Debug # END COMMENT

OP D = (INT d)STRING: whole(d,0); # for formatting an integer #

print (("I have chosen a number from ",D UPB chosen," unique digits from 1 to 9 arranged in a random order.", new line,
"You need to input a ",D UPB chosen," digit, unique digit number as a guess at what I have chosen", new line));

PRIO WITHIN = 5, NOTWITHIN = 5;
OP WITHIN = (CHAR c, []CHAR s)BOOL: char in string(c,LOC INT,s);
OP NOTWITHIN = (CHAR c, []CHAR s)BOOL: NOT ( c WITHIN s );

INT guesses := 0, bulls, cows;
WHILE
    STRING guess;
    guesses +:= 1;
    WHILE
        # get a good guess #
        print((new line,"Next guess [",D guesses,"]: "));
        read((guess, new line));
        IF UPB guess NE UPB chosen THEN
            FALSE
        ELSE
            BOOL ok;
            FOR i TO UPB guess WHILE
                ok := guess[i] WITHIN digits AND guess[i] NOTWITHIN guess[i+1:]
            DO SKIP OD;
            NOT ok
        FI
    DO
        print(("Problem, try again. You need to enter ",D UPB chosen," unique digits from 1 to 9", new line))
    OD;
# WHILE #
    guess NE chosen
DO
    bulls := cows := 0;
    FOR i TO UPB chosen DO
        IF guess[i] = chosen[i] THEN
            bulls +:= 1
        ELIF guess[i] WITHIN chosen THEN
            cows +:= 1
        FI
    OD;
    print(("  ",D bulls," Bulls",new line,"  ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))


// Assume your binary name is 'calendar'.
// Command line:
// >>$ calendar 2019 150
// First argument: year number.
// Second argument (optional): text area width (in characters).

extern crate chrono;

use std::{env, cmp};
use chrono::{NaiveDate, Datelike};

const MONTH_WIDTH: usize = 22;

fn print_header(months: &[&str]) {
    const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA  ";
    println!();
    for m in months {
        print!("{:^20}  ", m);
    }
    println!("\n{}", DAYS_OF_WEEK.repeat(months.len()));
}

fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> {
    let start = week_num * 7 - start_day_of_week + 1;
    let end = (week_num + 1) * 7 - start_day_of_week;
    let mut ret = String::with_capacity(MONTH_WIDTH);
    if start > days {
        None
    } else {
        for i in start..(end + 1) {
            if i <= 0 || i > days {
                ret.push_str("  ");
            } else {
                if i < 10 {
                    ret.push_str(" ");
                }
                ret.push_str(&i.to_string());
            }
            ret.push_str(" ");
        }
        ret.push_str(" ");
        Some(ret)
    }
}

fn main() {
    const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
                                     "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
    const DEFAULT_TEXT_WIDTH: usize = 100;

    let args: Vec<String> = env::args().collect();
    let year: i32 = args[1].parse().expect("The first argument must be a year");
    let width: usize = if args.len() > 2 {
        cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width"))
    } else {
        DEFAULT_TEXT_WIDTH
    };
    let months_in_row = width / MONTH_WIDTH;
    let month_rows = if MONTH_NAMES.len() % months_in_row == 0 {
        MONTH_NAMES.len() / months_in_row
    } else {
        MONTH_NAMES.len() / months_in_row + 1
    };

    let start_days_of_week: Vec<i32> =
        (1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect();

    let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    println!("{year:^w$}", w=width, year=year.to_string());
    for i in 0..month_rows {
        let start = i * months_in_row;
        let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len());
        print_header(&MONTH_NAMES[start..end]);
        let mut count = 0;
        let mut row_num = 0;
        while count < months_in_row {
            let mut row_str = String::with_capacity(width);
            for j in start..end {
                match get_week_str(month_days[j], row_num, start_days_of_week[j]) {
                    None => {
                        count += 1;
                        row_str.push_str(&" ".repeat(MONTH_WIDTH));
                    },
                    Some(week_str) => row_str.push_str(&week_str)
                }
            }
            if count < months_in_row {
                println!("{}", row_str);
            }
            row_num += 1;
        }
    }
}


? if (true) { "a" } else { "b" }
# value: "a"

? if (false) { "a" } else { "b" }
# value: "b"

? if (90) { "a" } else { "b" }
# problem: the int 90 doesn't coerce to a boolean


input   ← {⍞←'Guess: ' ⋄ 7↓⍞}
output  ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
isdigits← ∧/⎕D∊⍨⊢
valid   ← isdigits∧4=≢
guess   ← ⍎¨input⍣(valid⊣)
bulls   ← +/=
cows    ← +/∊∧≠
game    ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣)
random  ← 4∘⊣?9∘⊣
moo     ← 'You win!'⊣(random game⊢)


on pickNumber()
	set theNumber to ""
	repeat 4 times
		set theDigit to (random number from 1 to 9) as string
		repeat while (offset of theDigit in theNumber) > 0
			set theDigit to (random number from 1 to 9) as string
		end repeat
		set theNumber to theNumber & theDigit
	end repeat
end pickNumber

to bulls of theGuess given key:theKey
	set bullCount to 0
	repeat with theIndex from 1 to 4
		if text theIndex of theGuess = text theIndex of theKey then
			set bullCount to bullCount + 1
		end if
	end repeat
	return bullCount
end bulls

to cows of theGuess given key:theKey, bulls:bullCount
	set cowCount to -bullCount
	repeat with theIndex from 1 to 4
		if (offset of (text theIndex of theKey) in theGuess) > 0 then
			set cowCount to cowCount + 1
		end if
	end repeat

	return cowCount
end cows

to score of theGuess given key:theKey
	set bullCount to bulls of theGuess given key:theKey
	set cowCount to cows of theGuess given key:theKey, bulls:bullCount
	return {bulls:bullCount, cows:cowCount}
end score

on run
	set theNumber to pickNumber()
	set pastGuesses to {}
	repeat
		set theMessage to ""
		repeat with aGuess in pastGuesses
			set {theGuess, theResult} to aGuess
			set theMessage to theMessage & theGuess & ":" & bulls of theResult & "B, " & cows of theResult & "C" & linefeed
		end repeat
		set theMessage to theMessage & linefeed & "Enter guess:"
		set theGuess to text returned of (display dialog theMessage with title "Bulls and Cows" default answer "")
		set theScore to score of theGuess given key:theNumber
		if bulls of theScore is 4 then
			display dialog "Correct!  Found the secret in " & ((length of pastGuesses) + 1) & " guesses!"
			exit repeat
		else
			set end of pastGuesses to {theGuess, theScore}
		end if
	end repeat
end run


import java.util.{ Calendar, GregorianCalendar }
import language.postfixOps
import collection.mutable.ListBuffer

object CalendarPrint extends App {
  val locd = java.util.Locale.getDefault()
  val cal = new GregorianCalendar
  val monthsMax = cal.getMaximum(Calendar.MONTH)

  def JDKweekDaysToISO(dn: Int) = {
    val nday = dn - Calendar.MONDAY
    if (nday < 0) (dn + Calendar.THURSDAY) else nday
  }

  def daysInMonth(year: Int, monthMinusOne: Int): Int = {
    cal.set(year, monthMinusOne, 1)
    cal.getActualMaximum(Calendar.DAY_OF_MONTH)
  }

  def namesOfMonths() = {
    def f1(i: Int): String = {
      cal.set(2013, i, 1)
      cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locd)
    }
    (0 to monthsMax) map f1
  }

  def offsets(year: Int): List[Int] = {
    val months = cal.getMaximum(Calendar.MONTH)
    def get1stDayOfWeek(i: Int) = {
      cal.set(year, i, 1)
      cal.get(Calendar.DAY_OF_WEEK)
    }
    (0 to monthsMax).toList map get1stDayOfWeek map { i => JDKweekDaysToISO(i) }
  }

  def headerNameOfDays() = {
    val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locd) // map days of week
    val it = mdow.keySet.iterator
    val keySet = new ListBuffer[String]
    while (it.hasNext) keySet += it.next
    (keySet.map { key => (JDKweekDaysToISO(mdow.get(key)), key.take(2))
    }.sortWith(_._1 < _._1) map (_._2)).mkString(" ")
  }

  def getGregCal(year: Int) = {
    {

      def dayOfMonth(month: Int) = new Iterator[(Int, Int)] {
        cal.set(year, month, 1)
        var ldom = 0

        def next() = {
          val res = (cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH))
          ldom = res._2
          cal.roll(Calendar.DAY_OF_MONTH, true)
          res
        }

        def hasNext() = (cal.get(Calendar.DAY_OF_MONTH) > ldom)
      }
      var ret: List[(Int, Int)] = Nil
      for (i <- 0 to monthsMax) ret = ret ++ (dayOfMonth(i).toSeq)
      (ret, offsets(year))
    }
  }

  def printCalendar(calendar: (List[(Int, Int)], List[Int]),
                    headerList: List[String] = Nil,
                    printerWidth: Int = 80) = {
    val mw = 20 // month width
    val gwf = 2 // gap width fixed
    val gwm = 2 // gap width minimum
    val fgw = true

    val arr = Array.ofDim[String](6, 7)

    def limits(printerWidth: Int): (Int, Int, Int, Int, Int) = {
      val pw = if (printerWidth < 20) 20 else if (printerWidth > 300) 300 else printerWidth

      // months side by side, gaps sum minimum
      val (msbs, gsm) = {
        val x1 = {
          val c = if (pw / mw > 12) 12 else pw / mw
          val a = (c - 1)
          if (c * mw + a * gwm <= pw) c else a
        } match {
          case 5                      => 4
          case a if (a > 6 && a < 12) => 6
          case other                  => other
        }
        (x1, (x1 - 1) * gwm)
      }

      def getFGW(msbs: Int, gsm: Int) = { val r = (pw - msbs * mw - gsm) / 2; (r, gwf, r) } // fixed gap width
      def getVGW(msbs: Int, gsm: Int) = pw - msbs * mw - gsm match { // variable gap width
        case a if (a < 2 * gwm) => (a / 2, gwm, a / 2)
        case b                  => { val x = (b + gsm) / (msbs + 1); (x, x, x) }
      }

      // left margin, gap width, right margin
      val (lm, gw, rm) = if (fgw) getFGW(msbs, gsm) else getVGW(msbs, gsm)
      (pw, msbs, lm, gw, rm)
    } // def limits(

    val (pw, msbs, lm, gw, rm) = limits(printerWidth)
    val monthsList = (0 to monthsMax).map { m => calendar._1.filter { _._1 == m } }
    val nom = namesOfMonths()
    val hnod = headerNameOfDays

    def fsplit(list: List[(Int, Int)]): List[String] = {
      def fap(p: Int) = (p / 7, p % 7)
      for (i <- 0 until 6) for (j <- 0 until 7) arr(i)(j) = "  "
      for (i <- 0 until list.size)
        arr(fap(i + calendar._2(list(i)._1))._1)(fap(i + calendar._2(list(i)._1))._2) =
          f"${(list(i)._2)}%2d"
      arr.toList.map(_.foldRight("")(_ + " " + _))
    }
    val monthsRows = monthsList.map(fsplit)

    def center(s: String, l: Int): String = {
      (if (s.size >= l) s
      else " " * ((l - s.size) / 2) + s + " " * ((l - s.size) / 2) + " ").substring(0, l)
    }

    val maxMonths = monthsMax + 1

    val rowblocks = (1 to maxMonths / msbs).map { i =>
      (0 to 5).map { j =>
        val lb = new ListBuffer[String]
        val k = (i - 1) * msbs
        (k to k + msbs - 1).map { l => lb += monthsRows(l)(j) }
        lb
      }
    }

    val mheaders = (1 to maxMonths / msbs).
      map { i => (0 to msbs - 1).map { j => center(nom(j + (i - 1) * msbs), 20) } }
    val dowheaders = (1 to maxMonths / msbs).
      map { i => (0 to msbs - 1).map { j => center(hnod, 20) } }

    headerList.foreach(xs => println(center(xs + '\n', pw)))
    (1 to 12 / msbs).foreach { i =>
      println(" " * lm + mheaders(i - 1).foldRight("")(_ + " " * gw + _))
      println(" " * lm + dowheaders(i - 1).foldRight("")(_ + " " * gw + _))
      rowblocks(i - 1).foreach { xs => println(" " * lm + xs.foldRight("")(_ + " " * (gw - 1) + _)) }
      println
    }
  } //  def printCal(

  printCalendar(getGregCal(1969), List("[Snoopy Picture]", "1969"))
  printCalendar(getGregCal(1582), List("[Snoopy Picture]", "1582"), printerWidth = 132)
}


(not #t)  → #f
(not #f)  → #t
(not null) → #f
(not 0) → #f


myBool boolean = 0;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 1;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 2;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = false;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = true;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myInt int = 0;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 1;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 2;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = false;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = true;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));


iex(1)> true === :true
true
iex(2)> false === :false
true
iex(3)> true === 1
false


rand: first.n: 4 unique map 1..10 => [sample 0..9]
bulls: 0

while [bulls <> 4][
    bulls: new 0
	cows: new 0

    got: strip input "make a guess: "
    if? or? not? numeric? got
            4 <> size got -> print "Malformed answer. Try again!"
    else [
        loop.with:'i split got 'digit [
            if? (to :integer digit) = rand\[i] -> inc 'bulls
            else [
                if contains? rand to :integer digit -> inc 'cows
            ]
        ]
        print ["Bulls:" bulls "Cows:" cows "\n"]
    ]
]
print color #green "** Well done! You made the right guess!!"


length:=4, Code:="" ; settings

While StrLen(Code) < length {
	Random, num, 1, 9
	If !InStr(Code, num)
		Code .= num
}
Gui, Add, Text, w83 vInfo, I'm thinking of a %length%-digit number with no duplicate digits.
Gui, Add, Edit, wp vGuess, Enter a guess...
Gui, Add, Button, wp Default vDefault, Submit
Gui, Add, Edit, ym w130 r8 vHistory ReadOnly
Gui, Show
Return

ButtonSubmit:
	If Default = Restart
		Reload
	Gui, Submit, NoHide
	If (StrLen(Guess) != length)
		GuiControl, , Info, Enter a %length%-digit number.
	Else If Guess is not digit
		GuiControl, , Info, Enter a %length%-digit number.
	Else
	{
		GuiControl, , Info
		GuiControl, , Guess
		If (Guess = Code)
		{
			GuiControl, , Info, Correct!
			GuiControl, , Default, Restart
			Default = Restart
		}
		response := Response(Guess, Code)
		Bulls := SubStr(response, 1, InStr(response,",")-1)
		Cows := SubStr(response, InStr(response,",")+1)
		GuiControl, , History, % History . Guess ": " Bulls " Bulls " Cows " Cows`n"
	}
Return

GuiEscape:
GuiClose:
	ExitApp

Response(Guess,Code) {
	Bulls := 0, Cows := 0
	Loop, % StrLen(Code)
		If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1))
			Bulls++
		Else If (InStr(Code, SubStr(Guess, A_Index, 1)))
			Cows++
	Return Bulls "," Cows
}


$ include "seed7_05.s7i";
  include "time.s7i";

const func string: center (in string: stri, in integer: length) is
  return ("" lpad (length - length(stri)) div 2 <& stri) rpad length;

const proc: printCalendar (in integer: year, in integer: cols) is func
  local
    var time: date is time.value;
    var integer: dayOfWeek is 0;
    const array string: monthNames is [] ("January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December");
    var array array string: monthTable is 12 times 9 times "";
    var string: str is "";
    var integer: month is 0;
    var integer: position is 0;
    var integer: row is 0;
    var integer: column is 0;
    var integer: line is 0;
  begin
    for month range 1 to 12 do
      monthTable[month][1] := " " & center(monthNames[month], 20);
      monthTable[month][2] := " Mo Tu We Th Fr Sa Su";
      date := date(year, month, 1);
      dayOfWeek := dayOfWeek(date);
      for position range 1 to 43 do
        if position >= dayOfWeek and position - dayOfWeek < daysInMonth(date.year, date.month) then
          str := succ(position - dayOfWeek) lpad 3;
        else
          str := "" lpad 3;
        end if;
        monthTable[month][3 + pred(position) div 7] &:= str;
      end for;
    end for;
    writeln(center("[Snoopy Picture]", cols * 24 + 4));
    writeln(center(str(year),cols * 24 + 4));
    writeln;
    for row range 1 to succ(11 div cols) do
      for line range 1 to 9 do
        for column range 1 to cols do
          if pred(row) * cols + column <= 12 then
            write("   " & monthTable[pred(row) * cols + column][line]);
          end if;
        end for;
        writeln;
      end for;
    end for;
  end func;

const proc: main is func
  begin
    printCalendar(1969, 3);
  end func;


--True and False directly represent Boolean values in Elm
--For eg to show yes for true and no for false
if True then "yes" else "no"

--Same expression differently
if False then "no" else "yes"

--This you can run as a program
--Elm allows you to take anything you want for representation
--In the program we take T for true F for false
import Html exposing(text,div,Html)
import Html.Attributes exposing(style)

type Expr = T | F | And Expr Expr | Or Expr Expr | Not Expr

evaluate : Expr->Bool
evaluate expression =
 case expression of
 T ->
  True

 F ->
  False

 And expr1 expr2 ->
  evaluate expr1 && evaluate expr2

 Or expr1 expr2 ->
  evaluate expr1 || evaluate expr2

 Not expr ->
  not (evaluate expr)

--CHECKING RANDOM LOGICAL EXPRESSIONS
ex1= Not F
ex2= And T F
ex3= And (Not(Or T F)) T

main =
    div [] (List.map display  [ex1, ex2, ex3])

display expr=
   div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ]
--END


1> 1 < 2.
true
2> 1 < 1.
false
3> 0 == false.
false


# Usage: GAWK -f BULLS_AND_COWS.AWK
BEGIN {
    srand()
    secret = ""
    for (i = 1; i <= 4; ) {
        digit = int(9 * rand()) + 1
        if (index(secret, digit) == 0) {
            secret = secret digit
            i++
        }
    }
    print "Welcome to 'Bulls and Cows'!"
    print "I thought of a 4-digit number."
    print "Please enter your guess."
}
iswellformed($0) {
    if (calcscore($0, secret)) {
        exit
    }
}
function iswellformed(number,    i, digit) {
    if (number !~ /[1-9][1-9][1-9][1-9]/) {
        print "Your guess should contain 4 digits, each from 1 to 9. Try again!"
        return 0
    }
    for (i = 1; i <= 3; i++) {
        digit = substr(number, 1, 1)
        number = substr(number, 2)
        if (index(number, digit) != 0) {
            print "Your guess contains a digit twice. Try again!"
            return 0
        }
    }
    return 1
}
function calcscore(guess, secret,    bulls, cows, i, idx) {
    # Bulls = correct digits at the right position
    # Cows = correct digits at the wrong position
    for (i = 1; i <= 4; i++) {
        idx = index(secret, substr(guess, i, 1))
        if (idx == i) {
            bulls++
        } else if (idx > 0) {
            cows++
        }
    }
    printf("Your score for this guess: Bulls = %d, Cows = %d.", bulls, cows)
    if (bulls < 4) {
        printf(" Try again!\n")
    } else {
        printf("\nCongratulations, you win!\n")
    }
    return bulls == 4
}


require('DateTime')

define months_per_col = 3
define week_day_names = <Mo Tu We Th Fr Sa Su>
define month_names = <Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec>

func fmt_month (year, month) {
    var str = sprintf("%-20s\n", month_names[month-1])
    str += week_day_names.join(' ')+"\n"

    var dt = %s<DateTime>
    var date = dt.new(year => year, month => month)
    var week_day = date.day_of_week
    str += (week_day-1 `of` "  " -> join(" "))

    var last_day = dt.last_day_of_month(year => year, month => month).day
    for day (date.day .. last_day) {
        date = dt.new(year => year, month => month, day => day)
        str += " " if (week_day ~~ (2..7))
        if (week_day == 8) {
            str += "\n"
            week_day = 1
        }
        str += sprintf("%2d", day)
        ++week_day
    }
    str += " " if (week_day < 8)
    str += (8-week_day `of` "  " -> join(" "))
    str += "\n"
}

func fmt_year (year) {
    var month_strs = 12.of {|i| fmt_month(year, i+1).lines }

    var str = (' '*30 + year + "\n")
    for month (0..11 `by` months_per_col) {
        while (month_strs[month]) {
            for i (1..months_per_col) {
                month_strs[month + i - 1] || next
                str += month_strs[month + i - 1].shift
                str += ' '*3
            }
            str += "\n"
        }
        str += "\n"
    }

    return str
}

print fmt_year(ARGV ? Number(ARGV[0]) : 1969)


DEFINT A-Z

DIM secret AS STRING
DIM guess  AS STRING
DIM c      AS STRING
DIM bulls, cows, guesses, i

RANDOMIZE TIMER
DO WHILE LEN(secret) < 4
    c = CHR$(INT(RND * 10) + 48)
    IF INSTR(secret, c) = 0 THEN secret = secret + c
LOOP

guesses = 0
DO
    INPUT "Guess a 4-digit number with no duplicate digits: "; guess
    guess = LTRIM$(RTRIM$(guess))
    IF LEN(guess) = 0 THEN EXIT DO

    IF LEN(guess) <> 4 OR VAL(guess) = 0 THEN
        PRINT "** You should enter 4 numeric digits!"
        GOTO looper
    END IF

    bulls = 0: cows = 0: guesses = guesses + 1
    FOR i = 1 TO 4
        c = MID$(secret, i, 1)
        IF MID$(guess, i, 1) = c THEN
            bulls = bulls + 1
        ELSEIF INSTR(guess, c) THEN
            cows = cows + 1
        END IF
    NEXT i
    PRINT bulls; " bulls, "; cows; " cows"

    IF guess = secret THEN
        PRINT "You won after "; guesses; " guesses!"
        EXIT DO
    END IF
looper:
LOOP