    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Paint += Form1_Paint;
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            DrawTaijitu(g, new Point(50, 50), 200, true);
            DrawTaijitu(g, new Point(10, 10), 60, true);
        }

        private void DrawTaijitu(Graphics g, Point pt, int width, bool hasOutline)
        {
            g.FillPie(Brushes.Black, pt.X, pt.Y, width, width, 90, 180);
            g.FillPie(Brushes.White, pt.X, pt.Y, width, width, 270, 180);
            float headSize = Convert.ToSingle(width * 0.5);
            float headXPosition = Convert.ToSingle(pt.X + (width * 0.25));
            g.FillEllipse(Brushes.Black, headXPosition, Convert.ToSingle(pt.Y), headSize, headSize);
            g.FillEllipse(Brushes.White, headXPosition, Convert.ToSingle(pt.Y + (width * 0.5)), headSize, headSize);
            float headBlobSize = Convert.ToSingle(width * 0.125);
            float headBlobXPosition = Convert.ToSingle(pt.X + (width * 0.4375));
            g.FillEllipse(Brushes.White, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.1875)), headBlobSize, headBlobSize);
            g.FillEllipse(Brushes.Black, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.6875)), headBlobSize, headBlobSize);
            if (hasOutline) g.DrawEllipse(Pens.Black, pt.X, pt.Y, width, width);
        }
    }


taijitu = cluster is make
    rep = null

    circle = proc (x,y,c,r: int) returns (bool)
        return (r**2 >= (x/2)**2 + (y-c)**2)
    end circle

    pixel = proc (x,y,r: int) returns (char)
        if     circle(x,y,-r/2,r/6) then return('#')
        elseif circle(x,y, r/2,r/6) then return('.')
        elseif circle(x,y,-r/2,r/2) then return('.')
        elseif circle(x,y, r/2,r/2) then return('#')
        elseif circle(x,y,   0,  r) then
            if x<0 then return('.') else return('#') end
        end
        return(' ')
    end pixel

    make = proc (r: int) returns (string)
        chars: array[char] := array[char]$predict(1, r*r*2+r)
        for y: int in int$from_to(-r, r) do
            for x: int in int$from_to(-2*r, 2*r) do
                array[char]$addh(chars, pixel(x,y,r))
            end
            array[char]$addh(chars, '\n')
        end
        return (string$ac2s(chars))
    end make
end taijitu

start_up = proc ()
    po: stream := stream$primary_output()
    stream$putl(po, taijitu$make(4))
    stream$putl(po, taijitu$make(8))
end start_up


import std.stdio, std.algorithm, std.array, std.math, std.range,
       std.conv, std.typecons;

string yinYang(in int n) pure /*nothrow @safe*/ {
    enum : char { empty = ' ', white = '.', black = '#' }

    const radii = [1, 3, 6].map!(i => i * n).array;
    auto ranges = radii.map!(r => iota(-r, r + 1).array).array;
    alias V = Tuple!(int,"x", int,"y");
    V[][] squares, circles;
    squares = ranges.map!(r => cartesianProduct(r, r).map!V.array).array;

    foreach (sqrPoints, const radius; zip(squares, radii))
        circles ~= sqrPoints.filter!(p => p[].hypot <= radius).array;
    auto m = squares[$ - 1].zip(empty.repeat).assocArray;
    foreach (immutable p; circles[$ - 1])
        m[p] = black;
    foreach (immutable p; circles[$ - 1])
        if (p.x > 0)
            m[p] = white;
    foreach (immutable p; circles[$ - 2]) {
        m[V(p.x, p.y + 3 * n)] = black;
        m[V(p.x, p.y - 3 * n)] = white;
    }
    foreach (immutable p; circles[$ - 3]) {
        m[V(p.x, p.y + 3 * n)] = white;
        m[V(p.x, p.y - 3 * n)] = black;
    }
    return ranges[$ - 1]
           .map!(y => ranges[$ - 1].retro.map!(x => m[V(x, y)]).text)
           .join('\n');
}

void main() {
    2.yinYang.writeln;
    1.yinYang.writeln;
}


procedure DrawYinAndYang(Canv: TCanvas; R: TRect);
begin
  Canv.Brush.Color := clWhite;
  Canv.Pen.Color := clWhite;
  Canv.Pie(R.Left, R.Top, R.Right, R.Bottom,
    (R.Right + R.Left) div 2, R.Top, (R.Right + R.Left) div 2, R.Bottom);
  Canv.Brush.Color := clBlack;
  Canv.Pen.Color := clBlack;
  Canv.Pie(R.Left, R.Top, R.Right, R.Bottom,
    (R.Right + R.Left) div 2, R.Bottom, (R.Right + R.Left) div 2, R.Top);
  Canv.Brush.Color := clWhite;
  Canv.Pen.Color := clWhite;
  Canv.Ellipse((R.Right + 3 * R.Left) div 4, R.Top,
    (3 * R.Right + R.Left) div 4, (R.Top + R.Bottom) div 2);
  Canv.Brush.Color := clBlack;
  Canv.Pen.Color := clBlack;
  Canv.Ellipse((R.Right + 3 * R.Left) div 4, (R.Top + R.Bottom) div 2,
    (3 * R.Right + R.Left) div 4, R.Bottom);

  Canv.Brush.Color := clWhite;
  Canv.Pen.Color := clWhite;
  Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (11 * R.Bottom + 5 * R.Top) div 16,
    (9 * R.Right + 7 * R.Left) div 16, (13 * R.Bottom + 3 * R.Top) div 16);
  Canv.Brush.Color := clBlack;
  Canv.Pen.Color := clBlack;
  Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (3 * R.Bottom + 13 * R.Top) div 16,
    (9 * R.Right + 7 * R.Left) div 16, (5 * R.Bottom + 11 * R.Top) div 16);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ClientWidth := 400;
  ClientHeight := 400;
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  R: TRect;
begin
  R := ClientRect;
  Canvas.Brush.Color := clGray;
  Canvas.FillRect(R);

  InflateRect(R, -50, -50);
  OffsetRect(R, -40, -40);
  DrawYinAndYang(Canvas, R);

  InflateRect(R, -90, -90);
  OffsetRect(R, 170, 170);
  DrawYinAndYang(Canvas, R);
end;


type
   TColorFuncX = function (x : Integer) : Integer;

type
   TSquareBoard = class
      Scale : Integer;
      Pix : array of array of Integer;

      constructor Create(aScale : Integer);
      begin
         Scale := aScale;
         Pix := new Integer[aScale*12+1, aScale*12+1];
      end;

      method Print;
      begin
         var i, j : Integer;
         for i:=0 to Pix.High do begin
            for j:=0 to Pix.High do begin
               case Pix[j, i] of
                  1 : Print('.');
                  2 : Print('#');
               else
                  Print(' ');
               end;
            end;
            PrintLn('');
         end;
      end;

      method DrawCircle(cx, cy, cr : Integer; color : TColorFuncX);
      begin
         var rr := Sqr(cr*Scale);
         var x, y : Integer;
         for x := 0 to Pix.High do begin
            for y := 0 to Pix.High do begin
               if Sqr(x-cx*Scale)+Sqr(y-cy*Scale)<=rr then
                  Pix[x, y] := color(x);
            end;
         end;
      end;

      method ColorHalf(x : Integer) : Integer;
      begin
         if (x<6*Scale) then
            Result:=1
         else Result:=2;
      end;

      method ColorYin(x : Integer) : Integer;
      begin
         Result:=2;
      end;

      method ColorYang(x : Integer) : Integer;
      begin
         Result:=1;
      end;

      method YinYang;
      begin
         DrawCircle(6, 6, 6, ColorHalf);
         DrawCircle(6, 3, 3, ColorYang);
         DrawCircle(6, 9, 3, ColorYin);
         DrawCircle(6, 9, 1, ColorYang);
         DrawCircle(6, 3, 1, ColorYin);
      end;

   end;

var sq := new TSquareBoard(2);
sq.YinYang;
sq.Print;

sq := new TSquareBoard(1);
sq.YinYang;
sq.Print;


: circle ( x y r h -- f )
rot - dup *
rot   dup * +
swap  dup * swap
< invert
;

: pixel ( r x y -- r c )
2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then
2dup 4 pick 6 / 5 pick 2 /        circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then
2dup 4 pick 2 / 5 pick 2 /        circle if 2drop '#' exit then
2dup 4 pick     0 circle if
   drop 0< if '.' exit else '#' exit then
   then
2drop bl
;

: yinyang ( r -- )
dup dup 1+ swap -1 * do
   cr
   dup dup 2 * 1+ swap -2 * do
      I 2 / J  pixel emit
   loop
loop drop
;


package main

import (
    "fmt"
    "os"
    "text/template"
)

var tmpl = `<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="210" height="150">
<symbol id="yy" viewBox="0 0 200 200">
<circle stroke="black" stroke-width="2" fill="white"
    cx="100" cy="100" r="99" />
<path fill="black"
    d="M100 100 a49 49 0 0 0 0 -98
    v-1 a99 99 0 0 1 0 198
    v-1 a49 49 0 0 1 0 -98" />
<circle fill="black" cx="100" cy="51" r="17" />
<circle fill="white" cx="100" cy="149" r="17" />
</symbol>
{{range .}}<use xlink:href="#yy"
    x="{{.X}}" y="{{.Y}}" width="{{.Sz}}" height="{{.Sz}}"/>
{{end}}</svg>
`

// structure specifies position and size to draw symbol
type xysz struct {
    X, Y, Sz int
}

// example data to specify drawing the symbol twice,
// with different position and size.
var yys = []xysz{
    {20, 20, 100},
    {140, 30, 60},
}

func main() {
    xt := template.New("")
    template.Must(xt.Parse(tmpl))
    f, err := os.Create("yy.svg")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err := xt.Execute(f, yys); err != nil {
        fmt.Println(err)
    }
    f.Close()
}


{-# LANGUAGE NoMonomorphismRestriction #-}

import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine

yinyang = lw 0 $
          perim # lw 0.003 <>
          torus white black # xform id <>
          torus black white # xform negate <>
          clipBy perim base
  where perim      = arc 0 (360 :: Deg) # scale (1/2)
        torus c c' = circle (1/3) # fc c' <> circle 1 # fc c
        xform f    = translateY (f (1/4)) . scale (1/4)
        base       = rect (1/2) 1 # fc white ||| rect (1/2) 1 # fc black

main = defaultMain $
       pad 1.1 $
       beside (2,-1) yinyang (yinyang # scale (1/4))


link graphics

procedure main()
YinYang(100)
YinYang(40,"blue","yellow","white")
WDone()  # quit on Q/q
end

procedure YinYang(R,lhs,rhs,bg)   # draw YinYang with radius of R pixels and ...
/lhs := "white"                   # left hand side
/rhs := "black"                   # right hand side
/bg  := "grey"                    # background

wsize  := 2*(C := R + (margin := R/5))

W := WOpen("size="||wsize||","||wsize,"bg="||bg) | stop("Unable to open Window")
WAttrib(W,"fg="||lhs) & FillCircle(W,C,C,R,+dtor(90),dtor(180))        # main halves
WAttrib(W,"fg="||rhs) & FillCircle(W,C,C,R,-dtor(90),dtor(180))
WAttrib(W,"fg="||lhs) & FillCircle(W,C,C+R/2,R/2,-dtor(90),dtor(180))  # sub halves
WAttrib(W,"fg="||rhs) & FillCircle(W,C,C-R/2,R/2,dtor(90),dtor(180))
WAttrib(W,"fg="||lhs) & FillCircle(W,C,C-R/2,R/8)                      # dots
WAttrib(W,"fg="||rhs) & FillCircle(W,C,C+R/2,R/8)
end


yinyang=:3 :0
  radii=. y*1 3 6
  ranges=. i:each radii
  squares=. ,"0/~each ranges
  circles=. radii ([ >: +/"1&.:*:@])each squares
  cInds=. ({:radii) +each circles #&(,/)each squares

  M=. ' *.' {~  circles (*  1 + 0 >: {:"1)&(_1&{::) squares
  offset=. 3*y,0
  M=. '*' ((_2 {:: cInds) <@:+"1 offset)} M
  M=. '.' ((_2 {:: cInds) <@:-"1 offset)} M
  M=. '.' ((_3 {:: cInds) <@:+"1 offset)} M
  M=. '*' ((_3 {:: cInds) <@:-"1 offset)} M
)


package org.rosettacode.yinandyang;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class YinYangGenerator
{
    private final int size;

    public YinYangGenerator(final int size)
    {
        this.size = size;
    }

    /**
     *  Draw a yin yang symbol on the given graphics context.
     */
    public void drawYinYang(final Graphics graphics)
    {
        // Preserve the color for the caller
        final Color colorSave = graphics.getColor();

        graphics.setColor(Color.WHITE);
        // Use fillOval to draw a filled in circle
        graphics.fillOval(0, 0, size-1, size-1);

        graphics.setColor(Color.BLACK);
        // Use fillArc to draw part of a filled in circle
        graphics.fillArc(0, 0, size-1, size-1, 270, 180);
        graphics.fillOval(size/4, size/2, size/2, size/2);

        graphics.setColor(Color.WHITE);
        graphics.fillOval(size/4, 0, size/2, size/2);
        graphics.fillOval(7*size/16, 11*size/16, size/8, size/8);

        graphics.setColor(Color.BLACK);
        graphics.fillOval(7*size/16, 3*size/16, size/8, size/8);
        // Use drawOval to draw an empty circle for the outside border
        graphics.drawOval(0, 0, size-1, size-1);

        // Restore the color for the caller
        graphics.setColor(colorSave);
    }

    /**
     *  Create an image containing a yin yang symbol.
     */
    public Image createImage(final Color bg)
    {
        // A BufferedImage creates the image in memory
        final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        // Get the graphics object for the image; note in many
        // applications you actually use Graphics2D for the
        // additional API calls
        final Graphics graphics = image.getGraphics();
        // Color in the background of the image
        graphics.setColor(bg);
        graphics.fillRect(0,0,size,size);
        drawYinYang(graphics);
        return image;
    }

    public static void main(final String args[])
    {
        final int size = Integer.parseInt(args[0]);
        final YinYangGenerator generator = new YinYangGenerator(size);

        final JFrame frame = new JFrame("Yin Yang Generator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final Image yinYang = generator.createImage(frame.getBackground());
        // Use JLabel to display an image
        frame.add(new JLabel(new ImageIcon(yinYang)));
        frame.pack();
        frame.setVisible(true);
    }
}


function Arc(posX,posY,radius,startAngle,endAngle,color){//Angle in radians.
this.posX=posX;
this.posY=posY;
this.radius=radius;
this.startAngle=startAngle;
this.endAngle=endAngle;
this.color=color;
}
//0,0 is the top left of the screen
var YingYang=[
new Arc(0.5,0.5,1,0.5*Math.PI,1.5*Math.PI,"white"),//Half white semi-circle
new Arc(0.5,0.5,1,1.5*Math.PI,0.5*Math.PI,"black"),//Half black semi-circle
new Arc(0.5,0.25,.5,0,2*Math.PI,"black"),//black circle
new Arc(0.5,0.75,.5,0,2*Math.PI,"white"),//white circle
new Arc(0.5,0.25,1/6,0,2*Math.PI,"white"),//small white circle
new Arc(0.5,0.75,1/6,0,2*Math.PI,"black")//small black circle
]
//Ying Yang is DONE!
//Now we'll have to draw it.
//We'll draw it in a matrix that way we can get results graphically or by text!
function Array2D(width,height){
this.height=height;
this.width=width;
this.array2d=[];
for(var i=0;i<this.height;i++){
this.array2d.push(new Array(this.width));
}
}
Array2D.prototype.resize=function(width,height){//This is expensive
//nheight and nwidth is the difference of the new and old height
var nheight=height-this.height,nwidth=width-this.width;
if(nwidth>0){
for(var i=0;i<this.height;i++){
if(i<height)
Array.prototype.push.apply(this.array2d[i],new Array(nwidth));
}
}
else if(nwidth<0){
for(var i=0;i<this.height;i++){
if(i<height)
 this.array2d[i].splice(width,nwidth);
}
}
if(nheight>0){
 Array.prototype.push.apply(this.array2d,new Array(width));
}
else if(nheight<0){
 this.array2d.splice(height,nheight)
}
}
Array2D.prototype.loop=function(callback){
for(var i=0;i<this.height;i++)
 for(var i2=0;i2<this.width;i++)
   callback.call(this,this.array2d[i][i2],i,i2);

}
var mat=new Array2D(100,100);//this sounds fine;
YingYang[0];
//In construction.


def svg:
  "<svg width='100%' height='100%' version='1.1'
        xmlns='http://www.w3.org/2000/svg'
	xmlns:xlink='http://www.w3.org/1999/xlink'>" ;

def draw_yinyang(x; scale):
  "<use xlink:href='#y' transform='translate(\(x),\(x)) scale(\(scale))'/>";

def define_yinyang:
  "<defs>
    <g id='y'>
        <circle cx='0' cy='0' r='200' stroke='black'
         fill='white' stroke-width='1'/>
        <path d='M0 -200 A 200 200 0 0 0 0 200
              100 100 0 0 0 0 0 100 100 0 0 1 0 -200
  		 z' fill='black'/>
        <circle cx='0' cy='100' r='33' fill='white'/>
        <circle cx='0' cy='-100' r='33' fill='black'/>
    </g>
  </defs>" ;

def draw:
  svg,
    define_yinyang,
    draw_yinyang(20; .05),
    draw_yinyang(8 ; .02),
  "</svg>" ;

draw


function yinyang(n::Int=3)
    radii   = (i * n for i in (1, 3, 6))
    ranges  = collect(collect(-r:r) for r in radii)
    squares = collect(collect((x, y) for x in rnge, y in rnge) for rnge in ranges)
    circles = collect(collect((x, y) for (x,y) in sqrpoints if hypot(x, y) ≤ radius)
                      for (sqrpoints, radius) in zip(squares, radii))
    m = Dict((x, y) => ' ' for (x, y) in squares[end])
    for (x, y) in circles[end] m[(x, y)] = x > 0 ? '·' : '*' end
    for (x, y) in circles[end-1]
        m[(x, y + 3n)] = '*'
		m[(x, y - 3n)] = '·'
    end
    for (x, y) in circles[end-2]
        m[(x, y + 3n)] = '·'
		m[(x, y - 3n)] = '*'
    end
    return join((join(m[(x, y)]  for x in reverse(ranges[end])) for y in ranges[end]), '\n')
end

println(yinyang(4))


// version 1.1.2

import java.awt.Color
import java.awt.Graphics
import java.awt.Image
import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.JLabel

class YinYangGenerator {
    private fun drawYinYang(size: Int, g: Graphics) {
        with(g) {
            // Preserve the color for the caller
            val colorSave = color
            color = Color.WHITE

            // Use fillOval to draw a filled in circle
            fillOval(0, 0, size - 1, size - 1)
            color = Color.BLACK

            // Use fillArc to draw part of a filled in circle
            fillArc(0, 0, size - 1, size - 1, 270, 180)
            fillOval(size / 4, size / 2, size / 2, size / 2)
            color = Color.WHITE
            fillOval(size / 4, 0, size / 2, size / 2)
            fillOval(7 * size / 16, 11 * size / 16, size /8, size / 8)
            color = Color.BLACK
            fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8)

            // Use drawOval to draw an empty circle for the outside border
            drawOval(0, 0, size - 1, size - 1)

            // Restore the color for the caller
            color = colorSave
        }
    }

    fun createImage(size: Int, bg: Color): Image {
        // A BufferedImage creates the image in memory
        val image = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)

        // Get the graphics object for the image
        val g = image.graphics

        // Color in the background of the image
        g.color = bg
        g.fillRect(0, 0, size, size)
        drawYinYang(size, g)
        return image
    }
}

fun main(args: Array<String>) {
    val gen = YinYangGenerator()
    val size = 400 // say
    val p = JPanel()
    val yinYang = gen.createImage(size, p.background)
    p.add(JLabel(ImageIcon(yinYang)))

    val size2 = size / 2 // say
    val yinYang2 = gen.createImage(size2, p.background)
    p.add(JLabel(ImageIcon(yinYang2)))

    val f = JFrame("Big and Small Yin Yang")
    with (f) {
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        add(p)
        pack()
        isVisible = true
    }
}


{{SVG 580 580}
 {YY 145 145 300}
 {YY 270 195 50}
 {YY 270 345 50}
}

{def YY
 {lambda {:x :y :s}
  {{G :x :y :s}
    {CIRCLE 0.5 0.5 0.5 black 0 0}
    {{G 0.5 0 1} {HALF_CIRCLE}}
    {CIRCLE 0.5 0.25 0.25 black 0 0}
    {CIRCLE 0.5 0.75 0.25 white 0 0}
    {CIRCLE 0.5 0.25 0.1 white 0 0}
    {CIRCLE 0.5 0.75 0.1 black 0 0}
    {CIRCLE 0.5 0.5 0.5 none gray 0.01} }}}

{def CIRCLE
 {lambda {:x :y :r :f :s :w}
  {circle {@ cx=":x" cy=":y" r=":r"
             fill=":f" stroke=":s" stroke-width=":w"}}}}

{def HALF_CIRCLE
  {path {@ d="M 0 0 A 0.5 0.5 0 0 0 0 1" fill="white"}}}

{def SVG
 {lambda {:w :h}
  svg {@ width=":w" height=":h"
         style="box-shadow:0 0 8px #888;"}}}

{def G
 {lambda {:x :y :s}
  g {@ transform="translate(:x,:y) scale(:s,:s)"}}}

Output: Sorry, I was unable to upload the following PNG picture (45kb). Need help.

http://lambdaway.free.fr/lambdawalks/data/lambdatalk_yinyang.png


to taijitu :r
  ; Draw a classic Taoist taijitu of the given radius centered on the current
  ; turtle position. The "eyes" are placed along the turtle's heading, the
  ; filled one in front, the open one behind.

  ; don't bother doing anything if the pen is not down
  if not pendown? [stop]

  ; useful derivative values
  localmake "r2 (ashift :r  -1)
  localmake "r4 (ashift :r2 -1)
  localmake "r8 (ashift :r4 -1)

  ; remember where we started
  localmake "start  pos

  ; draw outer circle
  pendown
  arc 360 :r

  ; draw upper half of S
  penup
  forward :r2
  pendown
  arc 180 :r2

  ; and filled inner eye
  arc 360 :r8
  fill

  ; draw lower half of S
  penup
  back :r
  pendown
  arc -180 :r2

  ; other inner eye
  arc  360 :r8

  ; fill this half of the symbol
  penup
  forward :r4
  fill

  ; put the turtle back where it started
  setpos :start
  pendown
end

; demo code to produce image at right
clearscreen
pendown
hideturtle
taijitu 100
penup
forward 150
left 90
forward 150
pendown
taijitu 75


function circle(x, y, c, r)
    return (r * r) >= (x * x) / 4 + ((y - c) * (y - c))
end

function pixel(x, y, r)
    if circle(x, y, -r / 2, r / 6) then
        return '#'
    end
    if circle(x, y, r / 2, r / 6) then
        return '.'
    end
    if circle(x, y, -r / 2, r / 2) then
        return '.'
    end
    if circle(x, y, r / 2, r / 2) then
        return '#'
    end
    if circle(x, y, 0, r) then
        if x < 0 then
            return '.'
        else
            return '#'
        end
    end
    return ' '
end

function yinYang(r)
    for y=-r,r do
        for x=-2*r,2*r do
            io.write(pixel(x, y, r))
        end
        print()
    end
end

yinYang(18)


vardef yinyang(expr u) =
  picture pic_;
  path p_;
  p_ := halfcircle scaled 2u rotated -90 --
    halfcircle scaled u rotated 90 shifted (0, 1/2u) reflectedabout ((0,1), (0,-1)) --
    halfcircle scaled u rotated -270 shifted (0, -1/2u) -- cycle;

  pic_ := nullpicture;
  addto pic_ contour fullcircle scaled 2u withcolor black;
  addto pic_ contour p_ withcolor white;
  addto pic_ doublepath p_ withcolor black withpen pencircle scaled 0.5mm;
  addto pic_ contour fullcircle scaled 1/3u shifted (0, 1/2u) withcolor white;
  addto pic_ contour fullcircle scaled 1/3u shifted (0, -1/2u) withcolor black;
  pic_
enddef;

beginfig(1)
  % let's create a Yin Yang symbol with a radius of 5cm
  draw yinyang(5cm) shifted (5cm, 5cm);
  % and another one, radius 2.5cm, rotated 180 degrees and translated
  draw yinyang(2.5cm) rotated 180 shifted (11cm, 11cm);
endfig;

end.


MODULE Taijitu;
FROM InOut IMPORT Write, WriteLn;

PROCEDURE YinYang(r: INTEGER);
    VAR x, y: INTEGER;

    PROCEDURE circle(x, y, c, r: INTEGER): BOOLEAN;
    BEGIN
        RETURN r*r >= (x DIV 2) * (x DIV 2) + (y-c) * (y-c);
    END circle;

    PROCEDURE pixel(x, y, r: INTEGER): CHAR;
    BEGIN
        IF circle(x, y, -r DIV 2, r DIV 6) THEN RETURN '#';
        ELSIF circle(x, y, r DIV 2, r DIV 6) THEN RETURN '.';
        ELSIF circle(x, y, -r DIV 2, r DIV 2) THEN RETURN '.';
        ELSIF circle(x, y, r DIV 2, r DIV 2) THEN RETURN '#';
        ELSIF circle(x, y, 0, r) THEN
            IF x<0 THEN RETURN '.';
            ELSE RETURN '#';
            END;
        ELSE RETURN ' ';
        END;
    END pixel;
BEGIN
    FOR y := -r TO r DO
        FOR x := -2*r TO 2*r DO
            Write(pixel(x,y,r));
        END;
        WriteLn();
    END;
END YinYang;

BEGIN
    YinYang(4);
    WriteLn();
    YinYang(8);
END Taijitu.


/* NetRexx */

options replace format comments java crossref savelog symbols binary

say "<?xml version='1.0' encoding='UTF-8' standalone='no'?>"
say "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'"
say "  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>"
say "<svg xmlns='http://www.w3.org/2000/svg' version='1.1'"
say "  xmlns:xlink='http://www.w3.org/1999/xlink'"
say "  width='30' height='30'>"
say "  <defs><g id='y'>"
say "    <circle cx='0' cy='0' r='200' stroke='black'"
say "      fill='white' stroke-width='1'/>"
say "    <path d='M0 -200 A 200 200 0 0 0 0 200"
say "      100 100 0 0 0 0 0 100 100 0 0 1 0 -200"
say "      z' fill='black'/>"
say "    <circle cx='0' cy='100' r='33' fill='white'/>"
say "    <circle cx='0' cy='-100' r='33' fill='black'/>"
say "  </g></defs>"

say draw_yinyang(20, 0.05)
say draw_yinyang(8, 0.02)

say "</svg>"

return

method draw_yinyang(trans = int, scale = double) inheritable static returns String
  yy = String.format("  <use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>", -
       [Object Integer(trans), Integer(trans), Double(scale)])
  return yy


import gintro/cairo

proc draw(ctx: Context; x, y, r: float) =
  ctx.arc(x, y, r + 1, 1.571, 7.854)
  ctx.setSource(0.0, 0.0, 0.0)
  ctx.fill()
  ctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712)
  ctx.arc(x, y + r / 2, r / 2, 1.571, 4.712)
  ctx.arcNegative(x, y, r, 4.712, 1.571)
  ctx.setSource(1.0, 1.0, 1.0)
  ctx.fill()
  ctx.arc(x, y - r / 2, r / 5, 1.571, 7.854)
  ctx.setSource(0.0, 0.0, 0.0)
  ctx.fill()
  ctx.arc(x, y + r / 2, r / 5, 1.571, 7.854)
  ctx.setSource(1.0, 1.0, 1.0)
  ctx.fill()

let surface = imageSurfaceCreate(argb32, 200, 200)
let context = newContext(surface)
context.draw(120, 120, 75)
context.draw(35, 35, 30)
let status = surface.writeToPng("yin-yang.png")
assert status == Status.success


open Graphics

let draw_yinyang x y radius black white =
  let hr = radius / 2 in
  let sr = radius / 6 in
  set_color black;
  set_line_width 6;
  draw_circle x y radius;
  set_line_width 0;
  set_color black;
  fill_arc x y radius radius 270 450;
  set_color white;
  fill_arc x y radius radius 90 270;
  fill_arc x (y + hr) hr hr 270 450;
  set_color black;
  fill_arc x (y - hr) hr hr 90 270;
  fill_circle x (y + hr) sr;
  set_color white;
  fill_circle x (y - hr) sr

let () =
  open_graph "";
  let width = size_x()
  and height = size_y() in
  set_color (rgb 200 200 200);
  fill_rect 0 0 width height;
  let w = width / 3
  and h = height / 3 in
  let r = (min w h) / 3 in
  draw_yinyang w (h*2) (r*2) black white;
  draw_yinyang (w*2) h r blue magenta;
  ignore(read_key())


//Written for TU Berlin
//Compiled with fpc
Program yingyang;
Uses Math;
const
 scale_x=2;
 scale_y=1;
 black='#';
 white='.';
 clear=' ';

function inCircle(centre_x:Integer;centre_y:Integer;radius:Integer;x:Integer;y:Integer):Boolean ;
begin
inCircle:=power(x-centre_x,2)+power(y-centre_y,2)<=power(radius,2);
end;

function bigCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
bigCircle:=inCircle(0,0,radius,x,y);
end;

function whiteSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
whiteSemiCircle:=inCircle(0,radius div 2 ,radius div 2,x,y);
end;

function smallBlackCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
smallBlackCircle:=inCircle(0,radius div 2 ,radius div 6,x,y);
end;

function blackSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
blackSemiCircle:=inCircle(0,-radius div 2 ,radius div 2,x,y);
end;

function smallWhiteCircle(radius:Integer;x:Integer;y:Integer):Boolean ;
begin
smallWhiteCircle:=inCircle(0,-radius div 2 ,radius div 6,x,y);
end;

var
radius,sy,sx,x,y:Integer;
begin
   writeln('Please type a radius:');
   readln(radius);
   if radius<3 then begin writeln('A radius bigger than 3');halt end;
   sy:=round(radius*scale_y);
   while(sy>=-round(radius*scale_y)) do begin
      sx:=-round(radius*scale_x);
      while(sx<=round(radius*scale_x)) do begin
        x:=sx div scale_x;
        y:=sy div scale_y;
        if bigCircle(radius,x,y) then begin
                if (whiteSemiCircle(radius,x,y)) then if smallblackCircle(radius,x,y) then write(black) else write(white) else if blackSemiCircle(radius,x,y) then if smallWhiteCircle(radius,x,y) then write(white) else write(black) else if x>0 then write(white) else write(black);
                end
              else write(clear);
        sx:=sx+1
      end;
      writeln;
      sy:=sy-1;
   end;
end.


sub circle {
        my ($radius, $cx, $cy, $fill, $stroke) = @_;
        print   "<circle cx='$cx' cy='$cy' r='$radius' ",
                "fill='$fill' stroke='$stroke' stroke-width='1'/>\n";
}

sub yin_yang {
        my ($rad, $cx, $cy, %opt) = @_;
        my ($c, $w) = (1, 0);
        $opt{fill}   //= 'white';
        $opt{stroke} //= 'black';
        $opt{recurangle} //= 0;

        print "<g transform='rotate($opt{angle}, $cx, $cy)'>"
                if $opt{angle};

        if ($opt{flip}) { ($c, $w) = ($w, $c) };

        circle($rad, $cx, $cy, $opt{fill}, $opt{stroke});

        print "<path d='M $cx ", $cy + $rad, "A ",
                $rad/2, " ", $rad/2, " 0 0 $c $cx $cy ",
                $rad/2, " ", $rad/2, " 0 0 $w $cx ", $cy - $rad, " ",
                $rad,   " ", $rad,   " 0 0 $c $cx ", $cy + $rad, " ",
                "z' fill='$opt{stroke}' stroke='none' />";

        if ($opt{recur} and $rad > 1) {
                # recursive "eyes" are slightly larger
                yin_yang($rad/4, $cx, $cy + $rad/2, %opt,
                                angle   => $opt{recurangle},
                                fill    => $opt{stroke},
                                stroke  => $opt{fill}   );
                yin_yang($rad/4, $cx, $cy - $rad/2, %opt,
                                angle   => 180 + $opt{recurangle});
        } else {
                circle($rad/5, $cx, $cy + $rad/2, $opt{fill}, $opt{stroke});
                circle($rad/5, $cx, $cy - $rad/2, $opt{stroke}, $opt{fill});
        }
        print "</g>" if $opt{angle};
}

print <<'HEAD';
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
        "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
        xmlns:xlink="http://www.w3.org/1999/xlink">
HEAD

yin_yang(200, 250, 250, recur=>1,
         angle=>0, recurangle=>90, fill=>'white', stroke=>'black');
yin_yang(100, 500, 500);

print "</svg>"


--
-- demo\rosetta\Yin_and_yang.exw
-- =============================
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cd_canvas

procedure cdCanvasSecArc(cdCanvas hCdCanvas, atom xc, atom yc, atom w, atom h, atom angle1, atom angle2)
-- cdCanvasSector does not draw anti-aliased edges, but cdCanvasArc does, so over-draw...
    cdCanvasSector(hCdCanvas, xc, yc, w, h, angle1, angle2)
    cdCanvasArc   (hCdCanvas, xc, yc, w, h, angle1, angle2)
end procedure

procedure yinyang(atom  cx, cy, r)
    cdCanvasArc(cd_canvas, cx, cy, r, r, 0, 360)
    cdCanvasSecArc(cd_canvas, cx, cy, r, r, 270, 90)
    cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/2-1, r/2-1, 0, 360)
    cdCanvasSetForeground(cd_canvas, CD_WHITE)
    cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/2-1, r/2-1, 0, 360)
    cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/8, r/8, 0, 360)
    cdCanvasSetForeground(cd_canvas, CD_BLACK)
    cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/8, r/8, 0, 360)
end procedure

function redraw_cb(Ihandle /*ih*/)
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"),
             r = min(width,height)-40,
            cx = floor(width/2),
            cy = floor(height/2)
    cdCanvasActivate(cd_canvas)
    cdCanvasClear(cd_canvas)
    yinyang(cx-r*.43,cy+r*.43,r/6)
    yinyang(cx,cy,r)
    cdCanvasFlush(cd_canvas)
    return IUP_DEFAULT
end function

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

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

procedure main()
    IupOpen()
    canvas = IupGLCanvas("RASTERSIZE=340x340")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "RESIZE_CB", Icallback("canvas_resize_cb"),
                             "ACTION", Icallback("redraw_cb")})
    dlg = IupDialog(canvas, `TITLE="Yin and Yang"`)
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


module circles;

extern printf;

@Boolean in_circle(@Integer centre_x, @Integer centre_y, @Integer radius, @Integer x, @Integer y) [
	return (x-centre_x)*(x-centre_x)+(y-centre_y)*(y-centre_y) <= radius*radius;
]

@Boolean in_big_circle (@Integer radius, @Integer x, @Integer y) [
	return in_circle(0, 0, radius, x, y);
]

@Boolean in_while_semi_circle (@Integer radius, @Integer x, @Integer y) [
	return in_circle(0, radius/2, radius/2, x, y);
]

@Boolean in_small_white_circle (@Integer radius, @Integer x, @Integer y) [
	return in_circle(0, 0-radius/2, radius/6, x, y);
]

@Boolean in_black_semi_circle (@Integer radius, @Integer x, @Integer y) [
	return in_circle(0, 0-radius/2, radius/2, x, y);
]

@Boolean in_small_black_circle (@Integer radius, @Integer x, @Integer y) [
	return in_circle(0, radius/2, radius/6, x, y);
]

@Void print_yin_yang(@Integer radius) [
	var white = '.';
	var black = '#';
	var clear = ' ';

	var scale_y = 1;
	var scale_x = 2;
	for (var sy = radius*scale_y; sy >= -(radius*scale_y); sy=sy-1) {
		for (var sx = -(radius*scale_x); sx <= radius*scale_x; sx=sx+1) {
			var x = sx/(scale_x);
			var y = sy/(scale_y);

			if (in_big_circle(radius, x, y)) {
				if (in_while_semi_circle(radius, x, y))
					if (in_small_black_circle(radius, x, y))
						printf("%c", black);
					else
						printf("%c", white);
				else if (in_black_semi_circle(radius, x, y))
					if (in_small_white_circle(radius, x, y))
						printf("%c", white);
					else
						printf("%c", black);
				else 	if (x < 0)
						printf("%c", white);
					else
						printf("%c", black);
			} else printf("%c", clear);
		}
		printf("\n");
	}
]

@Integer main [
	print_yin_yang(17);
	print_yin_yang(8);
	return 0;
]


To run:
Start up.
Clear the screen to the gray color.
Draw the Taijitu symbol 4 inches wide at the screen's center.
Put the screen's center into a spot. Move the spot 4 inches right.
Draw the Taijitu symbol 2 inches wide at the spot.
Refresh the screen.
Wait for the escape key.
Shut down.

To draw the Taijitu symbol some twips wide at a spot:
Imagine a box the twips high by the twips wide.
Imagine an ellipse given the box.
Center the ellipse on the spot.
Mask outside the ellipse.
Imagine a left half box with the screen's left and the screen's top and the spot's x coord and the screen's bottom.
Fill the left half with the white color.
Imagine a right half box with the spot's x coord and the screen's top and the screen's right and the screen's bottom.
Fill the right half with the black color.
Imagine a swirl ellipse given the box.
Scale the swirl given 1/2.
Put the spot into an upper spot. Move the upper spot up the twips divided by 4.
Put the spot into a lower spot. Move the lower spot down the twips divided by 4.
Fill the swirl on the upper spot with the white color.
Fill the swirl on the lower spot with the black color.
Put the swirl into a dot.
Scale the dot given 1/4.
Fill the dot on the lower spot with the white color.
Fill the dot on the upper spot with the black color.
Unmask everything.
Use the fat pen.
Draw the ellipse.


yinyang: procedure options(main);
    yinyang: procedure(r);
        circle: procedure(x, y, c, r) returns(bit);
            declare (x, y, c, r) fixed;
            return( r*r >= (x/2) * (x/2) + (y-c) * (y-c) );
        end circle;

        pixel: procedure(x, y, r) returns(char);
            declare (x, y, r) fixed;
            if circle(x, y, -r/2, r/6) then return('#');
            if circle(x, y, r/2, r/6) then return('.');
            if circle(x, y, -r/2, r/2) then return('.');
            if circle(x, y, r/2, r/2) then return('#');
            if circle(x, y, 0, r) then do;
                if x<0 then return('.');
                else return('#');
            end;
            return(' ');
        end pixel;

        declare (x, y, r) fixed;
        do y=-r to r;
            do x=-2*r to 2*r;
                put edit(pixel(x, y, r)) (A(1));
            end;
            put skip;
        end;
    end yinyang;

    call yinyang(4);
    put skip;
    call yinyang(8);
end yinyang;


%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400

/fs 10 def
/ed { exch def } def
/dist { 3 -1 roll sub dup mul 3 1 roll sub dup mul add sqrt } def
/circ {
    /r exch def
    [r neg 1 r {
        /y exch def
        [ r 2 mul neg 1 r 2 mul {
            /x ed x 2 div y 0 0 dist r .05 add gt {( )}{
                x 2 div y 0 r 2 div dist dup
                r 5 div le { pop (.) } {
                    r 2 div le { (@) }{
                        x 2 div y 0 r 2 div neg dist dup
                        r 5 div le { pop (@)} {
                            r 2 div le {(.)}{
                                x 0 le {(.)}{(@)}ifelse
                            } ifelse
                        } ifelse
                    } ifelse
                } ifelse
            } ifelse
        } for]
    } for]
} def

/dis {  moveto gsave
        {       grestore 0 fs 1.15 mul neg rmoveto gsave
                {show} forall
        } forall grestore
} def

/Courier findfont fs scalefont setfont

11 circ 10 390 dis
6 circ 220 180 dis
showpage
%%EOF


// ====== General Scene setup ======
#version 3.7;
global_settings { assumed_gamma 2.2 }

camera{ location <0,2.7,4> look_at <0,.1,0> right x*1.6
        aperture .2 focal_point <1,0,0> blur_samples 200 variance 1/10000 }
light_source{<2,4,8>, 1 spotlight point_at 0 radius 10}
sky_sphere {pigment {granite scale <1,.1,1> color_map {[0 rgb 1][1 rgb <0,.4,.6>]}}}
#default {finish {diffuse .9 reflection {.1 metallic} ambient .3}
          normal {granite scale .2}}
plane { y, -1 pigment {hexagon color rgb .7 color rgb .75 color rgb .65}
        normal {hexagon scale 5}}

// ====== Declare one side of the symbol as a sum and difference of discs ======

#declare yang =
difference {
  merge {
    difference {
      cylinder {0 <0,.1,0> 1}               // flat disk
      box {-1 <1,1,0>}                      // cut in half
      cylinder {<.5,-.1,0> <.5,.2,0> .5}    // remove half-cicle on one side
    }
    cylinder {<-.5,0,0> <-.5,.1,0> .5}      // add on the other side
    cylinder {<.5,0,0> <.5,.1,0> .15}       // also add a little dot
  }
  cylinder {<-.5,-.1,0> <-.5,.2,0> .15}     // and carve out a hole
  pigment{color rgb 0.1}
}

// ====== The other side is white and 180-degree turned ======

#declare yin =
object {
  yang
  rotate <0,180,0>
  pigment{color rgb 1}
}

// ====== Here we put the two together: ======

#macro yinyang( ysize )
  union {
    object {yin}
    object {yang}
    scale ysize
  }
#end

// ====== Here we put one into a scene: ======

object { yinyang(1)
         translate -y*1.08 }

// ====== And a bunch more just for fun: ======

#declare scl=1.1;
#while (scl > 0.01)

  object { yinyang(scl)
        rotate <0,180,0> translate <-scl*4,scl*2-1,0>
        rotate <0,scl*360,0> translate <-.5,0,0>}

  object { yinyang(scl)
        translate <-scl*4,scl*2-1,0>
        rotate <0,scl*360+180,0> translate <.5,0,0>}

  #declare scl = scl*0.85;
#end


ying_yang(N) :-
	R is N * 100,
	sformat(Title, 'Yin Yang ~w', [N]),
	new(W, window(Title)),
	new(Wh, colour(@default, 255*255, 255*255, 255*255)),
	new(Bl, colour(@default, 0, 0, 0)),
	CX is R + 50,
	CY is R + 50,
	R1 is R / 2,
	R2 is R / 8,
	CY1 is R1 + 50,
	CY2 is 3 * R1 + 50,

	new(E, semi_disk(point(CX, CY), R, w, Bl)),
	new(F, semi_disk(point(CX, CY), R, e, Wh)),
	new(D1, disk(point(CX, CY1), R, Bl)),
	new(D2, disk(point(CX, CY2), R, Wh)),
	new(D3, disk(point(CX, CY1), R2, Wh)),
	new(D4, disk(point(CX, CY2), R2, Bl)),

	send_list(W, display, [E, F, D1, D2, D3, D4]),

	WD is 2 * R + 100,
	send(W, size, size(WD, WD )),
	send(W, open).

:- pce_begin_class(semi_disk, path, "Semi disk with color ").

initialise(P, C, R, O, Col) :->
        send(P, send_super, initialise),
	get(C, x, CX),
	get(C, y, CY),
	choose(O, Deb, End),
	forall(between(Deb, End, I),
	       (   X is R * cos(I * pi/180) + CX,
		   Y is R * sin(I * pi/180) + CY,
	           send(P, append, point(X,Y)))),
	send(P, closed, @on),
	send(P, fill_pattern, Col).

:- pce_end_class.

choose(s, 0, 180).
choose(n, 180, 360).
choose(w, 90, 270).
choose(e, -90, 90).

:- pce_begin_class(disk, ellipse, "disk with color ").

initialise(P, C, R, Col) :->
        send(P, send_super, initialise, R, R),
	send(P, center, C),
	send(P, pen, 0),
	send(P, fill_pattern, Col).

:- pce_end_class.


import math
def yinyang(n=3):
	radii   = [i * n for i in (1, 3, 6)]
	ranges  = [list(range(-r, r+1)) for r in radii]
	squares = [[ (x,y) for x in rnge for y in rnge]
		   for rnge in ranges]
	circles = [[ (x,y) for x,y in sqrpoints
		     if math.hypot(x,y) <= radius ]
		   for sqrpoints, radius in zip(squares, radii)]
	m = {(x,y):' ' for x,y in squares[-1]}
	for x,y in circles[-1]:
		m[x,y] = '*'
	for x,y in circles[-1]:
		if x>0: m[(x,y)] = '·'
	for x,y in circles[-2]:
		m[(x,y+3*n)] = '*'
		m[(x,y-3*n)] = '·'
	for x,y in circles[-3]:
		m[(x,y+3*n)] = '·'
		m[(x,y-3*n)] = '*'
	return '\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1])


[ $ "turtleduck.qky" loadfile ] now!

  [ -1 4 turn
    2dup -v fly
    1 4 turn
    4 wide
    ' [ 0 0 0 ] colour
    ' [ 0 0 0 ] fill
      [ 2dup 2 1 v/ 1 2 arc
        2dup -2 1 v/ 1 2 arc
        2dup -v 1 2 arc ]
    2dup -v 1 2 arc
    1 4 turn
    2dup 2 1 v/ fly
    ' [ 0 0 0 ] colour
    1 wide
    ' [ 255 255 255 ] fill
      [ 2dup 7 1 v/ circle ]
    2dup fly
    ' [ 255 255 255 ] colour
    ' [ 0 0 0 ] fill
      [ 2dup 7 1 v/ circle ]
    -2 1 v/ fly
    -1 4 turn ]               is yinyang ( n/d --> )

  turtle
 -110 1 fly
  100 1 yinyang
  420 1 fly
  300 1 yinyang


plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){
	suppressMessages(require("plotrix"))
	if(!add) plot(1:10, type="n", xlim=c(0,s), ylim=c(0,s), xlab="", ylab="", xaxt="n", yaxt="n", bty="n", asp=1)
	draw.circle(x, y, r, border="white", col= "black")
	draw.ellipse(x, y, r, r, col="white", angle=0, segment=c(90,270), arc.only=F)
	draw.ellipse(x, y - r * 0.5, r * 0.5, r * 0.5, col="black", border="black", angle=0, segment=c(90,270), arc.only=F)
	draw.circle(x, y - r * 0.5, r * 0.125, border="white", col= "white")
	draw.circle(x, y + r * 0.5, r * 0.5, col="white", border="white")
	draw.circle(x, y + r * 0.5, r * 0.125, border="black", lty=1, col= "black")
	draw.circle(x, y, r, border="black")
}
png("yin_yang.png")
plot.yin.yang()
plot.yin.yang(1,7,1, add=T)
dev.off()


#lang racket
(require slideshow/pict)

(define (yin-yang d)
  (define base
    (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0)
               (inset/clip (disk d) (- (/ d 2)) 0 0 0)))
  (define with-top
    (ct-superimpose
     base
     (cc-superimpose (colorize (disk (/ d 2)) "white")
                     (disk (/ d 8)))))
  (define with-bottom
    (cb-superimpose
     with-top
     (cc-superimpose (disk (/ d 2))
                     (colorize (disk (/ d 8)) "white"))))
  (cc-superimpose with-bottom (circle d)))

(yin-yang 200)


sub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){
    say "<circle cx='$cx' cy='$cy' r='$rad' fill='$fill' stroke='$stroke' stroke-width='1'/>";
}

sub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) {
    my ($c, $w) = (1, 0);
    say "<g transform='rotate($angle, $cx, $cy)'>" if $angle;
    circle($rad, $cx, $cy, $fill, $stroke);
    say "<path d='M $cx {$cy + $rad}A {$rad/2} {$rad/2} 0 0 $c $cx $cy ",
        "{$rad/2} {$rad/2} 0 0 $w $cx {$cy - $rad} $rad $rad 0 0 $c $cx ",
        "{$cy + $rad} z' fill='$stroke' stroke='none' />";
    circle($rad/5, $cx, $cy + $rad/2, $fill, $stroke);
    circle($rad/5, $cx, $cy - $rad/2, $stroke, $fill);
    say "</g>" if $angle;
}

say '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="400" width="400" xmlns="http://www.w3.org/2000/svg" version="1.1"
 xmlns:xlink="http://www.w3.org/1999/xlink">';

yin_yang(100, 130, 130);
yin_yang(50, 300, 300);

say '</svg>';


import util::Math;
import vis::Render;
import vis::Figure;

public void yinyang(){
	template = ellipse(fillColor("white"));

	smallWhite = ellipse(fillColor("white"), shrink(0.1), valign(0.75));
	smallBlack = ellipse(fillColor("black"), shrink(0.1), valign(0.25));

	dots= [ellipse(fillColor("white"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/4, 0.25 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]];
	dots2 = [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/-4, 0.75 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]];
	dots3= [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/2, 0.5-cos(0.0031415*n)/-2)) | n <- [1 .. 1000]];

	black= overlay([*dots, *dots2, *dots3], shapeConnected(true), shapeClosed(true), shapeCurved(true), fillColor("black"));

	render(hcat([vcat([overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0)), space(), space()]),
	                   overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0))]));
}


/*REXX program creates & displays an ASCII art version of the Yin─Yang (taijitu) symbol.*/
parse arg s1 s2 .                                /*obtain optional arguments from the CL*/
if s1=='' | s1==","  then s1=     17             /*Not defined?   Then use the default. */
if s2=='' | s2==","  then s2= s1 % 2             /* "      "        "   "   "     "     */
if s1>0              then call  Yin_Yang  s1     /*create & display 1st Yin-Yang symbol.*/
if s2>0              then call  Yin_Yang  s2     /*   "   "    "    2nd    "       "    */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
[email protected]:     procedure;  parse arg cy,r,x,y;           return x**2  +  (y-cy)**2  <=  r**2
[email protected]:      /*in big         circle. */             return [email protected](  0 ,    r  ,    x,    y )
[email protected]:     /*in semi        circle. */             return [email protected]( r/2,    r/2,    x,    y )
[email protected]:       /*in small black circle. */             return [email protected]( r/2,    r/6,    x,    y )
[email protected]:       /*in small white circle. */             return [email protected](-r/2,    r/6,    x,    y )
[email protected]:    /*in black semi  circle. */             return [email protected](-r/2,    r/2,    x,    y )
/*──────────────────────────────────────────────────────────────────────────────────────*/
Yin_Yang: procedure; parse arg r;  mX= 2;  mY= 1 /*aspect multiplier for the  X,Y  axis.*/
  do   sy= r*mY  to  -r*mY  by -1;     $=                           /*$ ≡ an output line*/
    do sx=-r*mX  to   r*mX;            x= sx / mX;    y= sy / mY    /*apply aspect ratio*/
    if [email protected]() then if [email protected]()  then if [email protected]()     then $= $'Θ';                else $= $"°"
                               else if [email protected]()  then if [email protected]()  then $= $'°'; else $= $"Θ"
                                                 else if x<0    then $= $'°'; else $= $"Θ"
              else $= $' '
    end   /*sy*/
  say strip($, 'T')                              /*display one line of a Yin─Yang symbol*/
  end     /*sx*/;       return


/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createXml64.s   */
/* install package   libxml++2.6-dev    */
/* link with gcc option -I/usr/include/libxml2 -lxml2    */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n"
szFileName:        .asciz "file1.xml"
szFileMode:        .asciz "w"
szMessError:       .asciz "Error detected !!!!. \n"

szVersDoc:         .asciz "1.0"
szLibRoot:         .asciz "root"
szLibElement:      .asciz "element"
szText:            .asciz "some text here"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     // entry of program
    ldr x0,qAdrszVersDoc
    bl xmlNewDoc                          // create doc
    mov x19,x0                            // doc address
    mov x0,#0
    ldr x1,qAdrszLibRoot
    bl xmlNewNode                         // create root node
    cbz x0,99f
    mov x20,x0                            // node root address
    mov x0,x19
    mov x1,x20
    bl xmlDocSetRootElement
    mov x0,#0
    ldr x1,qAdrszLibElement
    bl xmlNewNode                         // create element node
    mov x21,x0                             // node element address
    ldr x0,qAdrszText
    bl xmlNewText                         // create text
    mov x22,x0                             // text address
    mov x0,x21                             // node element address
    mov x1,x22                             // text address
    bl xmlAddChild                        // add text to element node
    mov x0,x20                             // node root address
    mov x1,x21                             // node element address
    bl xmlAddChild                        // add node elemeny to root node
    ldr x0,qAdrszFileName
    ldr x1,qAdrszFileMode
    bl fopen                              // file open
    cmp x0,#0
    blt 99f
    mov x23,x0                             // File descriptor
    mov x1,x19                             // doc
    mov x2,x20                             // root
    bl xmlElemDump                        // write xml file
    cmp x0,#0
    blt 99f
    mov x0,x23
    bl fclose                             // file close
    mov x0,x19
    bl xmlFreeDoc
    bl xmlCleanupParser
    ldr x0,qAdrszMessEndpgm
    bl affichageMess
    b 100f
99:                                        // error
    ldr x0,qAdrszMessError
    bl affichageMess
100:                                       // standard end of the program
    mov x0,0                               // return code
    mov x8,EXIT                            // request to exit program
    svc 0                                  // perform the system call

qAdrszMessError:          .quad szMessError
qAdrszMessEndpgm:         .quad szMessEndpgm
qAdrszVersDoc:            .quad szVersDoc
qAdrszLibRoot:            .quad szLibRoot
qAdrszLibElement:         .quad szLibElement
qAdrszText:               .quad szText
qAdrszFileName:           .quad szFileName
qAdrszFileMode:           .quad szFileMode
qAdrszCarriageReturn:     .quad szCarriageReturn
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


Shoes.app(:width => 470, :height => 380) do
  PI = Shoes::TWO_PI/2

  strokewidth 1

  def yin_yang(x, y, radius)
    fill black; stroke black
    arc x, y, radius, radius, -PI/2, PI/2

    fill white; stroke white
    arc x, y, radius, radius, PI/2, -PI/2
    oval x-radius/4, y-radius/2, radius/2-1

    fill black; stroke black
    oval x-radius/4, y, radius/2-1
    oval x-radius/12, y-radius/4-radius/12, radius/6-1

    fill white; stroke white
    oval x-radius/12, y+radius/4-radius/12, radius/6-1

    nofill
    stroke black
    oval x-radius/2, y-radius/2, radius
  end

  yin_yang 190, 190, 360
  yin_yang 410, 90, 90
end


use svg::node::element::Path;

fn main() {
    let doc = svg::Document::new()
        .add(yin_yang(15.0, 1.0).set("transform", "translate(20,20)"))
        .add(yin_yang(6.0, 1.0).set("transform", "translate(50,11)"));
    svg::save("yin_yang.svg", &doc).unwrap();
}
/// th - the thickness of the outline around yang
fn yin_yang(r: f32, th: f32) -> Path {
    let (cr, cw, ccw) = (",0,1,1,.1,0z", ",0,0,1,0,", ",0,0,0,0,");
    let d = format!("M0,{0} a{0},{0}{cr} M0,{1} ", r + th, -r / 3.0) // main_circle
        + &format!("a{0},{0}{cr} m0,{r} a{0},{0}{cr} M0,0 ", r / 6.0) // eyes
        + &format!("A{0},{0}{ccw}{r} A{r},{r}{cw}-{r} A{0},{0}{cw}0", r / 2.0); // yang
    Path::new().set("d", d).set("fill-rule", "evenodd")
}


DATA: xml_string TYPE string.

DATA(xml)  = cl_ixml=>create( ).
DATA(doc)  = xml->create_document( ).
DATA(root) = doc->create_simple_element( name   = 'root'
                                         parent = doc ).

doc->create_simple_element( name   = 'element'
                            parent = root
                            value  = 'Some text here' ).

DATA(stream_factory) = xml->create_stream_factory( ).
DATA(stream)         = stream_factory->create_ostream_cstring( string = xml_string ).
DATA(renderer)       = xml->create_renderer( document = doc
                                             ostream  = stream ).
stream->set_pretty_print( abap_true ).
renderer->render( ).

cl_demo_output=>display_text( xml_string ).


with Ada.Text_IO.Text_Streams;
with DOM.Core.Documents;
with DOM.Core.Nodes;

procedure Serialization is
   My_Implementation : DOM.Core.DOM_Implementation;
   My_Document       : DOM.Core.Document;
   My_Root_Node      : DOM.Core.Element;
   My_Element_Node   : DOM.Core.Element;
   My_Text_Node      : DOM.Core.Text;
begin
   My_Document := DOM.Core.Create_Document (My_Implementation);
   My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, "root");
   My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node);
   My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, "element");
   My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node);
   My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, "Some text here");
   My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node);
   DOM.Core.Nodes.Write
     (Stream => Ada.Text_IO.Text_Streams.Stream
        (Ada.Text_IO.Standard_Output),
      N => My_Document,
      Pretty_Print => True);
end Serialization;


import scala.swing.Swing.pair2Dimension
import scala.swing.{ MainFrame, Panel }
import java.awt.{ Color, Graphics2D }

object YinYang extends scala.swing.SimpleSwingApplication {
  var preferedSize = 500

  /** Draw a Taijitu symbol on the given graphics context.
   */
  def drawTaijitu(g: Graphics2D, size: Int) {
    val sizeMinsOne = size - 1
    // Preserve the color for the caller
    val colorSave = g.getColor()

    g.setColor(Color.WHITE)
    // Use fillOval to draw a filled in circle
    g.fillOval(0, 0, sizeMinsOne, sizeMinsOne)

    g.setColor(Color.BLACK)
    // Use fillArc to draw part of a filled in circle
    g.fillArc(0, 0, sizeMinsOne, sizeMinsOne, 270, 180)
    g.fillOval(size / 4, size / 2, size / 2, size / 2)

    g.setColor(Color.WHITE)
    g.fillOval(size / 4, 0, size / 2, size / 2)
    g.fillOval(7 * size / 16, 11 * size / 16, size / 8, size / 8)

    g.setColor(Color.BLACK)
    g.fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8)
    // Use drawOval to draw an empty circle for the outside border
    g.drawOval(0, 0, sizeMinsOne, sizeMinsOne)

    // Restore the color for the caller
    g.setColor(colorSave)
  }

  def top = new MainFrame {
    title = "Rosetta Code >>> Yin Yang Generator | Language: Scala"
    contents = gui(preferedSize)

    def gui(sizeInterior: Int) = new Panel() {
      preferredSize = (sizeInterior, sizeInterior)

      /** Draw a Taijitu symbol in this graphics context.
       */
      override def paintComponent(graphics: Graphics2D) = {
        super.paintComponent(graphics)

        // Color in the background of the image
        background = Color.RED
        drawTaijitu(graphics, sizeInterior)
      }
    } // def gui(
  }

  override def main(args: Array[String]) = {
    preferedSize = args.headOption.map(_.toInt).getOrElse(preferedSize)
    super.main(args)
  }
}


R = 1;                      //outer radius of first image
scale = 0.5;                //scale of the second image

scf(0); clf();
set(gca(),'isoview','on');
xname('Yin and Yang');

//First one
n_p = 100;                  //number of points per arc
angles = [];                //angles for each arc
angles = linspace(%pi/2, 3*%pi/2, n_p);
Arcs = zeros(7,n_p);

    Arcs(1,:) = R * exp(%i * angles);
    plot2d(real(Arcs(1,:)),imag(Arcs(1,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

    Arcs(2,:) = -%i*R/2 + R/2 * exp(%i * angles);
    plot2d(real(Arcs(2,:)),imag(Arcs(2,:)));
    line = gce();
    set(line.children,'polyline_style',5);

angles = [];
angles = linspace(-%pi/2, %pi/2, n_p);

    Arcs(3,:) = R * exp(%i * angles);
    plot2d(real(Arcs(3,:)), imag(Arcs(3,:)));
    line = gce();
    set(line.children,'polyline_style',5);

    Arcs(4,:) = %i*R/2 + R/2 * exp(%i * angles);
    plot2d(real(Arcs(4,:)),imag(Arcs(4,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

angles = [];
angles = linspace(0, 2*%pi, n_p);

    Arcs(5,:) = %i*R/2 + R/8 * exp(%i * angles);
    plot2d(real(Arcs(5,:)),imag(Arcs(5,:)));
    line = gce();
    set(line.children,'polyline_style',5);

    Arcs(6,:) = -%i*R/2 + R/8 * exp(%i * angles);
    plot2d(real(Arcs(6,:)),imag(Arcs(6,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

    Arcs(7,:) = R * exp(%i * angles);
    plot2d(real(Arcs(7,:)),imag(Arcs(7,:)));
    set(gca(),'axes_visible',['off','off','off']);

//Scaling
new_pos = R + 2*R*scale;
Arcs = new_pos + Arcs .* scale;

    plot2d(real(Arcs(1,:)),imag(Arcs(1,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

    plot2d(real(Arcs(2,:)),imag(Arcs(2,:)));
    line = gce();
    set(line.children,'polyline_style',5);

    plot2d(real(Arcs(3,:)), imag(Arcs(3,:)));
    line = gce();
    set(line.children,'polyline_style',5);

    plot2d(real(Arcs(4,:)),imag(Arcs(4,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

    plot2d(real(Arcs(5,:)),imag(Arcs(5,:)));
    line = gce();
    set(line.children,'polyline_style',5);

    plot2d(real(Arcs(6,:)),imag(Arcs(6,:)));
    line = gce();
    set(line.children,'polyline_style',5);
    set(line.children,'foreground',8);

    plot2d(real(Arcs(7,:)),imag(Arcs(7,:)));
    set(gca(),'axes_visible',['off','off','off']);


/* ARM assembly Raspberry PI  */
/*  program createXml.s   */
/* install package   libxml++2.6-dev    */
/* link with gcc option -lxml2    */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n"
szFileName:        .asciz "file1.xml"
szFileMode:        .asciz "w"
szMessError:       .asciz "Error detected !!!!. \n"

szVersDoc:         .asciz "1.0"
szLibRoot:         .asciz "root"
szLibElement:      .asciz "element"
szText:            .asciz "some text here"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     @ entry of program
    ldr r0,iAdrszVersDoc
    bl xmlNewDoc                          @ create doc
    mov r9,r0                             @ doc address
    mov r0,#0
    ldr r1,iAdrszLibRoot
    bl xmlNewNode                         @ create root node
    mov r8,r0                             @ node root address
    mov r0,r9
    mov r1,r8
    bl xmlDocSetRootElement
@TODO voir la gestion des erreurs

    mov r0,#0
    ldr r1,iAdrszLibElement
    bl xmlNewNode                         @ create element node
    mov r7,r0                             @ node element address
    ldr r0,iAdrszText
    bl xmlNewText                         @ create text
    mov r6,r0                             @ text address
    mov r0,r7                             @ node element address
    mov r1,r6                             @ text address
    bl xmlAddChild                        @ add text to element node
    mov r0,r8                             @ node root address
    mov r1,r7                             @ node element address
    bl xmlAddChild                        @ add node elemeny to root node
    ldr r0,iAdrszFileName
    ldr r1,iAdrszFileMode
    bl fopen                              @ file open
    cmp r0,#0
    blt 99f
    mov r5,r0                             @ File descriptor
    mov r1,r9                             @ doc
    mov r2,r8                             @ root
    bl xmlElemDump                        @ write xml file
    cmp r0,#0
    blt 99f
    mov r0,r5
    bl fclose                             @ file close
    mov r0,r9
    bl xmlFreeDoc
    bl xmlCleanupParser
    ldr r0,iAdrszMessEndpgm
    bl affichageMess
    b 100f
99:
    @ error
    ldr r0,iAdrszMessError
    bl affichageMess
100:                                       @ standard end of the program
    mov r0, #0                             @ return code
    mov r7, #EXIT                          @ request to exit program
    svc #0                                 @ perform the system call

iAdrszMessError:          .int szMessError
iAdrszMessEndpgm:         .int szMessEndpgm
iAdrszVersDoc:            .int szVersDoc
iAdrszLibRoot:            .int szLibRoot
iAdrszLibElement:         .int szLibElement
iAdrszText:               .int szText
iAdrszFileName:           .int szFileName
iAdrszFileMode:           .int szFileMode
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                   @ save  registres
    mov r2,#0                               @ counter length
1:                                          @ loop length calculation
    ldrb r1,[r0,r2]                         @ read octet start position + index
    cmp r1,#0                               @ if 0 its over
    addne r2,r2,#1                          @ else add 1 in the length
    bne 1b                                  @ and loop
                                            @ so here r2 contains the length of the message
    mov r1,r0                               @ address message in r1
    mov r0,#STDOUT                          @ code to write to the standard output Linux
    mov r7, #WRITE                          @ code call system "write"
    svc #0                                  @ call systeme
    pop {r0,r1,r2,r7,lr}                    @ restaur registers */
    bx lr                                   @ return
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                         @ save registers
    mov r3,r1
    mov r2,#LGZONECAL
1:                                          @ start loop
    bl divisionpar10                        @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                              @ digit
    strb r1,[r3,r2]                         @ store digit on area
    cmp r0,#0                               @ stop if quotient = 0
    subne r2,#1                               @ previous position
    bne 1b                                  @ else loop
                                            @ end replaces digit in front of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]                         @ store in area begin
    add r4,#1
    add r2,#1                               @ previous position
    cmp r2,#LGZONECAL                       @ end
    ble 2b                                  @ loop
    mov r1,#' '
3:
    strb r1,[r3,r4]
    add r4,#1
    cmp r4,#LGZONECAL                       @ end
    ble 3b
100:
    pop {r1-r4,lr}                          @ restaur registres
    bx lr                                   @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}                           @ save registers  */
    mov r4,r0
    mov r3,#0x6667                         @ r3 <- magic_number  lower
    movt r3,#0x6666                        @ r3 <- magic_number  upper
    smull r1, r2, r3, r0                   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
    mov r2, r2, ASR #2                     @ r2 <- r2 >> 2
    mov r1, r0, LSR #31                    @ r1 <- r0 >> 31
    add r0, r2, r1                         @ r0 <- r2 + r1
    add r2,r0,r0, lsl #2                   @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                   @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2-r4}
    bx lr                                  @ return


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const proc: yinYang (in integer: xPos, in integer: yPos, in integer: size) is func
  begin
    pieslice(xPos, yPos, size, 3.0 * PI / 2.0, PI, black);
    pieslice(xPos, yPos, size, PI / 2.0, PI, white);
    fcircle(xPos, yPos - size div 2, size div 2, white);
    fcircle(xPos, yPos + size div 2, size div 2, black);
    fcircle(xPos, yPos - size div 2, size div 6, black);
    fcircle(xPos, yPos + size div 2, size div 6, white);
    circle(xPos, yPos, size, black);
  end func;

const proc: main is func
  begin
    screen(640, 480);
    clear(white);
    KEYBOARD := GRAPH_KEYBOARD;
    yinYang(100, 100, 80);
    yinYang(400, 250, 200);
    readln(KEYBOARD);
  end func;


func circle (rad, cx, cy, fill='white', stroke='black') {
    say "<circle cx='#{cx}' cy='#{cy}' r='#{rad}' fill='#{fill}' stroke='#{stroke}' stroke-width='1'/>";
}

func yin_yang (rad, cx, cy, fill='white', stroke='black', angle=90) {
    var (c, w) = (1, 0);
    angle != 0 && say "<g transform='rotate(#{angle}, #{cx}, #{cy})'>";
    circle(rad, cx, cy, fill, stroke);
    say("<path d='M #{cx} #{cy + rad}A #{rad/2} #{rad/2} 0 0 #{c} #{cx} #{cy} ",
        "#{rad/2} #{rad/2} 0 0 #{w} #{cx} #{cy - rad} #{rad} #{rad} 0 0 #{c} #{cx} ",
        "#{cy + rad} z' fill='#{stroke}' stroke='none' />");
    circle(rad/5, cx, cy + rad/2, fill, stroke);
    circle(rad/5, cx, cy - rad/2, stroke, fill);
    angle != 0 && say "</g>";
}

say '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">';

yin_yang(40, 50, 50);
yin_yang(20, 120, 120);

say '</svg>';


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="600" height="600">

<!-- We create the symbol in the rectangle from (0, 0) to (1, 1)
and then translate it so it's centered on the origin. -->
<symbol id="yinyang">
  <g transform="translate(-0.5, -0.5)">
    <!-- A white circle, for the bulk of the left-hand part -->
    <circle cx="0.5" cy="0.5" r="0.5" fill="white"/>
    <!-- A black semicircle, for the bulk of the right-hand part -->
    <path d="M 0.5,0 A 0.5,0.5 0 0,1 0.5,1 z" fill="black"/>
    <!-- Circles to extend each part -->
    <circle cx="0.5" cy="0.25" r="0.25" fill="white"/>
    <circle cx="0.5" cy="0.75" r="0.25" fill="black"/>
    <!-- The spots -->
    <circle cx="0.5" cy="0.25" r="0.1" fill="black"/>
    <circle cx="0.5" cy="0.75" r="0.1" fill="white"/>
    <!-- An outline for the whole shape -->
    <circle cx="0.5" cy="0.5" r="0.5" fill="none"
      stroke="gray" stroke-width=".01"/>
  </g>
</symbol>

<use xlink:href="#yinyang"
  transform="translate(125, 125) scale(200, 200)"/>

<use xlink:href="#yinyang"
  transform="translate(375, 375) scale(400, 400)"/>

</svg>


version = "1.0"
xmlheader := "<?xml version=" . version . "?>" . "<" . root . ">"

element("root", "child")
element("root", "element", "more text here")
element("root_child", "kid", "yak yak")
MsgBox % xmlheader . serialize("root")
Return

element(parent, name, text="")
{
  Global
  %parent%_children .= name . "`n"
  %parent%_%name% = %parent%_%name%
  %parent%_%name%_name := name
  %parent%_%name%_text := text
}

serialize(root){
  StringSplit, root, root, _
  xml .= "<" . root%root0% . ">"
  StringTrimRight, %root%_children, %root%_children, 1
  Loop, Parse, %root%_children, `n
  {
    If %root%_%A_LoopField%_children
      xml .= serialize(%root%_%A_LoopField%)
    Else
    {
      element := "<" . %root%_%A_LoopField%_name . ">"
      element .= %root%_%A_LoopField%_text
      element .= "</" . %root%_%A_LoopField%_name . ">"
      xml .= element
    }
  }
  Return xml .= "</" . root%root0% . ">"
}


(     ("?"."xml version=\"1.0\" ")
      \n
      (root.,"\n    " (element.,"
        Some text here
    ") \n)
  : ?xml
& out$(toML$!xml)
);


#include <libxml/parser.h>
#include <libxml/tree.h>

int main()
{
  xmlDoc *doc = xmlNewDoc("1.0");
  xmlNode *root = xmlNewNode(NULL, BAD_CAST "root");
  xmlDocSetRootElement(doc, root);

  xmlNode *node = xmlNewNode(NULL, BAD_CAST "element");
  xmlAddChild(node, xmlNewText(BAD_CAST "some text here"));
  xmlAddChild(root, node);

  xmlSaveFile("myfile.xml", doc);

  xmlFreeDoc(doc);
  xmlCleanupParser();
}


package require Tcl 8.5
package require Tk

namespace import tcl::mathop::\[-+\]    ;# Shorter coordinate math
proc yinyang {c x y r {colors {white black}}} {
    lassign $colors a b
    set tt [expr {$r * 2 / 3.0}]
    set h [expr {$r / 2.0}]
    set t [expr {$r / 3.0}]
    set s [expr {$r / 6.0}]
    $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \
	-fill $a -outline {} -extent 180 -start 90
    $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \
	-fill $b -outline {} -extent 180 -start 270
    $c create oval [- $x $h] [- $y $r] [+ $x $h] $y \
	-fill $a -outline {}
    $c create oval [- $x $h] [+ $y $r] [+ $x $h] $y \
	-fill $b -outline {}
    $c create oval [- $x $s] [- $y $tt] [+ $x $s] [- $y $t] \
	-fill $b -outline {}
    $c create oval [- $x $s] [+ $y $tt] [+ $x $s] [+ $y $t] \
	-fill $a -outline {}
}

pack [canvas .c -width 300 -height 300 -background gray50]
yinyang .c 110 110 90
yinyang .c 240 240 40


#!/usr/bin/env bash
in_circle() { #(cx, cy, r, x y)
  # return true if the point (x,y) lies within the circle of radius r centered
  # on (cx,cy)
  # (but really scaled to an ellipse with vertical minor semiaxis r and
  # horizontal major semiaxis 2r)
  local -i cx=$1 cy=$2 r=$3 x=$4 y=$5
  local -i dx dy
  (( dx=(x-cx)/2, dy=y-cy, dx*dx + dy*dy <= r*r ))
}

taijitu() { #radius
  local -i radius=${1:-17}
  local -i x1=0 y1=0 r1=radius            # outer circle
  local -i x2=0 y2=-radius/2 r2=radius/6  # upper eye
  local -i x3=0 y3=-radius/2 r3=radius/2  # upper half
  local -i x4=0 y4=+radius/2 r4=radius/6  # lower eye
  local -i x5=0 y5=+radius/2 r5=radius/2  # lower half
  local -i x y
  for (( y=radius; y>=-radius; --y )); do
    for (( x=-2*radius; x<=2*radius; ++x)); do
      if ! in_circle $x1 $y1 $r1 $x $y; then
        printf ' '
      elif in_circle $x2 $y2 $r2 $x $y; then
        printf '#'
      elif in_circle $x3 $y3 $r3 $x $y; then
        printf '.'
      elif in_circle $x4 $y4 $r4 $x $y; then
        printf '.'
      elif in_circle $x5 $y5 $r5 $x $y; then
        printf '#'
      elif (( x <= 0 )); then
        printf '.'
      else
        printf '#'
      fi
    done
    printf '\n'
  done
}


using System.Xml;
using System.Xml.Serialization;
[XmlRoot("root")]
public class ExampleXML
{
    [XmlElement("element")]
    public string element = "Some text here";
    static void Main(string[] args)
    {
        var xmlnamespace = new XmlSerializerNamespaces();
        xmlnamespace.Add("", ""); //used to stop default namespaces from printing
        var writer = XmlWriter.Create("output.xml");
        new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
    }
    //Output: <?xml version="1.0" encoding="utf-8"?><root><element>Some text here</element></root>
}


#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>

#ifndef LIBXML_TREE_ENABLED
#   error libxml was not configured with DOM tree support
#endif

#ifndef LIBXML_OUTPUT_ENABLED
#   error libxml was not configured with serialization support
#endif

// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
//   1) a ScopeGuard-like type to handle cleanup functions; and
//   2) an exception type that transforms the library's errors.

// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
    // C++20: Constructor can (and should) be [[nodiscard]].
    /*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
        f_{std::move(f)}
    {}

    ~scope_exit()
    {
        f_();
    }

    // Non-copyable, non-movable.
    scope_exit(scope_exit const&) = delete;
    scope_exit(scope_exit&&) = delete;
    auto operator=(scope_exit const&) -> scope_exit& = delete;
    auto operator=(scope_exit&&) -> scope_exit& = delete;

private:
    F f_;
};

// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
    libxml_error() : libxml_error(std::string{}) {}

    explicit libxml_error(std::string message) :
        std::runtime_error{make_message_(std::move(message))}
    {}

private:
    static auto make_message_(std::string message) -> std::string
    {
        if (auto const last_error = ::xmlGetLastError(); last_error)
        {
            if (not message.empty())
                message += ": ";
            message += last_error->message;
        }

        return message;
    }
};

auto add_text(::xmlNode* node, ::xmlChar const* content)
{
    // Create a new text node with the desired content.
    auto const text_node = ::xmlNewText(content);
    if (not text_node)
        throw libxml_error{"failed to create text node"};

    // Try to add it to the node. If it succeeds, that node will take
    // ownership of the text node. If it fails, we have to clean up the text
    // node ourselves first, then we can throw.
    if (auto const res = ::xmlAddChild(node, text_node); not res)
    {
        ::xmlFreeNode(text_node);
        throw libxml_error{"failed to add text node"};
    }

    return text_node;
}

auto main() -> int
{
    // Set this to true if you don't want the XML declaration.
    constexpr auto no_xml_declaration = false;

    try
    {
        // Initialize libxml.
        ::xmlInitParser();
        LIBXML_TEST_VERSION
        auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};

        // Create a new document.
        auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
        if (not doc)
            throw libxml_error{"failed to create document"};
        auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};

        // Create the root element.
        auto root = ::xmlNewNode(nullptr,
            reinterpret_cast<::xmlChar const*>(u8"root"));
        if (not root)
            throw libxml_error{"failed to create root element"};
        ::xmlDocSetRootElement(doc, root); // doc now owns root

        // Add whitespace. Unless you know the whitespace is not significant,
        // you should do this manually, rather than relying on automatic
        // indenting.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n    "));

        // Add the child element.
        if (auto const res = ::xmlNewTextChild(root, nullptr,
                reinterpret_cast<::xmlChar const*>(u8"element"),
                reinterpret_cast<::xmlChar const*>(
                    u8"\n        Some text here\n    "));
                not res)
            throw libxml_error{"failed to create child text element"};

        // Add whitespace.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));

        // Output tree. Note that the output is UTF-8 in all cases. If you
        // want something different, use xmlSaveFileEnc() or the second
        // argument of xmlSaveDoc().
        if constexpr (no_xml_declaration)
        {
            auto const save_context = ::xmlSaveToFilename("-", nullptr,
                XML_SAVE_NO_DECL);
            auto const save_context_cleanup = scope_exit{[save_context] {
                ::xmlSaveClose(save_context); }};

            if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
        else
        {
            if (auto const res = ::xmlSaveFile("-", doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
    }
    catch (std::exception const& x)
    {
        std::cerr << "ERROR: " << x.what() << '\n';
        return EXIT_FAILURE;
    }
}


var inCircle = Fn.new { |centerX, centerY, radius, x, y|
    return (x-centerX)*(x-centerX)+(y-centerY)*(y-centerY) <= radius*radius
}

var inBigCircle        = Fn.new { |radius, x, y| inCircle.call(0, 0, radius, x, y) }

var inBlackSemiCircle  = Fn.new { |radius, x, y|  inCircle.call(0, -radius/2, radius/2, x, y) }

var inWhiteSemiCircle  = Fn.new { |radius, x, y|  inCircle.call(0,  radius/2, radius/2, x, y) }

var inSmallBlackCircle = Fn.new { |radius, x, y| inCircle.call(0,  radius/2, radius/6, x, y) }

var inSmallWhiteCircle = Fn.new { |radius, x, y| inCircle.call(0, -radius/2, radius/6, x, y) }

var yinAndYang = Fn.new { |radius|
    var black = "#"
    var white = "."
    var scaleX = 2
    var scaleY = 1
    for (sy in radius*scaleY..-(radius*scaleY)) {
        for (sx in -(radius*scaleX)..(radius*scaleX)) {
            var x = sx / scaleX
            var y = sy / scaleY
            if (inBigCircle.call(radius, x, y)) {
                if (inWhiteSemiCircle.call(radius, x, y)) {
                    System.write(inSmallBlackCircle.call(radius, x, y) ? black : white)
                } else if (inBlackSemiCircle.call(radius, x, y)) {
                    System.write(inSmallWhiteCircle.call(radius, x, y) ? white : black)
                } else {
                    System.write((x < 0) ? white : black)
                }
            } else {
                System.write(" ")
            }
        }
        System.print()
    }
}

yinAndYang.call(16)
yinAndYang.call(8)


USER>set writer=##class(%XML.Writer).%New()
USER>set writer.Charset="UTF-8"
USER>Set writer.Indent=1
USER>Set writer.IndentChars="    "
USER>set sc=writer.OutputToString()
USER>set sc=writer.RootElement("root")
USER>set sc=writer.Element("element")
USER>set sc=writer.WriteChars("Some text here")
USER>set sc=writer.EndElement()
USER>set sc=writer.EndRootElement()
USER>Write writer.GetXMLString()

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element>Some text here</element>
</root>


(require '[clojure.data.xml :as xml])

(def xml-example (xml/element :root {} (xml/element :element {} "Some text here")))

(with-open [out-file (java.io.OutputStreamWriter.
                        (java.io.FileOutputStream. "/tmp/output.xml") "UTF-8")]
  (xml/emit xml-example out-file))


(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))
       (root (dom:create-element doc "root"))
       (element (dom:create-element doc "element"))
       (text (dom:create-text-node doc "Some text here")))
  (dom:append-child element text)
  (dom:append-child root element)
  (dom:append-child doc root)
  (dom:map-document (cxml:make-rod-sink) doc))


module xmltest ;

import std.stdio ;
import std.xml ;

void main() {
  auto doc = new Document("root") ;
//doc.prolog = q"/<?xml version="1.0"?>/" ; // default
  doc ~= new Element("element", "Some text here") ;
  writefln(doc) ;
// output: <?xml version="1.0"?><root><element>Some text here</element></root>
}


include c:\cxpl\codes;          \intrinsic 'code' declarations

def Black=0, Red=4, White=$F;

proc Circle(X0, Y0, R, CL, CR); \Show a filled circle
int X0, Y0, R, CL, CR;          \left and right half colors
int X, Y;
[for Y:= -R to R do
    for X:= -R to R do
        if X*X + Y*Y <= R*R then
            Point(X+X0, Y+Y0, if X<0 then CL else CR);
]; \Circle

proc YinYang(X0, Y0, R);
int  X0, Y0, R;
[Circle(X0, Y0,     R,   White, Black);
 Circle(X0, Y0-R/2, R/2, White, White);
 Circle(X0, Y0-R/2, R/6, Black, Black);
 Circle(X0, Y0+R/2, R/2, Black, Black);
 Circle(X0, Y0+R/2, R/6, White, White);
]; \YinYang

[SetVid($101);                  \640x480 graphics
Circle(320, 240, 400, Red, Red);\fill screen with background color
YinYang(80, 80, 70);
YinYang(240, 240, 150);
if ChIn(1) then [];             \wait for keystroke
SetVid(3);                      \restore normal text mode
]


fcn draw_yinyang(trans,scale){
   0'|<use xlink:href="#y" transform="translate(%d,%d) scale(%g)"/>|
   .fmt(trans,trans,scale).print();
}

print(
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n"
"	'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n"
"<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\n"
"	xmlns:xlink='http://www.w3.org/1999/xlink'\n"
"		width='30' height='30'>\n"
"	<defs><g id='y'>\n"
"		<circle cx='0' cy='0' r='200' stroke='black'\n"
"			fill='white' stroke-width='1'/>\n"
"		<path d='M0 -200 A 200 200 0 0 0 0 200\n"
"			100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n"
"			z' fill='black'/>\n"
"		<circle cx='0' cy='100' r='33' fill='white'/>\n"
"		<circle cx='0' cy='-100' r='33' fill='black'/>\n"
"	</g></defs>\n");

draw_yinyang(20, 0.05);
draw_yinyang( 8, 0.02);
print("</svg>");


def document := <unsafe:javax.xml.parsers.makeDocumentBuilderFactory> \
                  .newInstance() \
                  .newDocumentBuilder() \
                  .getDOMImplementation() \
                  .createDocument(null, "root", null)
def root := document.getDocumentElement()
root.appendChild(
  def element := document.createElement("element"))
element.appendChild(
  document.createTextNode("Some text here"))
println(document.saveXML(root))


open System.Xml

[<EntryPoint>]
let main argv =
    let xd = new XmlDocument()
    // Create the required nodes:
    xd.AppendChild (xd.CreateXmlDeclaration("1.0", null, null)) |> ignore
    let root = xd.AppendChild (xd.CreateNode("element", "root", ""))
    let element = root.AppendChild (xd.CreateElement("element", "element", ""))
    element.AppendChild (xd.CreateTextNode("Some text here")) |> ignore
    // The same can be accomplished with:
    // xd.LoadXml("""<?xml version="1.0"?><root><element>Some text here</element></root>""")

    let xw = new XmlTextWriter(System.Console.Out)
    xw.Formatting <- Formatting.Indented
    xd.WriteContentTo(xw)
    0


USING: xml.syntax xml.writer ;

<XML <root><element>Some text here</element></root> XML>
pprint-xml


using xml

class XmlDom
{
  public static Void main ()
  {
    doc := XDoc()
    root := XElem("root")
    doc.add (root)

    child := XElem("element")
    child.add(XText("Some text here"))
    root.add (child)

    doc.write(Env.cur.out)
  }
}


include ffl/dom.fs

\ Create a dom variable 'doc' in the dictionary

dom-create doc

\ Add the document root with its version attribute

dom.document doc dom-append-node

s" version" s" 1.0" dom.attribute doc dom-append-node

\ Add root and element

doc dom-parent 2drop

s" root"    dom.element doc dom-append-node

s" element" dom.element doc dom-append-node

\ Add the text

s" Some text here" dom.text doc dom-append-node

\ Convert the document to a string and print

doc dom-write-string [IF]
  type cr
[THEN]


package main

import (
    "fmt"
    dom "gitlab.com/stone.code/xmldom-go.git"
)

func main() {
    d, err := dom.ParseStringXml(`
<?xml version="1.0" ?>
<root>
    <element>
        Some text here
    </element>
</root>`)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(d.ToXml()))
}


import groovy.xml.MarkupBuilder
def writer = new StringWriter() << '<?xml version="1.0" ?>\n'
def xml = new MarkupBuilder(writer)
xml.root() {
    element('Some text here' )
}
println writer


import Data.List
import Text.XML.Light

xmlDOM :: String -> String
xmlDOM txt = showTopElement $ Element
    (unqual "root")
    []
    [ Elem $ Element
      (unqual "element")
      []
      [Text $ CData CDataText txt Nothing]
      Nothing
    ]
    Nothing


serialize=: ('<?xml version="1.0" ?>',LF),;@serialize1&''
serialize1=:4 :0
  if.L.x do.
    start=. y,'<',(0{::x),'>',LF
    middle=. ;;(}.x) serialize1&.> <'    ',y
    end=. y,'</',(0{::x),'>',LF
    <start,middle,end
  else.
    <y,x,LF
  end.
)


import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class RDOMSerialization {

  private Document domDoc;

  public RDOMSerialization() {
    return;
  }

  protected void buildDOMDocument() {

    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    DOMImplementation impl;
    Element elmt1;
    Element elmt2;

    try {
      factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
      impl = builder.getDOMImplementation();
      domDoc = impl.createDocument(null, null, null);
      elmt1 = domDoc.createElement("root");
      elmt2 = domDoc.createElement("element");
      elmt2.setTextContent("Some text here");

      domDoc.appendChild(elmt1);
      elmt1.appendChild(elmt2);
    }
    catch (ParserConfigurationException ex) {
      ex.printStackTrace();
    }

    return;
  }

  protected void serializeXML() {

    DOMSource domSrc;
    Transformer txformer;
    StringWriter sw;
    StreamResult sr;

    try {
      domSrc = new DOMSource(domDoc);

      txformer = TransformerFactory.newInstance().newTransformer();
      txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      txformer.setOutputProperty(OutputKeys.METHOD, "xml");
      txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      txformer.setOutputProperty(OutputKeys.INDENT, "yes");
      txformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
      txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      sw = new StringWriter();
      sr = new StreamResult(sw);

      txformer.transform(domSrc, sr);

      System.out.println(sw.toString());
    }
    catch (TransformerConfigurationException ex) {
      ex.printStackTrace();
    }
    catch (TransformerFactoryConfigurationError ex) {
      ex.printStackTrace();
    }
    catch (TransformerException ex) {
      ex.printStackTrace();
    }

    return;
  }

  public static void serializationDriver(String[] args) {

    RDOMSerialization lcl = new RDOMSerialization();
    lcl.buildDOMDocument();
    lcl.serializeXML();

    return;
  }

  public static void main(String[] args) {
    serializationDriver(args);
    return;
  }
}


var doc = document.implementation.createDocument( null, 'root', null );
var root = doc.documentElement;
var element = doc.createElement( 'element' );
root.appendChild( element );
element.appendChild( document.createTextNode('Some text here') );
var xmlString = new XMLSerializer().serializeToString( doc );


using LightXML

# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.

# create an empty XML document
xdoc = XMLDocument()

# create & attach a root node
xroot = create_root(xdoc, "root")

# create the first child
xs1 = new_child(xroot, "element")

# add the inner content
add_text(xs1, "some text here")

println(xdoc)


// version 1.1.3

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory

fun main(args: Array<String>) {
    val dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val doc = dBuilder.newDocument()
    val root = doc.createElement("root")  // create root node
    doc.appendChild(root)
    val element = doc.createElement("element")  // create element node
    val text = doc.createTextNode("Some text here")  // create text node
    element.appendChild(text)
    root.appendChild(element)

    // serialize
    val source = DOMSource(doc)
    val sw = StringWriter()
    val result = StreamResult(sw)
    val tFactory = TransformerFactory.newInstance()
    tFactory.newTransformer().apply {
        setOutputProperty("indent", "yes")
        setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
        transform(source, result)
    }
    println(sw)
}


content_type( 'text/xml' );// set MIME type if serving

xml( '<?xml version="1.0" ?><root><element>Some text here</element></root>' );


-- create an XML document
doc = newObject("XML", "<?xml version='1.0' ?>")

root = doc.createElement("root")
doc.appendChild(root)

element = doc.createElement("element")
root.appendChild(element)

textNode = doc.createTextNode("Some text here")
element.appendChild(textNode)

put doc.toString()
-- "<?xml version='1.0' ?><root><element>Some text here</element></root>"


require("LuaXML")
local dom = xml.new("root")
local element = xml.new("element")
table.insert(element, "Some text here")
dom:append(element)
dom:save("dom.xml")


DOM = XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0","Encoding" -> "utf-8"]},
XMLElement["root", {}, {XMLElement["element", {}, {"Some text here"}]}], {}];
ExportString[DOM, "XML", "AttributeQuoting" -> "\""]


docNode = com.mathworks.xml.XMLUtils.createDocument('root');
docRootNode = docNode.getDocumentElement;
thisElement = docNode.createElement('element');
thisElement.appendChild(docNode.createTextNode('Some text here'));
docRootNode.appendChild(thisElement);


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

import java.io.StringWriter
import javax.xml.
import org.w3c.dom.

class RDOMSerialization public

properties private
  domDoc = Document

method main(args = String[]) public static

  lcl = RDOMSerialization()
  lcl.buildDOMDocument()
  lcl.serializeXML()

  return

method buildDOMDocument() inheritable

  do
    factory = DocumentBuilderFactory.newInstance()
    builder = factory.newDocumentBuilder()
    impl = builder.getDOMImplementation()
    domDoc = impl.createDocument(null, null, null)
    elmt1 = domDoc.createElement("root")
    elmt2 = domDoc.createElement("element")
    elmt2.setTextContent("Some text here")

    domDoc.appendChild(elmt1)
    elmt1.appendChild(elmt2)

  catch exPC = ParserConfigurationException
    exPC.printStackTrace
  end

  return

method serializeXML() inheritable

  do
    domSrc = DOMSource(domDoc)
    txformer = TransformerFactory.newInstance().newTransformer()
    txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
    txformer.setOutputProperty(OutputKeys.METHOD, "xml")
    txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
    txformer.setOutputProperty(OutputKeys.INDENT, "yes")
    txformer.setOutputProperty(OutputKeys.STANDALONE, "yes")
    txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")

    sw = StringWriter()
    sr = StreamResult(sw)

    txformer.transform(domSrc, sr)

    say sw.toString

  catch exTC = TransformerConfigurationException
    exTC.printStackTrace
  catch exTF = TransformerFactoryConfigurationError
    exTF.printStackTrace
  catch exTE = TransformerException
    exTE.printStackTrace
  end

  return


import xmldom

var
  dom = getDOM()
  document = dom.createDocument("", "root")
  topElement = document.documentElement
  firstElement = document.createElement "element"
  textNode = document.createTextNode "Some text here"

topElement.appendChild firstElement
firstElement.appendChild textNode

echo document


use XML;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      builder := XMLBuilder->New("root", "1.0");
      root := builder->GetRoot();
      element := XMLElement->New(XMLElementType->ELEMENT, "element", "Some text here");
      root->AddChild(element);
      builder->ToString()->PrintLine();
    }
  }
}


DEFINE VARIABLE hxdoc      AS HANDLE NO-UNDO.
DEFINE VARIABLE hxroot     AS HANDLE NO-UNDO.
DEFINE VARIABLE hxelement  AS HANDLE NO-UNDO.
DEFINE VARIABLE hxtext     AS HANDLE NO-UNDO.
DEFINE VARIABLE lcc        AS LONGCHAR NO-UNDO.

CREATE X-DOCUMENT hxdoc.

CREATE X-NODEREF hxroot.
hxdoc:CREATE-NODE( hxroot, 'root', 'ELEMENT' ).
hxdoc:APPEND-CHILD( hxroot ).

CREATE X-NODEREF hxelement.
hxdoc:CREATE-NODE( hxelement, 'element', 'ELEMENT' ).
hxroot:APPEND-CHILD( hxelement ).

CREATE X-NODEREF hxtext.
hxdoc:CREATE-NODE( hxtext, 'element', 'TEXT' ).
hxelement:APPEND-CHILD( hxtext ).
hxtext:NODE-VALUE = 'Some text here'.

hxdoc:SAVE( 'LONGCHAR', lcc ).
MESSAGE STRING( lcc ) VIEW-AS ALERT-BOX.


declare
  proc {Main}
   DOM = root(element("Some text here"))
  in
     {System.showInfo {Serialize DOM}}
  end
  ...


program CrearXML;

{$mode objfpc}{$H+}

uses
  Classes, XMLWrite, DOM;

var
  xdoc: TXMLDocument;                                  // variable objeto documento XML
  NodoRaiz, NodoPadre, NodoHijo: TDOMNode;             // variables a los nodos
begin
  //crear el documento
  xdoc := TXMLDocument.create;

  NodoRaiz := xdoc.CreateElement('root');               // crear el nodo raíz
  Xdoc.Appendchild(NodoRaiz);                           // guardar nodo raíz
  NodoPadre := xdoc.CreateElement('element');           // crear el nodo hijo
  NodoHijo := xdoc.CreateTextNode('Some text here');    // insertar el valor del nodo
  NodoPadre.Appendchild(NodoHijo);                      // guardar nodo
  NodoRaiz.AppendChild(NodoPadre);                      // insertar el nodo hijo en el correspondiente nodo padre
  writeXMLFile(xDoc,'prueba.xml');                      // escribir el XML
  NodoRaiz.free;
  NodoPadre.free;
  NodoHijo.free;
  Xdoc.free;
end.


use XML::Simple;
print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" );


with javascript_semantics
include builtins/xml.e
sequence elem = xml_new_element("element", "Some text here"),
         root = xml_new_element("root", {elem}),
         doc = xml_new_doc(root,{`<?xml version="1.0" ?>`})
puts(1,xml_sprint(doc))


<?php
$dom = new DOMDocument();//the constructor also takes the version and char-encoding as it's two respective parameters
$dom->formatOutput = true;//format the outputted xml
$root = $dom->createElement('root');
$element = $dom->createElement('element');
$element->appendChild($dom->createTextNode('Some text here'));
$root->appendChild($element);
$dom->appendChild($root);
$xmlstring = $dom->saveXML();


(load "@lib/xm.l")

(xml? T)
(xml '(root NIL (element NIL "Some text here")))


object dom = Parser.XML.Tree.SimpleRootNode();
dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), ""));
object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "root", ([]), "");
dom->add_child(node);

object subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "element", ([]), "");
node->add_child(subnode);

node = subnode;
subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "Some text here");
node->add_child(subnode);

dom->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"


from xml.dom.minidom import getDOMImplementation

dom = getDOMImplementation()
document = dom.createDocument(None, "root", None)

topElement = document.documentElement
firstElement = document.createElement("element")
topElement.appendChild(firstElement)
textNode = document.createTextNode("Some text here")
firstElement.appendChild(textNode)

xmlString = document.toprettyxml(" " * 4)


#lang at-exp racket
(require xml)

(define xml-str
  @~a{<?xml version="1.0" ?>
       <root>
           <element>
               Some text here
           </element>
       </root>})

;; read & parse to get an xml value
(define xml (read-xml/document (open-input-string xml-str)))
;; print it out in xml form, which is identical to the input xml
(write-xml xml)
(newline)


use XML;
use XML::Writer;

say my $document = XML::Document.new(
    XML::Writer.serialize( :root[ :element['Some text here', ], ] )
);


import lang::xml::DOM;

public void main(){
	x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])]));
	return println(xmlPretty(x));
}


require("rexml/document")
include REXML
(doc = Document.new) << XMLDecl.new
root = doc.add_element('root')
element = root.add_element('element')
element.add_text('Some text here')

# save to a string
# (the first argument to write() needs an object that understands "<<")
serialized = String.new
doc.write(serialized, 4)
puts serialized


val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null)


require('XML::Simple');
print %S'XML::Simple'.XMLout(
    :(root => :( element => 'Some text here' )),
    NoAttr => 1, RootName => '',
);