Set objFSO = CreateObject("Scripting.FileSystemObject")

SourceFile = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\out.txt"
Content = "(Over)write a file so that it contains a string." & vbCrLf &_
		"The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once."

With objFSO.OpenTextFile(SourceFile,2,True,0)
	.Write Content
	.Close
End With

Set objFSO = Nothing


Module Module1

    Sub Main()
        My.Computer.FileSystem.WriteAllText("new.txt", "This is a string", False)
    End Sub

End Module


import "io" for File

// create a text file
File.create("hello.txt") { |file|
    file.writeBytes("hello")
}

// check it worked
System.print(File.read("hello.txt"))

// overwrite it by 'creating' the file again
File.create("hello.txt") {|file|
    file.writeBytes("goodbye")
}

// check it worked
System.print(File.read("hello.txt"))


class Program
{
    static void Main(string[] args)
    {
        XDocument xmlDoc = XDocument.Load("XMLFile1.xml");
        var query = from p in xmlDoc.Descendants("Student")
                    select p.Attribute("Name");

        foreach (var item in query)
        {
            Console.WriteLine(item.Value);
        }
        Console.ReadLine();
    }
}


/*
Using the Qt library's XML parser.
*/
#include <iostream>

#include <QDomDocument>
#include <QObject>

int main() {
    QDomDocument doc;

    doc.setContent(
       QObject::tr(
          "<Students>\n"
          "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
          "<Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
          "<Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
          "<Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
          "<Pet Type=\"dog\" Name=\"Rover\" />\n"
          "</Student>\n"
          "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
          "</Students>"));

    QDomElement n = doc.documentElement().firstChildElement("Student");
    while(!n.isNull()) {
        std::cout << qPrintable(n.attribute("Name")) << std::endl;
        n = n.nextSiblingElement();
    }
    return 0;
}


Class XML.Students [ Abstract ]
{

XData XMLData
{
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
}

ClassMethod Output() As %Status
{
   // get xml stream from the 'XData' block contained in this class and parse
   Set xdata=##class(%Dictionary.CompiledXData).%OpenId($this_"||XMLData",, .sc)
   If $$$ISERR(sc) Quit sc
   Set sc=##class(%XML.TextReader).ParseStream(xdata.Data, .hdlr)
   If $$$ISERR(sc) Quit sc

   // iterate through document, node by node
   While hdlr.Read() {
	   If hdlr.Path="/Students/Student", hdlr.MoveToAttributeName("Name") {
		   Write hdlr.Value, !
	   }
   }

   // finished
   Quit $$$OK
}

}


ClearAll[ReverseFractionalPart, ReplacePixelWithAlpha, DrawEndPoint, DrawLine]
ReverseFractionalPart[x_] := 1 - FractionalPart[x]
ReplacePixelWithAlpha[img_Image, pos_ -> colvals : {_, _, _},
  alpha_] := Module[{vals,},
  vals = PixelValue[img, pos];
  vals = (1 - alpha) vals + alpha colvals;
  ReplacePixelValue[img, pos -> vals]
  ]
DrawEndPoint[img_Image, pt : {x_, y_}, grad_, p_] :=
 Module[{xend, yend, xgap, px, py, i},
  xend = Round[x];
  yend = y + grad (xend - x);
  xgap = ReverseFractionalPart[x + 0.5];
  {px, py} = Floor[{xend, yend}];
  i = ReplacePixelWithAlpha[img, p[{x, py}] -> {1, 1, 1}, ReverseFractionalPart[yend] xgap];
  i = ReplacePixelWithAlpha[i, p[{x, py + 1}] -> {1, 1, 1}, FractionalPart[yend] xgap];
  {px, i}
  ]
DrawLine[img_Image, p1 : {_, _}, p2 : {_, _}] :=
 Module[{x1, x2, y1, y2, steep, p, grad, intery, xend, yend, x, y,
   xstart, ystart, dx, dy, i},
  {x1, y1} = p1;
  {x2, y2} = p2;
  dx = x2 - x1;
  dy = y2 - y1;
  steep = Abs[dx] < Abs[dy];
  p = If[steep, Reverse[#], #] &;
  If[steep,
   {x1, y1, x2, y2, dx, dy} = {y1, x1, y2, x2, dy, dx}
   ];
  If[x2 < x1,
   {x1, x2, y1, y2} = {x2, x1, y2, y1}
   ];
  grad = dy/dx;
  intery = y1 + ReverseFractionalPart[x1] grad;
  {xstart, i} = DrawEndPoint[img, p[p1], grad, p];
  xstart += 1;
  {xend, i} = DrawEndPoint[i, p[p2], grad, p];
  Do[
   y = Floor[intery];
   i = ReplacePixelWithAlpha[i, p[{x, y}] -> {1, 1, 1}, ReverseFractionalPart[intery]];
   i = ReplacePixelWithAlpha[i, p[{x, y + 1}] -> {1, 1, 1}, FractionalPart[intery]];
   intery += grad
   ,
   {x, xstart, xend}
   ];
  i
  ]
image = ConstantImage[Black, {100, 100}];
Fold[DrawLine[#1, {20, 10}, #2] &, image, AngleVector[{20, 10}, {75, #}] & /@ Subdivide[0, Pi/2, 10]]


import math
import imageman

template ipart(x: float): float = floor(x)
template fpart(x: float): float = x - ipart(x)
template rfpart(x: float): float = 1 - fpart(x)

const
  BG = ColorRGBF64([0.0, 0.0, 0.0])
  FG = ColorRGBF64([1.0, 1.0, 1.0])

func plot(img: var Image; x, y: int; c: float) =
  ## Draw a point with brigthness c.
  let d = 1 - c
  img[x, y] = ColorRGBF64([BG.r * d + FG.r * c, BG.g * d + FG.g * c, BG.b * d + FG.b * c])

func drawLine(img: var Image; x0, y0, x1, y1: float) =
  ## Draw an anti-aliased line from (x0, y0) to (x1, y1).

  var (x0, y0, x1, y1) = (x0, y0, x1, y1)
  let steep = abs(y1 - y0) > abs(x1 - x0)
  if steep:
    swap x0, y0
    swap x1, y1
  if x0 > x1:
    swap x0, x1
    swap y0, y1

  let dx = x1 - x0
  let dy = y1 - y0
  var gradient = dy / dx
  if dx == 0:
    gradient = 1

  # Handle first endpoint.
  var xend = round(x0)
  var yend = y0 + gradient * (xend - x0)
  var xgap = rfpart(x0 + 0.5)
  let xpxl1 = xend.toInt
  let ypxl1 = yend.toInt
  if steep:
    img.plot(ypxl1, xpxl1, rfpart(yend) * xgap)
    img.plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)
  else:
    img.plot(xpxl1, ypxl1, rfpart(yend) * xgap)
    img.plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)
  var intery = yend + gradient    # First y-intersection for the main loop.

  # Handle second endpoint.
  xend = round(x1)
  yend = y1 + gradient * (xend - x1)
  xgap = fpart(x1 + 0.5)
  let xpxl2 = xend.toInt
  let ypxl2 = yend.toInt
  if steep:
    img.plot(ypxl2, xpxl2, rfpart(yend) * xgap)
    img.plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)
  else:
    img.plot(xpxl2, ypxl2, rfpart(yend) * xgap)
    img.plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)

  # Main loop.
  if steep:
    for x in (xpxl1 + 1)..(xpxl2 - 1):
      img.plot(intery.int, x, rfpart(intery))
      img.plot(intery.int + 1, x, fpart(intery))
      intery += gradient
  else:
    for x in (xpxl1 + 1)..(xpxl2 - 1):
      img.plot(x, intery.int, rfpart(intery))
      img.plot(x, intery.int + 1, fpart(intery))
      intery += gradient

when isMainModule:
  var img = initImage[ColorRGBF64](800, 800)
  img.fill(BG)
  for x1 in countup(100, 700, 60):
    img.drawLine(400, 700, x1.toFloat, 100)
  img.savePNG("xiaoling_wu.png", compression = 9)


program wu;
uses
  SDL2,
  math;

const
  FPS = 1000 div 60;
  SCALE = 6;

var
  win: PSDL_Window;
  ren: PSDL_Renderer;
  mouse_x, mouse_y: longint;
  origin: TSDL_Point;
  event: TSDL_Event;
  line_alpha: byte = 255;

procedure SDL_RenderDrawWuLine(renderer: PSDL_Renderer; x1, y1, x2, y2: longint);
var
  r, g, b, a, a_new: Uint8;
  gradient, iy: real;
  x, y: longint;
  px, py: plongint;

  procedure swap(var a, b: longint);
  var
    tmp: longint;
  begin
    tmp := a;
    a := b;
    b := tmp;
  end;

begin
  if a = 0 then
    exit;
  SDL_GetRenderDrawColor(renderer, @r, @g, @b, @a);
  if abs(y2 - y1) > abs(x2 - x1) then
    begin
      swap(x1, y1);
      swap(x2, y2);
      px := @y;
      py := @x;
    end
  else
    begin
      px := @x;
      py := @y;
    end;
  if x1 > x2 then
    begin
      swap(x1, x2);
      swap(y1, y2);
    end;
  x := x2 - x1;
  if x = 0 then
    x := 1;
  gradient := (y2 - y1) / x;
  iy := y1;
  for x := x1 to x2 do
    begin
      a_new := round(a * frac(iy));
      y := floor(iy);
      SDL_SetRenderDrawColor(renderer, r, g, b, a-a_new);
      SDL_RenderDrawPoint(renderer, px^, py^);
      inc(y);
      SDL_SetRenderDrawColor(renderer, r, g, b, a_new);
      SDL_RenderDrawPoint(renderer, px^, py^);
      iy := iy + gradient;
    end;
  SDL_SetRenderDrawColor(renderer, r, g, b, a);
end;

begin
  SDL_Init(SDL_INIT_VIDEO);
  win := SDL_CreateWindow('Xiaolin Wu''s line algorithm', SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                        640, 480, SDL_WINDOW_RESIZABLE);
  ren := SDL_CreateRenderer(win, -1, 0);
  if ren = NIL then
    begin
      writeln(SDL_GetError);
      halt;
    end;
  SDL_SetRenderDrawBlendMode(ren, SDL_BLENDMODE_BLEND);
  SDL_RenderSetScale(ren, SCALE, SCALE);
  SDL_SetCursor(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR));

  mouse_x := 0;
  mouse_y := 0;
  origin.x := 0;
  origin.y := 0;
  repeat
    while SDL_PollEvent(@event) = 1 do
      case event.type_ of
        SDL_KEYDOWN:
          if event.key.keysym.sym = SDLK_ESCAPE then
            halt;
        SDL_MOUSEBUTTONDOWN:
          begin
            origin.x := mouse_x;
            origin.y := mouse_y;
          end;
        SDL_MOUSEMOTION:
          with event.motion do
            begin
              mouse_x := x div SCALE;
              mouse_y := y div SCALE;
            end;
        SDL_MOUSEWHEEL:
          line_alpha := EnsureRange(line_alpha + event.wheel.y * 20, 0, 255);
        SDL_QUITEV:
          halt;
      end;

    SDL_SetRenderDrawColor(ren, 35, 35, 35, line_alpha);
    SDL_RenderDrawWuLine(ren, origin.x, origin.y, mouse_x, mouse_y);
    SDL_RenderPresent(ren);
    SDL_SetRenderDrawColor(ren, 255, 255, 255, 255);
    SDL_RenderClear(ren);
    SDL_Delay(FPS);
  until false;
end.


(define n (open-output-file "example.txt"))
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)


[FSet(FOpen("output.txt", 1), ^o);
Text(3, "This is a string.");
]


package com.rosetta.example

import java.io.File
import java.io.PrintStream

class WriteFile {
    def static main( String ... args ) {
        val fout = new PrintStream(new File(args.get(0)))
        fout.println("Some text.")
        fout.close
    }
}


open "output.txt" for writing as #1
print #1 "This is a string"
close #1


      // write returns bytes written, GC will close the file (eventually)
File("foo","wb").write("this is a test",1,2,3); //-->17

f:=File("bar",wb");
data.pump(f,g); // use g to process data as it is written to file
f.close();  // don't wait for GC


(import '(java.io ByteArrayInputStream))
(use 'clojure.xml) ; defines 'parse

(def xml-text "<Students>
  <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />
  <Student Name='Bob' Gender='M'  DateOfBirth='1990-03-04' />
  <Student Name='Chad' Gender='M'  DateOfBirth='1991-05-06' />
  <Student Name='Dave' Gender='M'  DateOfBirth='1992-07-08'>
    <Pet Type='dog' Name='Rover' />
  </Student>
  <Student DateOfBirth='1993-09-10' Gender='F' Name='Émily' />
</Students>")

(def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))


(defparameter *xml-blob*
"<Students>
  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />
  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />
  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">
    <Pet Type=\"dog\" Name=\"Rover\" />
  </Student>
  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>")

(let* ((document (cxml:parse *xml-blob* (cxml-dom:make-dom-builder)))
       (students (dom:item (dom:get-elements-by-tag-name document "Students") 0))
       (student-names '()))
  (dom:do-node-list (child (dom:child-nodes students) (nreverse student-names))
    (when (dom:element-p child)
      (push (dom:get-attribute child "Name") student-names))))


import kxml.xml;
char[]xmlinput =
"<Students>
  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />
  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />
  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">
    <Pet Type=\"dog\" Name=\"Rover\" />
  </Student>
  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>";

void main() {
        auto root = readDocument(xmlinput);
        foreach(students;root.getChildren) if (!students.isCData && students.getName == "Students") {
                // now look for student subnodes
                foreach(student;students.getChildren) if (!student.isCData && student.getName == "Student") {
                        // we found a student!
                        std.stdio.writefln("%s",student.getAttribute("Name"));
                }
                // we only want one, so break out of the loop once we find a match
                break;
        }
}


#!perl
use strict;
use warnings;

sub plot {
	my ($x, $y, $c) = @_;
	printf "plot %d %d %.1f\n", $x, $y, $c if $c;
}

sub ipart {
	int shift;
}

sub round {
	int( 0.5 + shift );
}

sub fpart {
	my $x = shift;
	$x - int $x;
}

sub rfpart {
	1 - fpart(shift);
}

sub drawLine {
	my ($x0, $y0, $x1, $y1) = @_;

	my $plot = \&plot;

	if( abs($y1 - $y0) > abs($x1 - $x0) ) {
		$plot = sub { plot( @_[1, 0, 2] ) };
		($x0, $y0, $x1, $y1) = ($y0, $x0, $y1, $x1);
	}

	if( $x0 > $x1 ) {
		($x0, $x1, $y0, $y1) = ($x1, $x0, $y1, $y0);
	}

	my $dx = $x1 - $x0;
	my $dy = $y1 - $y0;
	my $gradient = $dy / $dx;

	my @xends;
	my $intery;

	# handle the endpoints
	for my $xy ([$x0, $y0], [$x1, $y1]) {
		my ($x, $y) = @$xy;
		my $xend = round($x);
		my $yend = $y + $gradient * ($xend - $x);
		my $xgap = rfpart($x + 0.5);

		my $x_pixel = $xend;
		my $y_pixel = ipart($yend);
		push @xends, $x_pixel;

		$plot->($x_pixel, $y_pixel  , rfpart($yend) * $xgap);
		$plot->($x_pixel, $y_pixel+1,  fpart($yend) * $xgap);
		next if defined $intery;
		# first y-intersection for the main loop
		$intery = $yend + $gradient;
	}

	# main loop

	for my $x ( $xends[0] + 1 .. $xends[1] - 1 ) {
		$plot->($x, ipart ($intery),  rfpart($intery));
		$plot->($x, ipart ($intery)+1, fpart($intery));
		$intery += $gradient;
	}
}

if( $0 eq __FILE__ ) {
	drawLine( 0, 1, 10, 2 );
}
__END__


//You need to use these units
uses
  SysUtils,
  Dialogs,
  XMLIntf,
  XMLDoc;

//..............................................

//This function process the XML
function GetStudents(aXMLInput: string): string;
var
  XMLDoc: IXMLDocument;
  i: Integer;
begin
  //Creating the TXMLDocument instance
  XMLDoc:= TXMLDocument.Create(nil);

  //Loading8 the XML string
  XMLDoc.LoadFromXML(aXMLInput);

  //Parsing the xml document
  for i:=0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do
    Result:= Result + XMLDoc.DocumentElement.ChildNodes.Get(i).GetAttributeNS('Name', '') + #13#10;

  //Removing the trailing #13#10 characters
  Result:= Trim(Result);
end;

//..............................................

//Consuming code example (fragment)
var
  XMLInput: string;
begin
  XMLInput:= '<Students>' +
                '<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
                '<Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />' +
                '<Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />' +
                '<Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">' +
                  '<Pet Type="dog" Name="Rover" />' +
                '</Student>' +
                '<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />'+
              '</Students>';
  Showmessage(GetStudents(XMLInput));
end;


-module( xml_input ).

-export( [task/0] ).

-include_lib("xmerl/include/xmerl.hrl").

task() ->
    {XML, []} = xmerl_scan:string( xml(), [{encoding, "iso-10646-utf-1"}] ),
    Attributes = lists:flatten( [X || #xmlElement{name='Student', attributes=X} <- XML#xmlElement.content] ),
    [io:fwrite("~s~n", [X]) || #xmlAttribute{name='Name', value=X} <- Attributes].

xml() -> "<Students>
  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />
  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />
  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">
    <Pet Type=\"dog\" Name=\"Rover\" />
  </Student>
  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>".


--
-- demo\rosetta\XiaolinWuLine.exw
-- ==============================
--
--  Resize the window to show lines at any angle
--
--  For education/comparision purposes only: see demo\pGUI\aaline.exw
--  for a much shorter version, but "wrong algorithm" for the RC task.
--  Also note this blends with BACK rather than the actual pixel,
--  whereas aaline.exw does it properly.
--
with javascript_semantics   -- not really fair: pwa/p2js uses OpenGL
-- and does not draw bresenham lines anyway/ever, plus the next line
-- makes no difference whatsoever when running this in a browser.
constant USE_OPENGL = 0

constant TITLE = "Xiaolin Wu's line algorithm"

include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

bool wuline = true  -- space toggles, for comparison
                    -- when false, and with USE_OPENGL, lines are still smooth,
                    --  but a bit thicker - and therefore less "ropey".
                    -- when false, but without USE_OPENGL, it draws bresenham
                    --  lines (ie jagged, without anti-aliasing [desktop only]).

integer BACK = CD_PARCHMENT,
        LINE = CD_BLUE,
        {rB, gB, bB} = to_rgb(BACK),
        {rL, gL, bL} = to_rgb(LINE)

procedure plot(atom x, y, c, bool steep=false)
--  plot the pixel at (x, y) with brightness c (where 0 <= c <= 1)
    if steep then {x,y} = {y,x} end if
    atom C = 1-c
    c = rgb(rL*c+rB*C,gL*c+gB*C,bL*c+bB*C)
    cdCanvasPixel(cddbuffer, x, y, c)
end procedure

procedure plot2(atom x, y, f, xgap, bool steep)
    plot(x,y,(1-f)*xgap,steep)
    plot(x,y+1,(f)*xgap,steep)
end procedure

function fpart(atom x)
    return x-floor(x)   -- fractional part of x
end function

procedure wu_line(atom x0,y0,x1,y1)
    bool steep := abs(y1 - y0) > abs(x1 - x0)
    if steep then
        {x0, y0, x1, y1} = {y0, x0, y1, x1}
    end if
    if x0>x1 then
        {x0, x1, y0, y1} = {x1, x0, y1, y0}
    end if

    atom dx := x1 - x0,
         dy := y1 - y0,
         gradient := iff(dx=0? 1 : dy / dx)

    -- handle first endpoint
    atom xend := round(x0),
         yend := y0 + gradient * (xend - x0),
         xgap := 1 - fpart(x0 + 0.5),
         xpxl1 := xend, -- this will be used in the main loop
         ypxl1 := floor(yend)
    plot2(xpxl1, ypxl1, fpart(yend), xgap, steep)
    atom intery := yend + gradient -- first y-intersection for the main loop

    -- handle second endpoint
    xend := round(x1)
    yend := y1 + gradient * (xend - x1)
    xgap := fpart(x1 + 0.5)
    atom xpxl2 := xend, -- this will be used in the main loop
         ypxl2 := floor(yend)
    plot2(xpxl2, ypxl2, fpart(yend), xgap, steep)

    -- main loop
    for x = xpxl1+1 to xpxl2-1 do
        plot2(x, floor(intery), fpart(intery), 1, steep)
        intery += gradient
    end for
end procedure

procedure plot_4_points(integer cx, cy, x, y, atom f, angle1=0, angle2=360, angle=0)
integer x1 = cx+x, x2 = cx-x,
        y1 = cy+y, y2 = cy-y
    if angle<0 or angle>90.01 then ?9/0 end if
    if      angle >=angle1 and      angle <=angle2 then plot(x1, y1, f) end if  -- top right
    if (180-angle)>=angle1 and (180-angle)<=angle2 then plot(x2, y1, f) end if  -- top left
    if (180+angle)>=angle1 and (180+angle)<=angle2 then plot(x2, y2, f) end if  -- btm left
    if (360-angle)>=angle1 and (360-angle)<=angle2 then plot(x1, y2, f) end if  -- btm right
end procedure

procedure wu_ellipse(atom cx, cy, w, h, angle1=0, angle2=360)
--
-- (draws a circle when w=h) credit:
-- https://yellowsplash.wordpress.com/2009/10/23/fast-antialiased-circles-and-ellipses-from-xiaolin-wus-concepts/
--
    if w<=0 or h<=0 then return end if
    cx = round(cx)
    cy = round(cy)
    w = round(w)
    h = round(h)
    angle1 = mod(angle1,360)
    angle2 = mod(angle2,360)

    -- Match cdCanvasArc/Sector angles:
    angle1 = atan2((h/2)*sin(angle1*CD_DEG2RAD), (w/2)*cos(angle1*CD_DEG2RAD))*CD_RAD2DEG
    angle2 = atan2((h/2)*sin(angle2*CD_DEG2RAD), (w/2)*cos(angle2*CD_DEG2RAD))*CD_RAD2DEG

    if angle2<=angle1 then angle2 += 360 end if

    atom a := w/2, asq := a*a,
         b := h/2, bsq := b*b,
         sqab = sqrt(asq+bsq),
         ffd = round(asq/sqab), -- forty-five-degree coord
         xj, yj, frc, flr, angle

    -- draw top right, and the 3 mirrors of it in horizontal fashion
    --  (ie 90 to 45 degrees for a circle)

    for xi=0 to ffd do
        yj := b*sqrt(1-xi*xi/asq)   -- real y value
        frc := fpart(yj)
        flr := floor(yj)
        angle := iff(xi=0?90:arctan(yj/xi)*CD_RAD2DEG)
        plot_4_points(cx, cy, xi, flr, 1-frc, angle1, angle2, angle)
        plot_4_points(cx, cy, xi, flr+1, frc, angle1, angle2, angle)
    end for

    -- switch from horizontal to vertial mode for the rest, ditto 3
    -- (ie 45..0 degrees for a circle)

    ffd = round(bsq/sqab)
    for yi=0 to ffd do
        xj := a*sqrt(1-yi*yi/bsq)   -- real x value
        frc := fpart(xj)
        flr := floor(xj)
        angle = iff(xj=0?0:arctan(yi/xj)*CD_RAD2DEG)
        plot_4_points (cx, cy, flr, yi, 1-frc, angle1, angle2, angle)
        plot_4_points (cx, cy, flr+1, yi, frc, angle1, angle2, angle)
    end for

end procedure

function redraw_cb(Ihandle /*ih*/)
    integer {w, h} = sq_sub(IupGetIntInt(canvas, "DRAWSIZE"),10)
    cdCanvasActivate(cddbuffer)
    cdCanvasClear(cddbuffer)
    if platform()=JS then
        cdCanvasSetLineWidth(cddbuffer,iff(wuline?1:4))
    end if
if wuline then
    wu_line(0,0,200,200)
    wu_line(w,0,200,200)
    wu_line(0,h,200,200)
    wu_line(w,h,200,200)
else
    cdCanvasLine(cddbuffer,0,0,200,200)
    cdCanvasLine(cddbuffer,w,0,200,200)
    cdCanvasLine(cddbuffer,0,h,200,200)
    cdCanvasLine(cddbuffer,w,h,200,200)
end if

if wuline then
    wu_ellipse(200,200,200,200)
--  cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360)
    wu_ellipse(200,200,300,100)
--  wu_ellipse(200,200,300,100,15,85)
--  cdCanvasArc(cddbuffer, 205, 205, 300, 100, 15, 85)
else
    cdCanvasArc(cddbuffer, 200, 200, 200, 200, 0, 360)
--  cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360)
    cdCanvasArc(cddbuffer, 200, 200, 300, 100, 0, 360)
end if
--test - it works (much better) if you draw the polygon /after/ the lines!!
--  cdCanvasBegin(cddbuffer,CD_FILL)
--  cdCanvasVertex(cddbuffer,w,h)
--  cdCanvasVertex(cddbuffer,0,h)
--  cdCanvasVertex(cddbuffer,200,200)
--  cdCanvasEnd(cddbuffer)
--/test
    cdCanvasFlush(cddbuffer)
    if USE_OPENGL then
        if platform()!=JS then
            IupGLSwapBuffers(canvas)
        end if
    end if
    return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
    if USE_OPENGL then
        IupGLMakeCurrent(canvas)
        if platform()=JS then
            cdcanvas = cdCreateCanvas(CD_IUP, canvas)
        else
            atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
            cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res})
        end if
        cddbuffer = cdcanvas
    else
        cdcanvas = cdCreateCanvas(CD_IUP, ih)
        cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    end if
    cdCanvasSetBackground(cddbuffer, BACK)
    cdCanvasSetForeground(cddbuffer, LINE)
    return IUP_DEFAULT
end function

function canvas_resize_cb(Ihandle /*canvas*/)
    if USE_OPENGL then
        integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE")
        atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
        cdCanvasSetAttribute(cdcanvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res})
    end if
    return IUP_DEFAULT
end function

procedure set_title()
    string title = TITLE
    if USE_OPENGL then
        title &= iff(wuline?" (wu_line)":" (opengl)")
    else
        title &= iff(wuline?" (anti-aliased)":" (bresenham)")
    end if
    IupSetStrAttribute(dlg,"TITLE",title)
end procedure

function key_cb(Ihandle /*ih*/, atom c)
    if c=K_ESC then return IUP_CLOSE end if
    if c=' ' then
        wuline = not wuline
        set_title()
        IupRedraw(canvas)
    end if
    return IUP_CONTINUE
end function

procedure main()
    IupOpen()
    if USE_OPENGL then
        canvas = IupGLCanvas()
        IupSetAttribute(canvas, "BUFFER", "DOUBLE")
    else
        canvas = IupCanvas()
    end if

    IupSetAttribute(canvas, "RASTERSIZE", "640x480")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "ACTION", Icallback("redraw_cb"),
                             "RESIZE_CB", Icallback("canvas_resize_cb")})
    dlg = IupDialog(canvas)
    set_title()
    IupSetCallback(dlg, "KEY_CB", Icallback("key_cb"))
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


with Ada.Text_IO;                       use Ada.Text_IO;
with Ada.Float_Text_IO;                 use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;

procedure Write_Float_Array is
   type Float_Array is array (1..4) of Float;
   procedure Write_Columns
             (  File   : File_Type;
                X      : Float_Array;
                Y      : Float_Array;
                X_Pres : Natural := 3;
                Y_Pres : Natural := 5
             ) is
   begin
      for I in Float_Array'range loop
         Put (File => File, Item => X(I), Fore => 1, Aft => X_Pres - 1);
         Put (File, " ");
         Put (File => File, Item => Y(I), Fore => 1, Aft => Y_Pres - 1);
         New_Line (File);
      end loop;
   end Write_Columns;

   File : File_Type;
   X : Float_Array := (1.0, 2.0, 3.0, 1.0e11);
   Y : Float_Array;
begin
   Put ("Tell us the file name to write:");
   Create (File, Out_File, Get_Line);
   for I in Float_Array'range loop
      Y(I) := Sqrt (X (I));
   end loop;
   Write_columns (File, X, Y);
   Close (File);
end Write_Float_Array;


open System.IO
open System.Xml
open System.Xml.Linq

let xn s = XName.Get(s)

let xd = XDocument.Load(new StringReader("""
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"""))  // "

[<EntryPoint>]
let main argv =
    let students = xd.Descendants <| xn "Student"
    let names = students.Attributes <| xn "Name"
    Seq.iter ((fun (a : XAttribute) ->  a.Value) >> printfn "%s") names
    0


USING: io multiline sequences xml xml.data xml.traversal ;

: print-student-names ( string -- )
    string>xml "Student" tags-named [ "Name" attr print ] each ;

[[ <Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]] print-student-names


using xml

class XmlInput
{
  public static Void main ()
  {
    // create the XML parser
    parser := XParser(File("sample-xml.xml".toUri).in)
    // parse the document, creating an XML document
    XDoc doc := parser.parseDoc
    // walk through each child element from the root of the document
    doc.root.elems.each |elem|
    {
      // printing the Name attribute of all Students
      if (elem.name == "Student") { echo (elem.get("Name")) }
    }
  }
}


include ffl/est.fs
include ffl/str.fs
include ffl/xis.fs

\ Build input string
str-create xmlstr
: x+ xmlstr str-append-string ;

s\" <Students>\n" x+
s\" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" x+
s\" <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"  x+
s\" <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n" x+
s\" <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"   x+
s\" <Pet Type=\"dog\" Name=\"Rover\" />\n" x+
s\" </Student>\n" x+
s\" <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n" x+
s\" </Students>\n" x+

\ Setup xml parser
xis-create xmlparser
xmlstr str-get xmlparser xis-set-string

\ Parse the xml
: xmlparse
  BEGIN
    xmlparser xis-read  dup xis.error <> over xis.done <> AND
  WHILE
    dup xis.start-tag = over xis.empty-element = OR IF
      drop
      s" Student" compare 0= IF
        0 ?DO
          2swap s" Name" compare 0= IF
            type cr
          ELSE
            2drop
          THEN
        LOOP
      ELSE
        xis+remove-attribute-parameters
      THEN
    ELSE
      xis+remove-read-parameters
    THEN
  REPEAT
  drop
;

xmlparse


(scl 2)

(de plot (Img X Y C)
   (set (nth Img (*/ Y 1.0) (*/ X 1.0)) (- 100 C)) )

(de ipart (X)
   (* 1.0 (/ X 1.0)) )

(de iround (X)
   (ipart (+ X 0.5)) )

(de fpart (X)
   (% X 1.0) )

(de rfpart (X)
   (- 1.0 (fpart X)) )

(de xiaolin (Img X1 Y1 X2 Y2)
   (let (DX (- X2 X1)  DY (- Y2 Y1))
      (use (Grad Xend Yend Xgap Xpxl1 Ypxl1 Xpxl2 Ypxl2 Intery)
         (when (> (abs DY) (abs DX))
            (xchg 'X1 'Y1  'X2 'Y2) )
         (when (> X1 X2)
            (xchg 'X1 'X2  'Y1 'Y2) )
         (setq
            Grad (*/ DY 1.0 DX)
            Xend (iround X1)
            Yend (+ Y1 (*/ Grad (- Xend X1) 1.0))
            Xgap (rfpart (+ X1 0.5))
            Xpxl1 Xend
            Ypxl1 (ipart Yend) )
         (plot Img Xpxl1 Ypxl1 (*/ (rfpart Yend) Xgap 1.0))
         (plot Img Xpxl1 (+ 1.0 Ypxl1) (*/ (fpart Yend) Xgap 1.0))
         (setq
            Intery (+ Yend Grad)
            Xend (iround X2)
            Yend (+ Y2 (*/ Grad (- Xend X2) 1.0))
            Xgap (fpart (+ X2 0.5))
            Xpxl2 Xend
            Ypxl2 (ipart Yend) )
         (plot Img Xpxl2 Ypxl2 (*/ (rfpart Yend) Xgap 1.0))
         (plot Img Xpxl2 (+ 1.0 Ypxl2) (*/ (fpart Yend) Xgap 1.0))
         (for (X (+ Xpxl1 1.0)  (>= (- Xpxl2 1.0) X)  (+ X 1.0))
            (plot Img X (ipart Intery) (rfpart Intery))
            (plot Img X (+ 1.0 (ipart Intery)) (fpart Intery))
            (inc 'Intery Grad) ) ) ) )

(let Img (make (do 90 (link (need 120 99))))       # Create image 120 x 90
   (xiaolin Img 10.0 10.0 110.0 80.0)              # Draw lines
   (xiaolin Img 10.0 10.0 110.0 45.0)
   (xiaolin Img 10.0 80.0 110.0 45.0)
   (xiaolin Img 10.0 80.0 110.0 10.0)
   (out "img.pgm"                                  # Write to bitmap file
      (prinl "P2")
      (prinl 120 " " 90)
      (prinl 100)
      (for Y Img (apply printsp Y)) ) )


Macro PlotB(x, y, Color, b)
  Plot(x, y, RGB(Red(Color) * (b), Green(Color) * (b), Blue(Color) * (b)))
EndMacro

Procedure.f fracPart(x.f)
  ProcedureReturn x - Int(x)
EndProcedure

Procedure.f invFracPart(x.f)
  ProcedureReturn 1.0 - fracPart(x)
EndProcedure

Procedure drawAntiAliasedLine(x1.f, y1.f, x2.f, y2.f, color)
  Protected.f dx, dy, xend, yend, grad, yf, xgap, ix1, iy1, ix2, iy2
  Protected x

  dx = x2 - x1
  dy = y2 - y1
  If Abs(dx) < Abs(dy)
    Swap x1, y1
    Swap x2, y2
    Swap dx, dy
  EndIf

  If x2 < x1
    Swap x1, x2
    Swap y1, y2
  EndIf

  grad = dy / dx

  ;handle first endpoint
  xend = Round(x1, #pb_round_nearest)
  yend = y1 + grad * (xend - x1)
  xgap = invFracPart(x1 + 0.5)
  ix1 = xend  ;this will be used in the MAIN loop
  iy1 = Int(yend)
  PlotB(ix1, iy1, color, invFracPart(yend) * xgap)
  PlotB(ix1, iy1 + 1, color, fracPart(yend) * xgap)
  yf = yend + grad ;first y-intersection for the MAIN loop

  ;handle second endpoint
  xend = Round(x2, #pb_round_nearest)
  yend = y2 + grad * (xend - x2)
  xgap = fracPart(x2 + 0.5)
  ix2 = xend  ;this will be used in the MAIN loop
  iy2 = Int(yend)
  PlotB(ix2, iy2, color, invFracPart(yend) * xgap)
  PlotB(ix2, iy2 + 1, color, fracPart(yend) * xgap)
  ;MAIN loop
  For x = ix1 + 1 To ix2 - 1
    PlotB(x, Int(yf), color, invFracPart(yf))
    PlotB(x, Int(yf) + 1, color, fracPart(yf))
    yf + grad
  Next
EndProcedure

Define w = 200, h = 200, img = 1
CreateImage(img, w, h) ;img is internal id of the image

OpenWindow(0, 0, 0, w, h,"Xiaolin Wu's line algorithm", #PB_Window_SystemMenu)

StartDrawing(ImageOutput(img))
  drawAntiAliasedLine(80,20, 130,80, RGB(255, 0, 0))
StopDrawing()

ImageGadget(0, 0, 0, w, h, ImageID(img))

Define event
Repeat
  event = WaitWindowEvent()
Until event = #PB_Event_CloseWindow


PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: (
  FILE f;
  INT errno = open(f, filename, stand out channel);
  IF errno NE 0 THEN stop FI;
  FOR i TO UPB x DO
    # FORMAT := IF the absolute exponent is small enough, THEN use fixed ELSE use float FI; #
    FORMAT repr x := ( ABS log(x[i])<x width | $g(-x width,x width-2)$ | $g(-x width,x width-4,-1)$ ),
           repr y := ( ABS log(y[i])<y width | $g(-y width,y width-2)$ | $g(-y width,y width-4,-1)$ );
    putf(f, (repr x, x[i], $" "$, repr y, y[i], $l$))
  OD;
  close(f)
);
# Example usage: #
test:(
  []REAL x = (1, 2, 3, 1e11);
  [UPB x]REAL y; FOR i TO UPB x DO y[i]:=sqrt(x[i]) OD;
  printf(($"x before:"$, $xg$, x, $l$));
  printf(($"y before:"$, $xg$, y, $l$));
  writedat("sqrt.dat", x, y, 3+2, 5+2);

  printf($"After:"l$);
  FILE sqrt dat;
  INT errno = open(sqrt dat, "sqrt.dat", stand in channel);
  IF errno NE 0 THEN stop FI;
  on logical file end(sqrt dat, (REF FILE sqrt dat)BOOL: stop);
  TO UPB x DO
    STRING line;
    get(sqrt dat, (line, new line));
    print((line,new line))
  OD
)


#include <flow.h>

DEF-MAIN(argv,argc)

   VOID( x ), MSET( y, f )

   MEM(1,2,3,1.0e11), APND-LST(x), SET( y, x )
   SET-ROUND(5), SQRT(y), MOVE-TO(y)
   UNSET-ROUND

   CAT-COLS( f, y, x )
   TOK-SEP( TAB ), SAVE-MAT(f, "filename.txt" )
END


program tixi_rosetta
  use tixi
  implicit none
  integer :: i
  character (len=100) :: xml_file_name
  integer :: handle
  integer :: error
  character(len=100) :: name, xml_attr
  xml_file_name = 'rosetta.xml'

  call tixi_open_document( xml_file_name, handle, error )
  i = 1
  do
      xml_attr = '/Students/Student['//int2char(i)//']'
      call tixi_get_text_attribute( handle, xml_attr,'Name', name, error )
      if(error /= 0) exit
      write(*,*) name
      i = i + 1
  enddo

  call tixi_close_document( handle, error )

  contains

  function int2char(i) result(res)
    character(:),allocatable :: res
    integer,intent(in) :: i
    character(range(i)+2) :: tmp
    write(tmp,'(i0)') i
    res = trim(tmp)
  end function int2char

end program tixi_rosetta


package main

import (
    "encoding/xml"
    "fmt"
)

const XML_Data = `
<Students>
   <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
   <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
   <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
   <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
      <Pet Type="dog" Name="Rover" />
   </Student>
   <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
`

type Students struct {
    Student []Student
}

type Student struct {
    Name string `xml:",attr"`
    //  Gender      string `xml:",attr"`
    //  DateOfBirth string `xml:",attr"`
    //  Pets        []Pet  `xml:"Pet"`
}

type Pet struct {
    Type string `xml:",attr"`
    Name string `xml:",attr"`
}

// xml.Unmarshal quietly skips well formed input with no corresponding
// member in the output data structure.  With Gender, DateOfBirth, and
// Pets commented out of the Student struct, as above, Student contains
// only Name, and this is the only value extracted from the input XML_Data.
func main() {
    var data Students
    err := xml.Unmarshal([]byte(XML_Data), &data)
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, s := range data.Student {
        fmt.Println(s.Name)
    }
}


"""Script demonstrating drawing of anti-aliased lines using Xiaolin Wu's line
algorithm

usage: python xiaolinwu.py [output-file]

"""
from __future__ import division
import sys

from PIL import Image

def _fpart(x):
    return x - int(x)

def _rfpart(x):
    return 1 - _fpart(x)

def putpixel(img, xy, color, alpha=1):
    """
    Paints color over the background at the point xy in img.
    Use alpha for blending. alpha=1 means a completely opaque foreground.
    """
    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
    c = compose_color(img.getpixel(xy), color)
    img.putpixel(xy, c)

def draw_line(img, p1, p2, color):
    """Draws an anti-aliased line in img from p1 to p2 with the given color."""
    x1, y1 = p1
    x2, y2 = p2
    dx, dy = x2-x1, y2-y1
    steep = abs(dx) < abs(dy)
    p = lambda px, py: ((px,py), (py,px))[steep]

    if steep:
        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
    if x2 < x1:
        x1, x2, y1, y2 = x2, x1, y2, y1

    grad = dy/dx
    intery = y1 + _rfpart(x1) * grad
    def draw_endpoint(pt):
        x, y = pt
        xend = round(x)
        yend = y + grad * (xend - x)
        xgap = _rfpart(x + 0.5)
        px, py = int(xend), int(yend)
        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
        return px

    xstart = draw_endpoint(p(*p1)) + 1
    xend = draw_endpoint(p(*p2))

    for x in range(xstart, xend):
        y = int(intery)
        putpixel(img, p(x, y), color, _rfpart(intery))
        putpixel(img, p(x, y+1), color, _fpart(intery))
        intery += grad

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: python xiaolinwu.py [output-file]'
        sys.exit(-1)

    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    img = Image.new("RGB", (500,500), blue)
    for a in range(10, 431, 60):
        draw_line(img, (10, 10), (490, a), yellow)
        draw_line(img, (10, 10), (a, 490), yellow)
    draw_line(img, (10, 10), (490, 490), yellow)
    filename = sys.argv[1]
    img.save(filename)
    print 'image saved to', filename


x$ = "1 2 3 1e11"
x$ = explode(x$, " ")

f = freefile
open f, "filename.txt"

for i = 0 to x$[?]-1
	writeline f, int(x$[i]) + chr(9) + round(sqrt(x$[i]),4)
next i
close f


      DIM x(3), y(3)
      x() = 1, 2, 3, 1E11
      FOR i% = 0 TO 3
        y(i%) = SQR(x(i%))
      NEXT

      xprecision = 3
      yprecision = 5

      outfile% = OPENOUT("filename.txt")
      IF outfile%=0 ERROR 100, "Could not create file"

      FOR i% = 0 TO 3
        @% = &1000000 + (xprecision << 8)
        a$ = STR$(x(i%)) + CHR$(9)
        @% = &1000000 + (yprecision << 8)
        a$ += STR$(y(i%))
        PRINT #outfile%, a$ : BPUT #outfile%, 10
      NEXT

      CLOSE #outfile%


#include <stdio.h>
#include <math.h>

int main(int argc, char **argv) {

   float x[4] = {1,2,3,1e11}, y[4];
   int i = 0;
   FILE *filePtr;

   filePtr = fopen("floatArray","w");

   for (i = 0; i < 4; i++) {
      y[i] = sqrt(x[i]);
      fprintf(filePtr, "%.3g\t%.5g\n", x[i], y[i]);
   }

   return 0;
}


def input = """<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>"""

def students = new XmlParser().parseText(input)
students.each { println it.'@Name' }


import Data.Maybe
import Text.XML.Light

students="<Students>"++
        " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"++
        " <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />"++
        " <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\"/>"++
        " <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">"++
        "   <Pet Type=\"dog\" Name=\"Rover\" />  </Student>"++
        " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />"++
        "</Students>"

xmlRead elm name  = mapM_ putStrLn
      . concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm))
      . onlyElems.  parseXML


CHARACTER in*1000, out*100

READ(ClipBoard) in
EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)


#lang racket
(require 2htdp/image)

(define (plot img x y c)
  (define c*255 (exact-round (* (- 1 c) 255)))
  (place-image
   (rectangle 1 1 'solid (make-color c*255 c*255 c*255 255))
   x y img))

(define ipart exact-floor) ; assume that a "round-down" is what we want when -ve
;;; `round` is built in -- but we'll use exact round (and I'm not keen on over-binding round)

(define (fpart n) (- n (exact-floor n)))
(define (rfpart n) (- 1 (fpart n)))

(define (draw-line img x0 y0 x1 y1)
  (define (draw-line-steeped img x0 y0 x1 y1 steep?)
    (define (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?)
      (define dx (- x1 x0))
      (define dy (- y1 y0))
      (define gradient (/ dy dx))

      (define (handle-end-point img x y)
        (define xend (exact-round x))
        (define yend (+ y (* gradient (- xend x))))
        (define xgap (rfpart (+ x 0.5)))
        (define ypxl (ipart yend))
        (define intery (+ yend gradient))

        (case steep?
          [(#t)
           (define img* (plot img ypxl xend (* xgap (rfpart yend))))
           (values (plot img* (+ ypxl 1) xend (* xgap (fpart yend))) xend intery)]
          [(#f)
           (define img* (plot img xend ypxl (* xgap (rfpart yend))))
           (values (plot img* xend (+ ypxl 1) (* xgap (fpart yend))) xend intery)]))

      (define-values (img-with-l-endpoint xpl1 intery) (handle-end-point img x0 y0))
      (define-values (img-with-r-endpoint xpl2 _) (handle-end-point img-with-l-endpoint x1 y1))

      (for/fold ((img img-with-l-endpoint)  (y intery))
        ((x (in-range (+ xpl1 1) xpl2)))
        (define y-i (ipart y))
        (values
         (case steep?
           [(#t)
            (define img* (plot img y-i x (rfpart y)))
            (plot img* (+ 1 y-i) x (fpart y))]
           [(#f)
            (define img* (plot img x y-i (rfpart y)))
            (plot img* x (+ 1 y-i) (fpart y))])
         (+ y gradient))))

    (if (> x0 x1)
        (draw-line-steeped-l-to-r img x1 y1 x0 y0 steep?)
        (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?)))

  (define steep? (> (abs (- y1 y0)) (abs (- x1 x0))))
  (define-values (img* _)
    (if steep?
        (draw-line-steeped img y0 x0 y1 x1 steep?)
        (draw-line-steeped img x0 y0 x1 y1 steep?)))
  img*)

(define img-1
(beside
 (scale 3 (draw-line (empty-scene 150 100) 12 12 138 88))
 (above
  (scale 1 (draw-line (empty-scene 150 100) 12 50 138 50))
  (scale 1 (draw-line (empty-scene 150 100) 75 12 75 88))
  (scale 1 (draw-line (empty-scene 150 100) 12 88 138 12)))))

(define img-2
  (beside
 (scale 3 (draw-line (empty-scene 100 150) 12 12 88 138))
 (above (scale 1 (draw-line (empty-scene 100 150) 50 12 50 138))
        (scale 1 (draw-line (empty-scene 100 150) 12 75 88 75))
        (scale 1 (draw-line (empty-scene 100 150) 88 12 12 138)))))

img-1
img-2
(save-image img-1 "images/xiaolin-wu-racket-1.png")
(save-image img-2 "images/xiaolin-wu-racket-2.png")


sub plot(\x, \y, \c) { say "plot {x} {y} {c}" }

sub fpart(\x) { x - floor(x) }

sub draw-line(@a is copy, @b is copy) {
    my Bool \steep = abs(@b[1] - @a[1]) > abs(@b[0] - @a[0]);
    my $plot = &OUTER::plot;

    if steep {
	$plot = -> $y, $x, $c { plot($x, $y, $c) }
	@a.=reverse;
	@b.=reverse;
    }
    if @a[0] > @b[0] { my @t = @a; @a = @b; @b = @t }

    my (\x0,\y0) = @a;
    my (\x1,\y1) = @b;

    my \dx = x1 - x0;
    my \dy = y1 - y0;
    my \gradient = dy / dx;

    # handle first endpoint
    my \x-end1 = round(x0);
    my \y-end1 = y0 + gradient * (x-end1 - x0);
    my \x-gap1 = 1 - round(x0 + 0.5);

    my \x-pxl1 = x-end1;   # this will be used in the main loop
    my \y-pxl1 = floor(y-end1);
    my \c1 = fpart(y-end1) * x-gap1;

    $plot(x-pxl1, y-pxl1    , 1 - c1) unless c1 == 1;
    $plot(x-pxl1, y-pxl1 + 1, c1    ) unless c1 == 0;

    # handle second endpoint
    my \x-end2 = round(x1);
    my \y-end2 = y1 + gradient * (x-end2 - x1);
    my \x-gap2 = fpart(x1 + 0.5);

    my \x-pxl2 = x-end2; # this will be used in the main loop
    my \y-pxl2 = floor(y-end2);
    my \c2 = fpart(y-end2) * x-gap2;

    my \intery = y-end1 + gradient;

    # main loop
    for (x-pxl1 + 1 .. x-pxl2 - 1)
	Z
	(intery, intery + gradient ... *)
    -> (\x,\y) {
	my \c = fpart(y);
	$plot(x, floor(y)    , 1 - c) unless c == 1;
	$plot(x, floor(y) + 1, c    ) unless c == 0;
    }

    $plot(x-pxl2, y-pxl2    , 1 - c2) unless c2 == 1;
    $plot(x-pxl2, y-pxl2 + 1, c2    ) unless c2 == 0;
}

draw-line [0,1], [10,2];


using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var x = new double[] { 1, 2, 3, 1e11 };
        var y = new double[] { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 };

        int xprecision = 3;
        int yprecision = 5;

        string formatString = "{0:G" + xprecision + "}\t{1:G" + yprecision + "}";

        using (var outf = new StreamWriter("FloatArrayColumns.txt"))
            for (int i = 0; i < x.Length; i++)
                outf.WriteLine(formatString, x[i], y[i]);
    }
}


template<class InputIterator, class InputIterator2>
void writedat(const char* filename,
              InputIterator xbegin, InputIterator xend,
              InputIterator2 ybegin, InputIterator2 yend,
              int xprecision=3, int yprecision=5)
{
  std::ofstream f;
  f.exceptions(std::ofstream::failbit | std::ofstream::badbit);
  f.open(filename);
  for ( ; xbegin != xend and ybegin != yend; ++xbegin, ++ybegin)
    f << std::setprecision(xprecision) << *xbegin << '\t'
      << std::setprecision(yprecision) << *ybegin << '\n';
}


load'xml/sax'

saxclass 'Students'
startElement =: ([: smoutput 'Name' getAttribute~ [)^:('Student'-:])
cocurrent'base'

process_Students_ XML


import java.io.IOException;
import java.io.StringReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class StudentHandler extends DefaultHandler {
  public static void main(String[] args)throws Exception{
    String xml = "<Students>\n"+
    "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"+
    "<Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"+
    "<Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"+
    "<Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"+
    "  <Pet Type=\"dog\" Name=\"Rover\" />\n"+
    "</Student>\n"+
    "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"+
    "</Students>";
    StudentHandler handler = new StudentHandler();
    handler.parse(new InputSource(new StringReader(xml)));
  }

  public void parse(InputSource src) throws SAXException, IOException {
		XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(this);
    parser.parse(src);
  }

  @Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    //if there were text as part of the elements, we would deal with it here
    //by adding it to a StringBuffer, but we don't have to for this task
    super.characters(ch, start, length);
  }

  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    //this is where we would get the info from the StringBuffer if we had to,
    //but all we need is attributes
    super.endElement(uri, localName, qName);
  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if(qName.equals("Student")){
      System.out.println(attributes.getValue("Name"));
    }
  }
}


/*REXX program  plots/draws (ASCII)  a   line   using the   Xiaolin Wu  line algorithm. */
background= '·'                                  /*background character:  a middle-dot. */
    image.= background                           /*fill the array with middle-dots.     */
     plotC= '░▒▓█'                               /*characters used for plotting points. */
       EoE= 3000                                 /*EOE = End Of Earth,  er, ··· graph.  */
                     do j=-EoE  to +EoE          /*define the graph: lowest ──► highest.*/
                     image.j.0= '─'              /*define the graph's horizontal axis.  */
                     image.0.j= '│'              /*   "    "     "    verical      "    */
                     end   /*j*/
 image.0.0= '┼'                                  /*define the graph's axis origin (char)*/
parse arg xi yi xf yf .                          /*allow specifying the line-end points.*/
if xi=='' | xi==","  then xi= 1                  /*Not specified?  Then use the default.*/
if yi=='' | yi==","  then yi= 2                  /* "      "         "   "   "     "    */
if xf=='' | xf==","  then xf=11                  /* "      "         "   "   "     "    */
if yf=='' | yf==","  then yf=12                  /* "      "         "   "   "     "    */
minX=0;    minY=0                                /*use these as the limits for plotting.*/
maxX=0;    maxY=0                                /* "    "    "  "    "     "      "    */
call drawLine  xi, yi, xf, yf                    /*invoke subroutine and graph the line.*/
border=2                                         /*allow additional space (plot border).*/
minX=minX - border * 2;  maxX=maxX + border * 2  /*preserve screen's aspect ratio  {*2}.*/
minY=minY - border    ;  maxY=maxY + border
                              do     y=maxY  to minY  by -1;  $=      /*construct a row.*/
                                  do x=minX  to maxX;       $=$ || image.x.y;   end  /*x*/
                              say $              /*display the constructed row to term. */
                              end   /*y*/        /*graph is cropped by the MINs and MAXs*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
drawLine: parse arg x1,y1,x2,y2;      switchXY=0;        dx=x2-x1
                                                         dy=y2-y1
          if abs(dx)<abs(dy)  then parse value  x1 y1 x2 y2 dx dy  with  y1 x2 y2 x2 dy dx
          if x2<x1       then parse value  x1 x2 y1 y2   1   with   x2 x1 y2 y1   switchXY
          gradient=dy/dx
              xend=round(x1)             /*◄─────────────────1st endpoint.══════════════*/
              yend=y1 + gradient * (xend-x1);      xgap=1 - fpart(x1 + .5)
             xpx11=xend;       ypx11=floor(yend)
            intery=yend+gradient
          call plotXY  xpx11,  ypx11,    brite(1 - fpart(yend*xgap)), switchXY
          call plotXY  xpx11,  ypx11+1,  brite(    fpart(yend*xgap)), switchXY
              xend=round(x2)             /*◄─────────────────2nd endpoint.══════════════*/
              yend=y2 + gradient * (xend-x2);      xgap=    fpart(x2 + .5)
             xpx12=xend;       ypx12=floor(yend)
          call plotXY  xpx12,  ypx12  ,  brite(1 - fpart(yend*xgap)), switchXY
          call plotXY  xpx12,  ypx12+1,  brite(    fpart(yend*xgap)), switchXY

                do x=xpx11+1  to xpx12-1 /*◄═════════════════draw the line.═════════════*/
                !intery=floor(intery)
                call plotXY  x,  !intery  ,  brite(1 - fpart(intery)), switchXY
                call plotXY  x,  !intery+1,  brite(    fpart(intery)), switchXY
                intery=intery + gradient
                end   /*x*/
          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
brite:    return substr(background || plotC, 1 + round( abs( arg(1) ) * length(plotC)), 1)
floor:    parse arg #; _=trunc(#);  return _   -   (#<0) * (#\=_)
fpart:    parse arg #;              return abs(# - trunc(#) )
round:    return   format(arg(1), , word(arg(2) 0, 1) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
plotXY:   parse arg xx,yy,bc,switchYX;             if switchYX  then parse arg yy,xx
          image.xx.yy=bc;    minX=min(minX, xx);   maxX=max(maxX,xx)
                             minY=min(minY, yy);   maxY=max(maxY,yy);               return


       identification division.
       program-id. wr-float.
       environment division.
       input-output section.
       file-control.
           select report-file assign "float.txt"
               organization sequential.
       data division.
       file section.
       fd report-file
           report is floats.
       working-storage section.
       1 i binary pic 9(4).
       1 x-values comp-2.
        2 value 1.0.
        2 value 2.0.
        2 value 3.0.
        2 value 1.0e11.
       1 redefines x-values comp-2.
        2 x occurs 4.
       1 comp-2.
        2 y occurs 4.
       report section.
       rd floats.
       1 float-line type de.
        2 line plus 1.
         3 column 1 pic -9.99e+99 source x(i).
         2 column 12 pic -9.9999e+99 source y(i).
       procedure division.
       begin.
           open output report-file
           initiate floats
           perform varying i from 1 by 1
           until i > 4
               compute y(i) = function sqrt (x(i))
               generate float-line
           end-perform
           terminate floats
           close report-file
           stop run
           .
       end program wr-float.


(with-open-file (stream (make-pathname :name "filename") :direction :output)
    (let* ((x (make-array 4 :initial-contents '(1 2 3 1e11)))
              (y (map 'vector 'sqrt x))
              (xprecision 3)
              (yprecision 5)
              (fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision)))
        (map nil (lambda (a b)
                     (format stream fmt a b)) x y)))


var xmlstr = '<Students>' +
  '<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
  '<Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />' +
  '<Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />' +
  '<Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">' +
    '<Pet Type="dog" Name="Rover" />' +
  '</Student>' +
  '<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />' +
'</Students>';

if (window.DOMParser)
  {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(xmlstr,"text/xml");
  }
else // Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.loadXML(xmlstr);
  }

var students=xmlDoc.getElementsByTagName('Student');
for(var e=0; e<=students.length-1; e++) {
  console.log(students[e].attributes.Name.value);
}


using LightXML

let docstr = """<Students>
      <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
      <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
      <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
      <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
        <Pet Type="dog" Name="Rover" />
      </Student>
      <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
    </Students>"""

    doc = parse_string(docstr)
    xroot = root(doc)
    for elem in xroot["Student"]
        println(attribute(elem, "Name"))
    end
end


// version 1.1.3

import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
import java.io.StringReader
import org.w3c.dom.Node
import org.w3c.dom.Element

val xml =
"""
<Students>
    <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
    <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
    <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
    <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
        <Pet Type="dog" Name="Rover" />
    </Student>
    <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"""

fun main(args: Array<String>) {
    val dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val xmlInput = InputSource(StringReader(xml))
    val doc = dBuilder.parse(xmlInput)
    val nList = doc.getElementsByTagName("Student")
    for (i in 0 until nList.length) {
        val node = nList.item(i)
        if (node.nodeType == Node.ELEMENT_NODE) {
            val element = node as Element
            val name = element.getAttribute("Name")
            println(name)
        }
    }
}


def ipart(n); n.truncate; end
def fpart(n); n - ipart(n); end
def rfpart(n); 1.0 - fpart(n); end

class Pixmap
  def draw_line_antialised(p1, p2, colour)
    x1, y1 = p1.x, p1.y
    x2, y2 = p2.x, p2.y

    steep = (y2 - y1).abs > (x2 - x1).abs
    if steep
      x1, y1 = y1, x1
      x2, y2 = y2, x2
    end
    if x1 > x2
      x1, x2 = x2, x1
      y1, y2 = y2, y1
    end
    deltax = x2 - x1
    deltay = (y2 - y1).abs
    gradient = 1.0 * deltay / deltax

    # handle the first endpoint
    xend = x1.round
    yend = y1 + gradient * (xend - x1)
    xgap = rfpart(x1 + 0.5)
    xpxl1 = xend
    ypxl1 = ipart(yend)
    put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap)
    put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap)
    itery = yend + gradient

    # handle the second endpoint
    xend = x2.round
    yend = y2 + gradient * (xend - x2)
    xgap = rfpart(x2 + 0.5)
    xpxl2 = xend
    ypxl2 = ipart(yend)
    put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap)
    put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap)

    # in between
    (xpxl1 + 1).upto(xpxl2 - 1).each do |x|
      put_colour(x, ipart(itery), colour, steep, rfpart(itery))
      put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery))
      itery = itery + gradient
    end
  end

  def put_colour(x, y, colour, steep, c)
    x, y = y, x if steep
    self[x, y] = anti_alias(colour, self[x, y], c)
  end

  def anti_alias(new, old, ratio)
    blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round}
    RGBColour.new(*blended)
  end
end

bitmap = Pixmap.new(500, 500)
bitmap.fill(RGBColour::BLUE)
10.step(430, 60) do |a|
  bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW)
  bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW)
end
bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)


import std.file, std.conv, std.string;

void main() {
    auto x = [1.0, 2, 3, 1e11];
    auto y = [1.0, 1.4142135623730951,
              1.7320508075688772, 316227.76601683791];
    int xPrecision = 3,
        yPrecision = 5;

    string tmp;
    foreach (i, fx; x)
        tmp ~= format("%." ~ text(xPrecision) ~ "g      %." ~
                      text(yPrecision) ~ "g\r\n", fx, y[i]);

    write("float_array.txt", tmp);
}


program Write_float_arrays_to_a_text_file;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IoUtils;

function ToString(v: TArray<Double>): TArray<string>;
var
  fmt: TFormatSettings;
begin
  fmt := TFormatSettings.Create('en-US');
  SetLength(Result, length(v));

  for var i := 0 to High(v) do
    Result[i] := v[i].tostring(ffGeneral, 5, 3, fmt);
end;

function Merge(a, b: TArray<string>): TArray<string>;
begin
  SetLength(Result, length(a));
  for var i := 0 to High(a) do
    Result[i] := a[i] + ^I + b[i];
end;

var
  x, y: TArray<Double>;

begin
  x := [1, 2, 3, 1e11];
  y := [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791];

  TFile.WriteAllLines('FloatArrayColumns.txt', Merge(ToString(x), ToString(y)));
end.


// makes extracting attribute values easier
define xml_attrmap(in::xml_namedNodeMap_attr) => {
	local(out = map)
	with attr in #in
		do #out->insert(#attr->name = #attr->value)
	return #out
}

local(
	text = '<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
',
xml = xml(#text)
)

local(
	students	= #xml -> extract('//Student'),
	names		= array
)
with student in #students do {
	#names -> insert(xml_attrmap(#student -> attributes) -> find('Name'))
}
#names -> join('<br />')


q = QUOTE
r = RETURN
xml = "<Students>"&r&\
"  <Student Name="&q&"April"&q&" Gender="&q&"F"&q&" DateOfBirth="&q&"1989-01-02"&q&" />"&r&\
"  <Student Name="&q&"Bob"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1990-03-04"&q&" />"&r&\
"  <Student Name="&q&"Chad"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1991-05-06"&q&" />"&r&\
"  <Student Name="&q&"Dave"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1992-07-08"&q&">"&r&\
"    <Pet Type="&q&"dog"&q&" Name="&q&"Rover"&q&" />"&r&\
"  </Student>"&r&\
"  <Student DateOfBirth="&q&"1993-09-10"&q&" Gender="&q&"F"&q&" Name="&q&"Émily"&q&" />"&r&\
"</Students>"

parser = xtra("xmlparser").new()
parser.parseString(xml)
res = parser.makePropList()
repeat with c in res.child
  put c.attributes.name
end repeat


put revXMLCreateTree(fld "FieldXML",true,true,false) into currTree
put revXMLAttributeValues(currTree,"Students","Student","Name",return,-1)


require 'lxp'
data = [[<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]]

p = lxp.new({StartElement = function (parser, name, attr)
	if name == 'Student' and attr.Name then
		print(attr.Name)
	end
end})

p:parse(data)
p:close()


import java.awt.Color
import math.{floor => ipart, round, abs}

case class Point(x: Double, y: Double) {def swap = Point(y, x)}

def plotter(bm: RgbBitmap, c: Color)(x: Double, y: Double, v: Double) = {
  val X = round(x).toInt
  val Y = round(y).toInt
  val V = v.toFloat
  // tint the existing pixels
  val c1 = c.getRGBColorComponents(null)
  val c2 = bm.getPixel(X, Y).getRGBColorComponents(null)
  val c3 = (c1 zip c2).map{case (n, o) => n * V + o * (1 - V)}
  bm.setPixel(X, Y, new Color(c3(0), c3(1), c3(2)))
}

def drawLine(plotter: (Double,Double,Double) => _)(p1: Point, p2: Point) {
  def fpart(x: Double) = x - ipart(x)
  def rfpart(x: Double) = 1 - fpart(x)
  def avg(a: Float, b: Float) = (a + b) / 2

  val steep = abs(p2.y - p1.y) > abs(p2.x - p1.x)
  val (p3, p4) = if (steep) (p1.swap, p2.swap) else (p1, p2)
  val (a, b) = if (p3.x > p4.x) (p4, p3) else (p3, p4)
  val dx = b.x - a.x
  val dy = b.y - a.y
  val gradient = dy / dx
  var intery = 0.0

  def endpoint(xpxl: Double, yend: Double, xgap: Double) {
    val ypxl = ipart(yend)
    if (steep) {
      plotter(ypxl,   xpxl, rfpart(yend) * xgap)
      plotter(ypxl+1, xpxl,  fpart(yend) * xgap)
    } else {
      plotter(xpxl, ypxl  , rfpart(yend) * xgap)
      plotter(xpxl, ypxl+1,  fpart(yend) * xgap)
    }
  }

  // handle first endpoint
  var xpxl1 = round(a.x);
  {
    val yend = a.y + gradient * (xpxl1 - a.x)
    val xgap = rfpart(a.x + 0.5)
    endpoint(xpxl1, yend, xgap)
    intery = yend + gradient
  }

  // handle second endpoint
  val xpxl2 = round(b.x);
  {
    val yend = b.y + gradient * (xpxl2 - b.x)
    val xgap = fpart(b.x + 0.5)
    endpoint(xpxl2, yend, xgap)
  }

  // main loop
  for (x <- (xpxl1 + 1) to (xpxl2 - 1)) {
    if (steep) {
      plotter(ipart(intery)  , x, rfpart(intery))
      plotter(ipart(intery)+1, x,  fpart(intery))
    } else {
      plotter(x, ipart (intery),  rfpart(intery))
      plotter(x, ipart (intery)+1, fpart(intery))
    }
    intery = intery + gradient
  }
}


defmodule Write_float_arrays do
  def task(xs, ys, fname, precision\\[]) do
    xprecision = Keyword.get(precision, :x, 2)
    yprecision = Keyword.get(precision, :y, 3)
    format = "~.#{xprecision}g\t~.#{yprecision}g~n"
    File.open!(fname, [:write], fn file ->
      Enum.zip(xs, ys)
      |> Enum.each(fn {x, y} -> :io.fwrite file, format, [x, y] end)
    end)
  end
end

x = [1.0, 2.0, 3.0, 1.0e11]
y = for n <- x, do: :math.sqrt(n)
fname = "filename.txt"

Write_float_arrays.task(x, y, fname)
IO.puts File.read!(fname)

precision = [x: 3, y: 5]
Write_float_arrays.task(x, y, fname, precision)
IO.puts File.read!(fname)


-module( write_float_arrays ).

-export( [task/0, to_a_text_file/3, to_a_text_file/4] ).

task() ->
	File = "afile",
	Xs = [1.0, 2.0, 3.0, 1.0e11],
	Ys = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],
	Options = [{xprecision, 3}, {yprecision, 5}],
	to_a_text_file( File, Xs, Ys, Options ),
	{ok, Contents} = file:read_file( File ),
	io:fwrite( "File contents: ~p~n", [Contents] ).

to_a_text_file( File, Xs, Ys ) -> to_a_text_file( File, Xs, Ys, [] ).

to_a_text_file( File, Xs, Ys, Options ) ->
	Xprecision = proplists:get_value( xprecision, Options, 2 ),
	Yprecision = proplists:get_value( yprecision, Options, 2 ),
	Format = lists:flatten( io_lib:format("~~.~pg ~~.~pg~n", [Xprecision, Yprecision]) ),
	{ok, IO} = file:open( File, [write] ),
	[ok = io:fwrite( IO, Format, [X, Y]) || {X, Y} <- lists:zip( Xs, Ys)],
	file:close( IO ).


Module CheckIt {
      Const Enumerator=-4&
      xml$={<Students>
              <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
              <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
              <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
              <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
                <Pet Type="dog" Name="Rover" />
              </Student>
              <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
            </Students>
            }
      Declare Dom "Msxml2.DOMDocument"
      Method Dom, "LoadXML", xml$
      Method Dom, "getElementsByTagName", "Student" as Students

      With Students, Enumerator as Student
      While Student {
            Method Student, "getAttribute", "Name" as Student.Name$
            Print Student.Name$
      }
      Declare Student Nothing
      Declare Students Nothing
      Declare DOM Nothing
}
CheckIt


Column[Cases[Import["test.xml","XML"],Rule["Name", n_ ] -> n,Infinity]]


RootXML = com.mathworks.xml.XMLUtils.createDocument('Students');
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','April')
thisElement.setAttribute('Gender','F')
thisElement.setAttribute('DateOfBirth','1989-01-02')
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','Bob')
thisElement.setAttribute('Gender','M')
thisElement.setAttribute('DateOfBirth','1990-03-04')
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','Chad')
thisElement.setAttribute('Gender','M')
thisElement.setAttribute('DateOfBirth','1991-05-06')
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','Dave')
thisElement.setAttribute('Gender','M')
thisElement.setAttribute('DateOfBirth','1992-07-08')
node = RootXML.createElement('Pet');
node.setAttribute('Type','dog')
node.setAttribute('name','Rover')
thisElement.appendChild(node);
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','Émily')
thisElement.setAttribute('Gender','F')
thisElement.setAttribute('DateOfBirth','1993-09-10')
docRootNode.appendChild(thisElement);
clearvars -except RootXML

for I=0:1:RootXML.getElementsByTagName('Student').item(0).getAttributes.getLength-1
    if strcmp(RootXML.getElementsByTagName('Student').item(0).getAttributes.item(I).getName,'Name')
        tag=I;
        break
    end
end

for I=0:1:RootXML.getElementsByTagName('Student').getLength-1
    disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue)
end


func plot(x, y, c) {
    c && printf("plot %d %d %.1f\n", x, y, c);
}

func fpart(x) {
    x - int(x);
}

func rfpart(x) {
    1 - fpart(x);
}

func drawLine(x0, y0, x1, y1) {

    var p = plot;
    if (abs(y1 - y0) > abs(x1 - x0)) {
        p = {|arg| plot(arg[1, 0, 2]) };
        (x0, y0, x1, y1) = (y0, x0, y1, x1);
    }

    if (x0 > x1) {
        (x0, x1, y0, y1) = (x1, x0, y1, y0);
    }

    var dx = (x1 - x0);
    var dy = (y1 - y0);
    var gradient = (dy / dx);

    var xends = [];
    var intery;

    # handle the endpoints
    for x,y in [[x0, y0], [x1, y1]] {
        var xend = int(x + 0.5);
        var yend = (y + gradient*(xend-x));
        var xgap = rfpart(x + 0.5);

        var x_pixel = xend;
        var y_pixel = yend.int;
        xends << x_pixel;

        p.call(x_pixel, y_pixel  , rfpart(yend) * xgap);
        p.call(x_pixel, y_pixel+1,  fpart(yend) * xgap);
        defined(intery) && next;

        # first y-intersection for the main loop
        intery = (yend + gradient);
    }

    # main loop
    range(xends[0]+1, xends[1]-1).each { |x|
        p.call(x, intery.int,  rfpart(intery));
        p.call(x, intery.int+1, fpart(intery));
        intery += gradient;
    }
}

drawLine(0, 1, 10, 2);


[<EntryPoint>]
let main argv =
    let x = [ 1.; 2.; 3.; 1e11 ]
    let y = List.map System.Math.Sqrt x

    let xprecision = 3
    let yprecision = 5

    use file = System.IO.File.CreateText("float.dat")
    let line = sprintf "%.*g\t%.*g"
    List.iter2 (fun x y -> file.WriteLine (line xprecision x yprecision y)) x y
    0


create x  1e f, 2e       f, 3e       f, 1e11       f,
create y  1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f,

: main
  s" sqrt.txt" w/o open-file throw  to outfile-id

  4 0 do
    4 set-precision
    x i floats + [email protected] f.
    6 set-precision
    y i floats + [email protected] f. cr
  loop

  outfile-id  stdout to outfile-id
  close-file throw ;


/**
 XML/Input in Neko
 Tectonics:
   nekoc xml-input.neko
   neko xml-input | recode html
*/

/* Get the Neko XML parser function */
var parse_xml = $loader.loadprim("[email protected]_xml", 2);

/* Load the student.xml file as string */
var file_contents = $loader.loadprim("[email protected]_contents", 1);
var xmlString = file_contents("students.xml");

/* Build up a (very specific) XML event processor object */
/* Needs functions for xml, done, pcdata, cdata and comment */
var events = $new(null);
events.xml = function(name, attributes) {
  if name == "Student" {
    $print(attributes.Name, "\n");
  }
}
events.done = function() { }
events.pcdata = function(x) { }
events.cdata = function(x) { }
events.comment = function(x) { }

parse_xml(xmlString, events);

/* Entities are not converted, use external recode program for that */


(set 'xml-input "<Students>
  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />
  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />
  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">
    <Pet Type=\"dog\" Name=\"Rover\" />
  </Student>
  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>")

(set 'sexp (xml-parse xml-input))

(dolist (x (ref-all "Name" sexp))
	(if (= (length x) 6)
		(println (last (sexp (chop x))))))


import Darwin
// apply pixel of color at x,y with an OVER blend to the bitmap
public func pixel(color: Color, x: Int, y: Int) {
    let idx = x + y * self.width
    if idx >= 0 && idx < self.bitmap.count {
        self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color)
    }
}

// return the fractional part of a Double
func fpart(_ x: Double) -> Double {
    return modf(x).1
}

// reciprocal of the fractional part of a Double
func rfpart(_ x: Double) -> Double {
    return 1 - fpart(x)
}

// draw a 1px wide line using Xiolin Wu's antialiased line algorithm
public func smoothLine(_ p0: Point, _ p1: Point) {
    var x0 = p0.x, x1 = p1.x, y0 = p0.y, y1 = p1.y //swapable ptrs
    let steep = abs(y1 - y0) > abs(x1 - x0)
    if steep {
        swap(&x0, &y0)
        swap(&x1, &y1)
    }
    if x0 > x1 {
        swap(&x0, &x1)
        swap(&y0, &y1)
    }
    let dX = x1 - x0
    let dY = y1 - y0

    var gradient: Double
    if dX == 0.0 {
        gradient = 1.0
    }
    else {
        gradient = dY / dX
    }

    // handle endpoint 1
    var xend = round(x0)
    var yend = y0 + gradient * (xend - x0)
    var xgap = self.rfpart(x0 + 0.5)
    let xpxl1 = Int(xend)
    let ypxl1 = Int(yend)

    // first y-intersection for the main loop
    var intery = yend + gradient

    if steep {
        self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl1, y: xpxl1)
        self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl1 + 1, y: xpxl1)
    }
    else {
        self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl1, y: ypxl1)
        self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl1, y: ypxl1 + 1)
    }

    xend = round(x1)
    yend = y1 + gradient * (xend - x1)
    xgap = self.fpart(x1 + 0.5)
    let xpxl2 = Int(xend)
    let ypxl2 = Int(yend)

    // handle second endpoint
    if steep {
        self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl2, y: xpxl2)
        self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl2 + 1, y: xpxl2)
    }
    else {
        self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl2, y: ypxl2)
        self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl2, y: ypxl2 + 1)
    }

    // main loop
    if steep {
        for x in xpxl1+1..<xpxl2 {
            self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: Int(intery), y: x)
            self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: Int(intery) + 1, y:x)
            intery += gradient
        }
    }
    else {
        for x in xpxl1+1..<xpxl2 {
            self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: x, y: Int(intery))
            self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: x, y: Int(intery) + 1)
            intery += gradient
        }
    }
}


program writefloats
  implicit none

  real, dimension(10) :: a, sqrta
  integer :: i
  integer, parameter :: unit = 40

  a = (/ (i, i=1,10) /)
  sqrta = sqrt(a)

  open(unit, file="xydata.txt", status="new", action="write")
  call writexy(unit, a, sqrta)
  close(unit)

contains

  subroutine writexy(u, x, y)
    real, dimension(:), intent(in) :: x, y
    integer, intent(in) :: u

    integer :: i

    write(u, "(2F10.4)") (x(i), y(i), i=lbound(x,1), ubound(x,1))
  end subroutine writexy

end program writefloats


import xmlparser, xmltree, streams

let doc = newStringStream """<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>"""

for i in doc.parseXml.findAll "Student":
  echo i.attr "Name"


use XML;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      in := String->New();
      in->Append("<Students>");
      in->Append("<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />");
      in->Append("<Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />");
      in->Append("<Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />");
      in->Append("<Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">");
      in->Append("<Pet Type=\"dog\" Name=\"Rover\" />");
      in->Append("</Student>");
      in->Append("<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" /></Students>");

      parser := XmlParser->New(in);
      if(parser->Parse()) {
        root := parser->GetRoot();
        children := root->GetChildren("Student");
        each(i : children) {
          child : XMLElement := children->Get(i)->As(XMLElement);
          XMLElement->DecodeString(child->GetAttribute("Name"))->PrintLine();
        };
      };
    }
  }
}


package require Tcl 8.5
package require Tk

proc ::tcl::mathfunc::ipart x {expr {int($x)}}
proc ::tcl::mathfunc::fpart x {expr {$x - int($x)}}
proc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}}

proc drawAntialiasedLine {image colour p1 p2} {
    lassign $p1 x1 y1
    lassign $p2 x2 y2

    set steep [expr {abs($y2 - $y1) > abs($x2 - $x1)}]
    if {$steep} {
        lassign [list $x1 $y1] y1 x1
        lassign [list $x2 $y2] y2 x2
    }
    if {$x1 > $x2} {
        lassign [list $x1 $x2] x2 x1
        lassign [list $y1 $y2] y2 y1
    }
    set deltax [expr {$x2 - $x1}]
    set deltay [expr {abs($y2 - $y1)}]
    set gradient [expr {1.0 * $deltay / $deltax}]

    # handle the first endpoint
    set xend [expr {round($x1)}]
    set yend [expr {$y1 + $gradient * ($xend - $x1)}]
    set xgap [expr {rfpart($x1 + 0.5)}]
    set xpxl1 $xend
    set ypxl1 [expr {ipart($yend)}]
    plot $image $colour $steep $xpxl1 $ypxl1 [expr {rfpart($yend)*$xgap}]
    plot $image $colour $steep $xpxl1 [expr {$ypxl1+1}] [expr {fpart($yend)*$xgap}]
    set itery [expr {$yend + $gradient}]

    # handle the second endpoint
    set xend [expr {round($x2)}]
    set yend [expr {$y2 + $gradient * ($xend - $x2)}]
    set xgap [expr {rfpart($x2 + 0.5)}]
    set xpxl2 $xend
    set ypxl2 [expr {ipart($yend)}]
    plot $image $colour $steep $xpxl2 $ypxl2 [expr {rfpart($yend)*$xgap}]
    plot $image $colour $steep $xpxl2 [expr {$ypxl2+1}] [expr {fpart($yend)*$xgap}]

    for {set x [expr {$xpxl1 + 1}]} {$x < $xpxl2} {incr x} {
        plot $image $colour $steep $x [expr {ipart($itery)}] [expr {rfpart($itery)}]
        plot $image $colour $steep $x [expr {ipart($itery) + 1}] [expr {fpart($itery)}]
        set itery [expr {$itery + $gradient}]
    }
}

proc plot {image colour steep x y c} {
    set point [expr {$steep ? [list $y $x] : [list $x $y]}]
    set newColour [antialias $colour [getPixel $image $point] $c]
    setPixel $image $newColour $point
}

proc antialias {newColour oldColour c} {
    # get the new colour r,g,b
    if {[scan $newColour "#%2x%2x%2x%c" nr ng gb -] != 3} {
        scan [colour2rgb $newColour] "#%2x%2x%2x" nr ng nb
    }

    # get the current colour r,g,b
    scan $oldColour "#%2x%2x%2x" cr cg cb

    # blend the colours in the ratio defined by "c"
    foreach new [list $nr $ng $nb] curr [list $cr $cg $cb] {
        append blend [format {%02x} [expr {round($new*$c + $curr*(1.0-$c))}]]
    }
    return #$blend
}

proc colour2rgb {color_name} {
    foreach part [winfo rgb . $color_name] {
        append colour [format %02x [expr {$part >> 8}]]
    }
    return #$colour
}

set img [newImage 500 500]
fill $img blue
for {set a 10} {$a < 500} {incr a 60} {
    drawAntialiasedLine $img yellow {10 10} [list 490 $a]
    drawAntialiasedLine $img yellow {10 10} [list $a 490]
}
toplevel .wu
label .wu.l -image $img
pack .wu.l


package main

import (
    "fmt"
    "os"
)

var (
    x = []float64{1, 2, 3, 1e11}
    y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}

    xprecision = 3
    yprecision = 5
)

func main() {
    if len(x) != len(y) {
        fmt.Println("x, y different length")
        return
    }
    f, err := os.Create("filename")
    if err != nil {
        fmt.Println(err)
        return
    }
    for i := range x {
        fmt.Fprintf(f, "%.*e, %.*e\n", xprecision-1, x[i], yprecision-1, y[i])
    }
    f.Close()
}


import System.IO
import Text.Printf
import Control.Monad

writeDat filename x y xprec yprec =
  withFile filename WriteMode $ \h ->
     -- Haskell's printf doesn't support a precision given as an argument for some reason, so we insert it into the format manually:
     let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in
       zipWithM_ writeLine x y


REAL :: n=4, x(n), y(n)
CHARACTER :: outP = "Test.txt"

OPEN(FIle = outP)
x = (1, 2, 3, 1E11)
y = x ^ 0.5
DO i = 1, n
   WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i)
ENDDO


# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;
# #load "xml-light.cma" ;;

# let x = Xml.parse_string "
  <Students>
    <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />
    <Student Name='Bob' Gender='M'  DateOfBirth='1990-03-04' />
    <Student Name='Chad' Gender='M'  DateOfBirth='1991-05-06' />
    <Student Name='Dave' Gender='M'  DateOfBirth='1992-07-08'>
      <Pet Type='dog' Name='Rover' />
    </Student>
    <Student DateOfBirth='1993-09-10' Gender='F' Name='Émily' />
  </Students>"
  in
  Xml.iter (function
    Xml.Element ("Student", attrs, _) ->
       List.iter (function ("Name", name) -> print_endline name | _ -> ()) attrs
  | _ -> ()) x
  ;;
April
Bob
Chad
Dave
Émily
- : unit = ()


/** ==== Definitions ===== **/
DEFINE VARIABLE chXMLString AS LONGCHAR NO-UNDO.
DEFINE TEMP-TABLE ttStudent NO-UNDO XML-NODE-NAME 'Student'
    FIELD StudentName AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'Name'        LABEL 'Name'
    FIELD Gender      AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'Gender'      LABEL 'Gender'
    FIELD DateOfBirth AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'DateOfBirth' LABEL 'Date Of Birth'.
DEFINE DATASET dsStudents XML-NODE-NAME 'Students' FOR ttStudent.

/** ==== Main block ====**/

/** ASSIGN the XML string with the XML data.. **/
chXMLString = '<Students>~
                <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />~
                <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />~
                <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />~
                <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">~
                    <Pet Type="dog" Name="Rover" />~
                </Student>~
                <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />~
               </Students>'.

/** Read the string into the dataset...**/
DATASET dsStudents:READ-XML('LONGCHAR', chXMLString, 'EMPTY',?,?).

/** Loop thought each temp-table record to produce the results...**/
FOR EACH ttStudent:
    DISPLAY ttStudent.StudentName.
END.


DEF VAR lcc          AS LONGCHAR.
DEF VAR hxdoc        AS HANDLE.
DEF VAR hxstudents   AS HANDLE.
DEF VAR hxstudent    AS HANDLE.
DEF VAR hxname       AS HANDLE.
DEF VAR ii           AS INTEGER EXTENT 2.
DEF VAR cstudents    AS CHARACTER.

lcc   =  '<Students>'
      +  '<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />'
      +  '<Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />'
      +  '<Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />'
      +  '<Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">'
      +  '<Pet Type="dog" Name="Rover" />'
      +  '</Student>'
      +  '<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />'
      +  '</Students>'.

CREATE X-DOCUMENT hxdoc.
hxdoc:LOAD( 'LONGCHAR', lcc, FALSE ).

DO ii[1] = 1 TO hxdoc:NUM-CHILDREN:
   CREATE X-NODEREF hxstudents.
   hxdoc:GET-CHILD( hxstudents, ii[1] ).
   IF hxstudents:NAME = 'Students' THEN DO ii[2] = 1 TO hxstudents:NUM-CHILDREN:
      CREATE X-NODEREF hxstudent.
      hxstudents:GET-CHILD( hxstudent, ii[2] ).
      IF hxstudent:NAME = 'Student' THEN
         cstudents = cstudents + hxstudent:GET-ATTRIBUTE( 'Name' ) + '~n'.
      DELETE OBJECT hxstudent.
   END.
   DELETE OBJECT hxstudents.
END.
DELETE OBJECT hxdoc.

MESSAGE cstudents VIEW-AS ALERT-BOX.


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math

class XiaolinWu {
    construct new(width, height) {
        Window.title = "Xiaolin Wu's line algorithm"
        Window.resize(width, height)
        Canvas.resize(width, height)
    }

    init() {
        Canvas.cls(Color.white)
        drawLine(550, 170, 50, 435)
    }

    plot(x, y, c) {
        var col = Color.rgb(0, 0, 0, c * 255)
        x = ipart(x)
        y = ipart(y)
        Canvas.ellipsefill(x, y, x + 2, y + 2, col)
    }

    ipart(x) { x.truncate }

    fpart(x) { x.fraction }

    rfpart(x) { 1 - fpart(x) }

    drawLine(x0, y0, x1, y1) {
        var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
        if (steep) drawLine(y0, x0, y1, x1)
        if (x0 > x1) drawLine(x1, y1, x0, y0)
        var dx = x1 - x0
        var dy = y1 - y0
        var gradient = dy / dx

        // handle first endpoint
        var xend = Math.round(x0)
        var yend = y0 + gradient * (xend - x0)
        var xgap = rfpart(x0 + 0.5)
        var xpxl1 = xend  // this will be used in the main loop
        var ypxl1 = ipart(yend)

        if (steep) {
            plot(ypxl1, xpxl1, rfpart(yend) * xgap)
            plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)
        } else {
            plot(xpxl1, ypxl1, rfpart(yend) * xgap)
            plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)
        }

        // first y-intersection for the main loop
        var intery = yend + gradient

        // handle second endpoint
        xend = Math.round(x1)
        yend = y1 + gradient * (xend - x1)
        xgap = fpart(x1 + 0.5)
        var xpxl2 = xend  // this will be used in the main loop
        var ypxl2 = ipart(yend)

        if (steep) {
            plot(ypxl2, xpxl2, rfpart(yend) * xgap)
            plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)
        } else {
            plot(xpxl2, ypxl2, rfpart(yend) * xgap)
            plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)
        }

        // main loop
        var x = xpxl1 + 1
        while (x <= xpxl2 - 1) {
            if (steep) {
                plot(ipart(intery), x, rfpart(intery))
                plot(ipart(intery) + 1, x, fpart(intery))
            } else {
                plot(x, ipart(intery), rfpart(intery))
                plot(x, ipart(intery) + 1, fpart(intery))
            }
            intery = intery + gradient
            x = x + 1
        }
    }

    update() {}

    draw(alpha) {}
}

var Game = XiaolinWu.new(640, 640)


link printf

procedure main()
    every put(x := [], (1 to 3) | 1e11)
    every put(y := [], sqrt(!x))
    every fprintf(open("filename","w"),"%10.2e %10.4e\n", x[i := 1 to *x], y[i])
end


; the data:
x = [1,2,3,1e11]
y=sqrt(x)
xprecision=3
yprecision=5

; NOT how one would do things in IDL, but in the spirit of the task - the output format:
form = string(xprecision,yprecision,format='("(G0.",I0.0,",1x,G0.",I0.0,")")')

; file I/O:
openw,unit,"datafile.txt",/get
  for i = 1L, n_elements(x) do printf, unit, x[i-1],y[i-1],format=form
free_lun,unit


require 'files'            NB.  for fwrites

x          =.  1 2 3 1e11
y          =.  %: x        NB.  y is sqrt(x)

xprecision =.  3
yprecision =.  5

filename   =.  'whatever.txt'

data       =.  (0 j. xprecision,yprecision) ": x,.y

data fwrites filename


import java.io.*;

public class FloatArray {
    public static void writeDat(String filename, double[] x, double[] y,
                                int xprecision, int yprecision)
        throws IOException {
        assert x.length == y.length;
        PrintWriter out = new PrintWriter(filename);
        for (int i = 0; i < x.length; i++)
            out.printf("%."+xprecision+"g\t%."+yprecision+"g\n", x[i], y[i]);
        out.close();
    }

    public static void main(String[] args) {
        double[] x = {1, 2, 3, 1e11};
        double[] y = new double[x.length];
        for (int i = 0; i < x.length; i++)
            y[i] = Math.sqrt(x[i]);

        try {
            writeDat("sqrt.dat", x, y, 3, 5);
        } catch (IOException e) {
            System.err.println("writeDat: exception: "+e);
        }

        try {
            BufferedReader br = new BufferedReader(new FileReader("sqrt.dat"));
            String line;
            while ((line = br.readLine()) != null)
                System.out.println(line);
        } catch (IOException e) { }
    }
}


declare
  [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
  Parser = {New XMLParser.parser init}

  Data =
   "<Students>"
  #"  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"
  #"  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />"
  #"  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />"
  #"  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">"
  #"    <Pet Type=\"dog\" Name=\"Rover\" />"
  #"  </Student>"
  #"  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />"
  #"</Students>"

  fun {IsStudentElement X}
     case X of element(name:'Student' ...) then true
     else false
     end
  end

  fun {GetStudentName element(attributes:As ...)}
     [NameAttr] = {Filter As fun {$ attribute(name:N ...)} N == 'Name' end}
  in
     NameAttr.value
  end

  [StudentsDoc] = {Parser parseVS(Data $)}
  Students = {Filter StudentsDoc.children IsStudentElement}
  StudentNames = {Map Students GetStudentName}
in
  {ForAll StudentNames System.showInfo}


use utf8;
use XML::Simple;

my $ref = XMLin('<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>');

print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}});


with javascript_semantics
include builtins/xml.e
constant xml = """
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"""
sequence x = xml_parse(xml)

procedure traverse(sequence x)
    if x[XML_TAGNAME]="Student" then
        puts(1,xml_get_attribute(x,"Name"),false)
        puts(1,"\n")
    else
        x = x[XML_CONTENTS]
        if not string(x) then
            for i=1 to length(x) do
                traverse(x[i])
            end for
        end if
    end if
end procedure
traverse(x[XML_CONTENTS])


V games = [‘12’, ‘13’, ‘14’, ‘23’, ‘24’, ‘34’]
V results = ‘000000’

F numberToBase(=n, b)
   I n == 0
      R ‘0’
   V digits = ‘’
   L n != 0
      digits ‘’= String(Int(n % b))
      n I/= b
   R reversed(digits)

F nextResult()
   I :results == ‘222222’
      R 0B
   V res = Int(:results, radix' 3) + 1
   :results = numberToBase(res, 3).zfill(6)
   R 1B

V points = [[0] * 10] * 4
L
   V records = [0] * 4
   L(i) 0 .< games.len
      S results[i]
         ‘2’
            records[games[i][0].code - ‘1’.code] += 3
         ‘1’
            records[games[i][0].code - ‘1’.code]++
            records[games[i][1].code - ‘1’.code]++
         ‘0’
            records[games[i][1].code - ‘1’.code] += 3

   records.sort()
   L(i) 4
      points[i][records[i]]++

   I !nextResult()
      L.break

print(|‘POINTS       0    1    2    3    4    5    6    7    8    9
        -------------------------------------------------------------’)
V places = [‘1st’, ‘2nd’, ‘3rd’, ‘4th’]
L(i) 4
   print(places[i], end' ‘ place    ’)
   L(j) 10
      print(‘#<5’.format(points[3 - i][j]), end' ‘’)
   print()


bresline = false   // space toggles, for comparison

rB = 255 : gB = 255 : bB = 224
rL = 0 : gL = 0 : bL = 255

sub round(x)
    return int(x + .5)
end sub

sub plot(x, y, c, steep)
//  plot the pixel at (x, y) with brightness c (where 0 <= c <= 1)

    local t, C

    if steep then t = x : x = y : y = t end if
    C = 1 - c
    color rL * c + rB * C, gL * c + gB * C, bL * c + bB * C

    dot x, y
end sub

sub plot2(x, y, f, xgap, steep)
    plot(x, y, (1 - f) * xgap, steep)
    plot(x, y + 1, f * xgap, steep)
end sub

sub draw_line(x0, y0, x1, y1)
    local steep, t, dx, dy, gradient, xend, yend, xgap, xpxl1, ypxl1, xpxl2, ypxl2, intery

    if bresline then
        line x0, y0, x1, y1
        return
    end if
    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep then
        t = x0 : x0 = y0 : y0 = t
        t = x1 : x1 = y1 : y1 = t
    end if
    if x0 > x1 then
        t = x0 : x0 = x1 : x1 = t
        t = y0 : y0 = y1 : y1 = t
    end if

    dx = x1 - x0
    dy = y1 - y0
    if dx = 0 then
        gradient = 1
    else
        gradient = dy / dx
    end if

    // handle first endpoint
    xend = round(x0)
    yend = y0 + gradient * (xend - x0)
    xgap = 1 - frac(x0 + 0.5)
    xpxl1 = xend // this will be used in the main loop
    ypxl1 = int(yend)
    plot2(xpxl1, ypxl1, frac(yend), xgap, steep)
    intery = yend + gradient // first y-intersection for the main loop

    // handle second endpoint
    xend = round(x1)
    yend = y1 + gradient * (xend - x1)
    xgap = frac(x1 + 0.5)
    xpxl2 = xend // this will be used in the main loop
    ypxl2 = int(yend)
    plot2(xpxl2, ypxl2, frac(yend), xgap, steep)

    // main loop
    for x = xpxl1 + 1 to xpxl2 - 1
        plot2(x, int(intery), frac(intery), 1, steep)
        intery = intery + gradient
    next x
end sub

w = 640 : h = 480
open window w, h

color 0, 0, 255

draw_line(0, 0, 200, 200)
draw_line(w, 0, 200, 200)
draw_line(0, h, 200, 200)
draw_line(w, h, 200, 200)


DEFINE write-floats ==
['g 0] [formatf] enconcat map rollup
['g 0] [formatf] enconcat map swap zip
"filename" "w" fopen swap
[[fputchars] 9 fputch] step 10 fputch] step
fclose.


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val x = doubleArrayOf(1.0, 2.0, 3.0, 1e11)
    val y = doubleArrayOf(1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)
    val xp = 3
    val yp = 5
    val f = "%.${xp}g\t%.${yp}g\n"
    val writer = File("output.txt").writer()
    writer.use {
        for (i in 0 until x.size) {
            val s = f.format(x[i], y[i])
            writer.write(s)
        }
    }
}


<?php
$data = '<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>';
$xml = new XMLReader();
$xml->xml( $data );
while ( $xml->read() )
	if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' )
		echo $xml->getAttribute('Name') . "\n";
?>


(load "@lib/xm.l")

(mapcar
   '((L) (attr L 'Name))
   (body (in "file.xml" (xml))) )


string in = "<Students>\n"
            "  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
            "  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
            "  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
            "  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
            "    <Pet Type=\"dog\" Name=\"Rover\" />\n"
            "  </Student>\n"
            "  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
            "</Students>\n";

object s = Parser.XML.Tree.simple_parse_input(in);

array collect = ({});
s->walk_inorder(lambda(object node)
                {
                    if (node->get_tag_name() == "Student")
                        collect += ({ node->get_attributes()->Name });
                });
write("%{%s\n%}", collect);


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

// to supply to qsort
int compare(const void *a, const void *b) {
    int int_a = *((int *)a);
    int int_b = *((int *)b);
    return (int_a > int_b) - (int_a < int_b);
}

char results[7];
bool next_result() {
    char *ptr = results + 5;
    int num = 0;
    size_t i;

    // check if the space has been examined
    if (strcmp(results, "222222") == 0) {
        return false;
    }

    // translate the base 3 string back to a base 10 integer
    for (i = 0; results[i] != 0; i++) {
        int d = results[i] - '0';
        num = 3 * num + d;
    }

    // to the next value to process
    num++;

    // write the base 3 string (fixed width)
    while (num > 0) {
        int rem = num % 3;
        num /= 3;
        *ptr-- = rem + '0';
    }
    // zero fill the remainder
    while (ptr > results) {
        *ptr-- = '0';
    }

    return true;
}

char *games[6] = { "12", "13", "14", "23", "24", "34" };
char *places[4] = { "1st", "2nd", "3rd", "4th" };
int main() {
    int points[4][10];
    size_t i, j;

    strcpy(results, "000000");
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 10; j++) {
            points[i][j] = 0;
        }
    }

    do {
        int records[] = { 0, 0, 0, 0 };

        for (i = 0; i < 6; i++) {
            switch (results[i]) {
            case '2':
                records[games[i][0] - '1'] += 3;
                break;
            case '1':
                records[games[i][0] - '1']++;
                records[games[i][1] - '1']++;
                break;
            case '0':
                records[games[i][1] - '1'] += 3;
                break;
            default:
                break;
            }
        }

        qsort(records, 4, sizeof(int), compare);
        for (i = 0; i < 4; i++) {
            points[i][records[i]]++;
        }
    } while (next_result());

    printf("POINTS       0    1    2    3    4    5    6    7    8    9\n");
    printf("-----------------------------------------------------------\n");
    for (i = 0; i < 4; i++) {
        printf("%s place", places[i]);
        for (j = 0; j < 10; j++) {
            printf("%5d", points[3 - i][j]);
        }
        printf("\n");
    }

    return 0;
}


on saveFloatLists (filename, x, y, xprecision, yprecision)
  eol = numtochar(10) -- LF
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 2)
  cnt = x.count
  repeat with i = 1 to cnt
    the floatPrecision = xprecision
    fp.writeString(string(x[i])
    fp.writeString(TAB)
    the floatPrecision = yprecision
    fp.writeString(string(y[i])
    fp.writeString(eol)
  end repeat
  fp.closeFile()
end


filename = "file.txt"

x = { 1, 2, 3, 1e11 }
y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 };
xprecision = 3;
yprecision = 5;

fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n"

fp = io.open( filename, "w+" )

for i = 1, #x do
    fp:write( string.format( fstr, x[i], y[i] ) )
end

io.close( fp )


exportPrec[path_, data1_, data2_, prec1_, prec2_] :=
 Export[
   path,
   Transpose[{Map[ToString[NumberForm[#, prec2]] &, data2], Map[ToString[NumberForm[#, prec1]] &, data1]}],
   "Table"
]