task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Julia
Julia
using Images, FileIO, Netpbm   rgbimg = load("data/bitmapInputTest.ppm") greyimg = Gray.(rgbimg) save("data/bitmapOutputTest.ppm", greyimg)
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Kotlin
Kotlin
// Version 1.2.40   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage import java.io.FileInputStream import java.io.PushbackInputStream import java.io.File import javax.imageio.ImageIO   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)   fun fill(c: Color) { val g = image.graphics g.color = c g.fillRect(0, 0, image.width, image.height) }   fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())   fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))   fun toGrayScale() { for (x in 0 until image.width) { for (y in 0 until image.height) { var rgb = image.getRGB(x, y) val red = (rgb shr 16) and 0xFF val green = (rgb shr 8) and 0xFF val blue = rgb and 0xFF val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() rgb = (lumin shl 16) or (lumin shl 8) or lumin image.setRGB(x, y, rgb) } } } }   fun PushbackInputStream.skipComment() { while (read().toChar() != '\n') {} }   fun PushbackInputStream.skipComment(buffer: ByteArray) { var nl: Int while (true) { nl = buffer.indexOf(10) // look for newline at end of comment if (nl != -1) break read(buffer) // read another buffer full if newline not yet found } val len = buffer.size if (nl < len - 1) unread(buffer, nl + 1, len - nl - 1) }   fun Byte.toUInt() = if (this < 0) 256 + this else this.toInt()   fun main(args: Array<String>) { // use file, output.ppm, created in the Bitmap/Write a PPM file task val pbis = PushbackInputStream(FileInputStream("output.ppm"), 80) pbis.use { with (it) { val h1 = read().toChar() val h2 = read().toChar() val h3 = read().toChar() if (h1 != 'P' || h2 != '6' || h3 != '\n') { println("Not a P6 PPM file") System.exit(1) } val sb = StringBuilder() while (true) { val r = read().toChar() if (r == '#') { skipComment(); continue } if (r == ' ') break // read until space reached sb.append(r.toChar()) } val width = sb.toString().toInt() sb.setLength(0) while (true) { val r = read().toChar() if (r == '#') { skipComment(); continue } if (r == '\n') break // read until new line reached sb.append(r.toChar()) } val height = sb.toString().toInt() sb.setLength(0) while (true) { val r = read().toChar() if (r == '#') { skipComment(); continue } if (r == '\n') break // read until new line reached sb.append(r.toChar()) } val maxCol = sb.toString().toInt() if (maxCol !in 0..255) { println("Maximum color value is outside the range 0..255") System.exit(1) } var buffer = ByteArray(80) // get rid of any more opening comments before reading data while (true) { read(buffer) if (buffer[0].toChar() == '#') { skipComment(buffer) } else { unread(buffer) break } } // read data val bbs = BasicBitmapStorage(width, height) buffer = ByteArray(width * 3) var y = 0 while (y < height) { read(buffer) for (x in 0 until width) { val c = Color( buffer[x * 3].toUInt(), buffer[x * 3 + 1].toUInt(), buffer[x * 3 + 2].toUInt() ) bbs.setPixel(x, y, c) } y++ } // convert to grayscale and save to a file bbs.toGrayScale() val grayFile = File("output_gray.jpg") ImageIO.write(bbs.image, "jpg", grayFile) } } }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#360_Assembly
360 Assembly
FALSE DC X'00' TRUE DC X'FF'
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#6502_Assembly
6502 Assembly
clr bit ; clears setb bit ; sets
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Red
Red
  Red ["Ceasar Cipher"]   rot: func [ char [char!] key [number!] ofs [char!] ][ to-char key + char - ofs // 26 + ofs ]   caesar: function [ src [string!] key [integer!] ][ lower: charset [#"a" - #"z"] upper: charset [#"A" - #"Z"] parse src [ any [ change s: [lower (o: #"a") | upper (o: #"A")] (rot s/1 key o) | skip ] ] src ]   encrypt: :caesar decrypt: func spec-of :caesar [caesar src negate key]  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Delphi
Delphi
  program Bitwise_IO;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Classes;   type TBitReader = class private readData: Cardinal; startPosition: Integer; endPosition: Integer; Stream: TStream; procedure Align; function BaseStream: TStream; procedure EnsureData(bitCount: Integer); function GetInBuffer: Integer; public constructor Create(sm: TStream); function Read(bitCount: Integer): Integer; function ReadBit: Boolean; end;   TBitWriter = class private data: Byte; dataLength: Integer; Stream: TStream; procedure Align; function BaseStream: TStream; function BitsToAligment: Integer; public constructor Create(sm: TStream); procedure Write(value, length: Integer); procedure WriteBit(value: Boolean); end;   function TBitReader.GetInBuffer: Integer; begin result := endPosition - startPosition; end;   function TBitReader.BaseStream: TStream; begin result := stream; end;   constructor TBitReader.Create(sm: TStream); begin Stream := sm; end;   procedure TBitReader.EnsureData(bitCount: Integer); var readBits: Integer; b: Byte; begin readBits := bitCount - GetInBuffer; while readBits > 0 do begin BaseStream.Read(b, 1); readData := readData or (b shl endPosition); endPosition := endPosition + 8; readBits := readBits - 8; end; end;   function TBitReader.ReadBit: Boolean; begin Exit(Read(1) > 0); end;   function TBitReader.Read(bitCount: Integer): Integer; begin EnsureData(bitCount); result := (readData shr startPosition) and ((1 shl bitCount) - 1); startPosition := startPosition + bitCount; if endPosition = startPosition then begin endPosition := ord(startPosition = 0); readData := 0; end else if (startPosition >= 8) then begin readData := readData shr startPosition; endPosition := endPosition - startPosition; startPosition := 0; end; end;   procedure TBitReader.Align; begin endPosition := ord(startPosition = 0); readData := 0; end;   function TBitWriter.BaseStream: TStream; begin Exit(stream); end;   function TBitWriter.BitsToAligment: Integer; begin Exit((32 - dataLength) mod 8); end;   constructor TBitWriter.Create(sm: TStream); begin Stream := sm; end;   procedure TBitWriter.WriteBit(value: Boolean); begin self.Write(ord(value), 1); end;   procedure TBitWriter.Write(value, length: Integer); var currentData: Cardinal; currentLength: Integer; begin currentData := data or (value shl dataLength); currentLength := dataLength + length; while currentLength >= 8 do begin   BaseStream.Write(currentData, 1); currentData := currentData shr 8; currentLength := currentLength - 8; end; data := currentData; dataLength := currentLength; end;   procedure TBitWriter.Align; begin if dataLength > 0 then begin BaseStream.Write(data, 1); data := 0; dataLength := 0; end; end;   var ms: TMemoryStream; writer: TBitWriter; reader: TBitReader;   begin ms := TMemoryStream.create(); writer := TBitWriter.create(ms); writer.WriteBit(true); writer.Write(5, 3); writer.Write($0155, 11); writer.Align(); ms.Position := 0; reader := TBitReader.create(ms); writeln(reader.ReadBit()); writeln(reader.Read(3)); writeln(format('0x%.4x', [reader.Read(11)])); reader.Align(); ms.Free; writer.Free; reader.Free; Readln; end.
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Euphoria
Euphoria
constant dimx = 800, dimy = 800 constant fn = open("first.ppm","wb") -- b - binary mode sequence color printf(fn, "P6\n%d %d\n255\n", {dimx,dimy}) for j = 0 to dimy-1 do for i = 0 to dimx-1 do color = { remainder(i,256), -- red remainder(j,256), -- green remainder(i*j,256) -- blue } puts(fn,color) end for end for close(fn)
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#FBSL
FBSL
#ESCAPECHARS ON   DIM bmpin = ".\\LenaClr.bmp", ppmout = ".\\Lena.ppm", bmpblob = 54 ' Size of BMP file headers FILEGET(FILEOPEN(bmpin, BINARY), FILELEN(bmpin)): FILECLOSE(FILEOPEN) ' Fill buffer   DIM ppmheader AS STRING * 256, breadth, height LET(breadth, height) = 128 ' Image width and height SPRINTF(ppmheader, "P6\n%d %d\n255\n", breadth, height) ' Create PPM file header   DIM ppmdata AS STRING * (STRLEN(ppmheader) + FILELEN - bmpblob) DIM head = @ppmdata + STRLEN, tail = @FILEGET + FILELEN - breadth * 3 - 2 ' Start of last scanline ppmdata = ppmheader ' Copy PPM file header   WHILE tail >= @FILEGET + bmpblob ' Flip upside down FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B NEXT INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline WEND   FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN)
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Lua
Lua
function Read_PPM( filename ) local fp = io.open( filename, "rb" ) if fp == nil then return nil end   local data = fp:read( "*line" ) if data ~= "P6" then return nil end   repeat data = fp:read( "*line" ) until string.find( data, "#" ) == nil   local image = {} local size_x, size_y   size_x = string.match( data, "%d+" ) size_y = string.match( data, "%s%d+" )   data = fp:read( "*line" ) if tonumber(data) ~= 255 then return nil end   for i = 1, size_x do image[i] = {} end   for j = 1, size_y do for i = 1, size_x do image[i][j] = { string.byte( fp:read(1) ), string.byte( fp:read(1) ), string.byte( fp:read(1) ) } end end   fp:close()   return image end
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#68000_Assembly
68000 Assembly
clr bit ; clears setb bit ; sets
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#8051_Assembly
8051 Assembly
clr bit ; clears setb bit ; sets
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Retro
Retro
{{ variable offset  : rotate ( cb-c ) tuck - @offset + 26 mod + ;  : rotate? ( c-c ) dup 'a 'z within [ 'a rotate ] ifTrue dup 'A 'Z within [ 'A rotate ] ifTrue ; ---reveal---  : ceaser ( $n-$ )  !offset dup [ [ @ rotate? ] sip ! ] ^types'STRING each@ ; }}   ( Example ) "THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string ) 23 ceaser ( returns decrypted string )
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Erlang
Erlang
-module(bitwise_io). -compile([export_all]).   %% Erlang allows for easy manipulation of bitstrings. Here I'll %% present a function that can take a message of 8-bit ASCII %% characters and remove the MSB, leaving the same message in 7-bits.   compress(Message) -> << <<X:7>> || <<X:8>> <= Message >>.   %% Here we decompress the message.   decompress(Message) -> << <<X:8>> || <<X:7>> <= Message >>.   %% Now a test to demonstrate that this conversion works:   test_bitstring_conversion() -> Message = <<"Hello, Rosetta Code!">>, io:format("~p: ~B~n",[Message, bit_size(Message)]), Compressed = compress(Message), io:format("~p: ~B~n",[Compressed, bit_size(Compressed)]), Decompressed = decompress(Compressed), io:format("~p: ~B~n",[Decompressed, bit_size(Decompressed)]), io:format("~p = ~p ? ~p~n",[Message, Decompressed, Message =:= Decompressed]).   %% Now to show this on file output, we'll write the compressed version %% to a file. Now, erlang's file:write_file expects objects that are %% multiples of 8bits. We'll add padding to allow the writing to %% complete, and then discard the padding when reading the file back %% in.   test_file_io() -> Message = <<"Hello, Rosetta Code!">>, FileName = "bitwise_io.dat", Compressed = compress(Message), PaddingSize = (8 - (bit_size(Compressed) rem 8)) rem 8, PaddedCompressed = <<Compressed:(bit_size(Compressed))/bitstring, 0:PaddingSize>>, file:write_file(FileName,PaddedCompressed), {ok, ReadIn} = file:read_file(FileName), UnpaddedSize = bit_size(ReadIn) - 7, Unpadded = case UnpaddedSize rem 7 =:= 0 of true -> <<T:(UnpaddedSize)/bitstring,_:7>> = ReadIn, T; false -> << <<X:7>> || <<X:7>> <= ReadIn >> end, Decompressed = decompress(Unpadded), io:format("~p~n",[Decompressed]).
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Forth
Forth
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ;   s" red.ppm" w/o create-file throw test over write-ppm close-file throw
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Fortran
Fortran
program main   use rgbimage_m   implicit none   integer :: nx, ny, i, j, k   type(rgbimage) :: im   ! init image of height nx, width ny nx = 400 ny = 300 call im%init(nx, ny)   ! set some random pixel data do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do   ! output image into file call im%write('fig.ppm')   end program
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function Bitmap { If match("NN") then { Read x as long, y as long } else.if Match("N") Then { \\ is a file? Read f if not Eof(f) then { Line Input #f, p3$ If p3$="P3" Then { Line Input #f, Comment$ if left$(Comment$,1)="#" then { Line Input #f, Dimension$ } else Dimension$=Comment$ long x=Val(piece$(Dimension$," ")(0)) long y=Val(piece$(Dimension$," ")(1)) do { Line Input #f, P255$ } until left$(P255$, 1)<>"#" If not P255$="255" then Error "Not proper ppm format" } } } else Error "No proper arguments"     if x<1 or y<1 then Error "Wrong dimensions" structure rgb { red as byte green as byte blue as byte } m=len(rgb)*x mod 4 if m>0 then m=4-m ' add some bytes to raster line m+=len(rgb) *x Structure rasterline { { pad as byte*m } \\ union pad+hline hline as rgb*x }   Structure Raster { magic as integer*4 w as integer*4 h as integer*4 lines as rasterline*y } Buffer Clear Image1 as Raster \\ 24 chars as header to be used from bitmap render build in functions Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) \\ fill white (all 255) \\ Str$(string) convert to ascii, so we get all characters from words width to byte width if not valid(f) then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) Buffer Clear Pad as Byte*4 SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ where=alines+3*x+blines*y if c>0 then c=color(c) c-! Return Pad, 0:=c as long Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte   } GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ where=alines+3*x+blines*y =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) } StrDib$=Lambda$ Image1, Raster -> { =Eval$(Image1, 0, Len(Raster)) } CopyImage=Lambda Image1 (image$) -> { if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { Return Image1, 0:=Image$ } Else Error "Can't Copy Image" } Export2File=Lambda Image1, x, y (f) -> { \\ use this between open and close Print #f, "P3" Print #f,"# Created using M2000 Interpreter" Print #f, x;" ";y Print #f, 255 x2=x-1 where=24 For y1= 0 to y-1 { a$="" For x1=0 to x2 { Print #f, a$;Eval(Image1, where+2 as byte);" "; Print #f, Eval(Image1, where+1 as byte);" "; Print #f, Eval(Image1, where as byte); where+=3 a$=" " } Print #f m=where mod 4 if m<>0 then where+=4-m } } if valid(F) then { 'load RGB values form file x0=x-1 where=24 For y1=y-1 to 0 { do { Line Input #f, aline$ } until left$(aline$,1)<>"#" flush ' empty stack Stack aline$ ' place all values to stack as FIFO For x1=0 to x0 { \\ now read from stack using Number Return Image1, 0!where+2:=Number as byte, 0!where+1:=Number as byte, 0!where:=Number as byte where+=3 } m=where mod 4 if m<>0 then where+=4-m } } Group Bitmap { SetPixel=SetPixel GetPixel=GetPixel Image$=StrDib$ Copy=CopyImage ToFile=Export2File } =Bitmap } A=Bitmap(10, 10) Call A.SetPixel(5,5, color(128,0,255)) Open "A.PPM" for Output as #F Call A.ToFile(F) Close #f Open "A.PPM" for Input as #F Try { C=Bitmap(f) Copy 400*twipsx,200*twipsy use C.Image$() } Close #f ' is the same as this one Open "A.PPM" for Input as #F Line Input #f, p3$ If p3$="P3" Then { Line Input #f, Comment$ if left$(Comment$,1)="#" then { Line Input #f, Dimension$ } else Dimension$=Comment$ Long x=Val(piece$(Dimension$," ")(0)) Long y=Val(piece$(Dimension$," ")(1)) do { Line Input #f, P255$ } until left$(P255$, 1)<>"#" If not P255$="255" then Error "Not proper ppm format" B=Bitmap(x, y) x0=x-1 For y1=y-1 to 0 { do { Line Input #f, aline$ } until left$(aline$,1)<>"#" flush ' empty stack Stack aline$ ' place all values to stack as FIFO For x1=0 to x0 { \\ now read from stack Read red, green, blue Call B.setpixel(x1, y1, Color(red, green, blue)) } } } Close #f If valid("B") then Copy 200*twipsx,200*twipsy use B.Image$() } Checkit    
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Mathematica.2F_Wolfram_Language
Mathematica/ Wolfram Language
Import["file.ppm","PPM"]  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#8th
8th
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program boolean.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ FALSE, 0 // or other value .equ TRUE, 1 // or other value /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessTrue: .asciz "The value is true.\n" szMessFalse: .asciz "The value is false.\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   mov x0,0 //mov x0,#1 //uncomment pour other test cmp x0,TRUE bne 1f // value true ldr x0,qAdrszMessTrue bl affichageMess b 100f 1: // value False ldr x0,qAdrszMessFalse bl affichageMess   100: // standard end of the program */ mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszMessTrue: .quad szMessTrue qAdrszMessFalse: .quad szMessFalse /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program boolean.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ FALSE, 0 // or other value .equ TRUE, 1 // or other value /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessTrue: .asciz "The value is true.\n" szMessFalse: .asciz "The value is false.\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   mov x0,0 //mov x0,#1 //uncomment pour other test cmp x0,TRUE bne 1f // value true ldr x0,qAdrszMessTrue bl affichageMess b 100f 1: // value False ldr x0,qAdrszMessFalse bl affichageMess   100: // standard end of the program */ mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszMessTrue: .quad szMessTrue qAdrszMessFalse: .quad szMessFalse /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#REXX
REXX
/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */ /*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/ parse arg key .; arg . p /*get key & uppercased text to be used.*/ p= space(p, 0) /*elide any and all spaces (blanks). */ say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/ say ' plain text:' p /* " " plain text " " */ y= Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */ z= Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */ if z\==p then say "plain text doesn't match uncyphered cyphered text." exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Caesar: procedure; arg s,k; @= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ak= abs(k) /*obtain the absolute value of the key.*/ L= length(@) /*obtain the length of the @ string. */ if ak>length(@)-1 | k==0 then call err k 'key is invalid.' _= verify(s, @) /*any illegal characters specified ? */ if _\==0 then call err 'unsupported character:' substr(s, _, 1) if k>0 then ky= k + 1 /*either cypher it, or ··· */ else ky= L + 1 - ak /* decypher it. */ return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ err: say; say '***error***'; say; say arg(1); say; exit 13
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Forth
Forth
\ writing   : init-write ( -- b m ) 0 128 ;   : flush-bits ( b m -- 0 128 ) drop emit init-write ;   : ?flush-bits ( b m -- b' m' ) dup 128 < if flush-bits then ;   : write-bit ( b m f -- b' m' ) if tuck or swap then 2/ dup 0= if flush-bits then ;   \ reading   : init-read ( -- b m ) key 128 ;   : eof? ( b m -- b m f ) dup if false else key? 0= then ;   : read-bit ( b m -- b' m' f ) dup 0= if 2drop init-read then 2dup and swap 2/ swap ;
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Go
Go
// Package bit provides bit-wise IO to an io.Writer and from an io.Reader. package bit   import ( "bufio" "errors" "io" )   // Order specifies the bit ordering within a byte stream. type Order int   const ( // LSB is for Least Significant Bits first LSB Order = iota // MSB is for Most Significant Bits first MSB )   // ==== Writing / Encoding ====   type writer interface { io.ByteWriter Flush() error }   // Writer implements bit-wise writing to an io.Writer. type Writer struct { w writer order Order write func(uint32, uint) error // writeLSB or writeMSB bits uint32 nBits uint err error }   // writeLSB writes `width` bits of `c` in LSB order. func (w *Writer) writeLSB(c uint32, width uint) error { w.bits |= c << w.nBits w.nBits += width for w.nBits >= 8 { if err := w.w.WriteByte(uint8(w.bits)); err != nil { return err } w.bits >>= 8 w.nBits -= 8 } return nil }   // writeMSB writes `width` bits of `c` in MSB order. func (w *Writer) writeMSB(c uint32, width uint) error { w.bits |= c << (32 - width - w.nBits) w.nBits += width for w.nBits >= 8 { if err := w.w.WriteByte(uint8(w.bits >> 24)); err != nil { return err } w.bits <<= 8 w.nBits -= 8 } return nil }   // WriteBits writes up to 16 bits of `c` to the underlying writer. // Even for MSB ordering the bits are taken from the lower bits of `c`. // (e.g. WriteBits(0x0f,4) writes four 1 bits). func (w *Writer) WriteBits(c uint16, width uint) error { if w.err == nil { w.err = w.write(uint32(c), width) } return w.err }   var errClosed = errors.New("bit reader/writer is closed")   // Close closes the writer, flushing any pending output. // It does not close the underlying writer. func (w *Writer) Close() error { if w.err != nil { if w.err == errClosed { return nil } return w.err } // Write the final bits (zero padded). if w.nBits > 0 { if w.order == MSB { w.bits >>= 24 } if w.err = w.w.WriteByte(uint8(w.bits)); w.err != nil { return w.err } } w.err = w.w.Flush() if w.err != nil { return w.err }   // Make any future calls to Write return errClosed. w.err = errClosed return nil }   // NewWriter returns a new bit Writer that writes completed bytes to `w`. func NewWriter(w io.Writer, order Order) *Writer { bw := &Writer{order: order} switch order { case LSB: bw.write = bw.writeLSB case MSB: bw.write = bw.writeMSB default: bw.err = errors.New("bit writer: unknown order") return bw } if byteWriter, ok := w.(writer); ok { bw.w = byteWriter } else { bw.w = bufio.NewWriter(w) } return bw }   // ==== Reading / Decoding ====   // Reader implements bit-wise reading from an io.Reader. type Reader struct { r io.ByteReader bits uint32 nBits uint read func(width uint) (uint16, error) // readLSB or readMSB err error }   func (r *Reader) readLSB(width uint) (uint16, error) { for r.nBits < width { x, err := r.r.ReadByte() if err != nil { return 0, err } r.bits |= uint32(x) << r.nBits r.nBits += 8 } bits := uint16(r.bits & (1<<width - 1)) r.bits >>= width r.nBits -= width return bits, nil }   func (r *Reader) readMSB(width uint) (uint16, error) { for r.nBits < width { x, err := r.r.ReadByte() if err != nil { return 0, err } r.bits |= uint32(x) << (24 - r.nBits) r.nBits += 8 } bits := uint16(r.bits >> (32 - width)) r.bits <<= width r.nBits -= width return bits, nil }   // ReadBits reads up to 16 bits from the underlying reader. func (r *Reader) ReadBits(width uint) (uint16, error) { var bits uint16 if r.err == nil { bits, r.err = r.read(width) } return bits, r.err }   // Close closes the reader. // It does not close the underlying reader. func (r *Reader) Close() error { if r.err != nil && r.err != errClosed { return r.err } r.err = errClosed return nil }   // NewReader returns a new bit Reader that reads bytes from `r`. func NewReader(r io.Reader, order Order) *Reader { br := new(Reader) switch order { case LSB: br.read = br.readLSB case MSB: br.read = br.readMSB default: br.err = errors.New("bit writer: unknown order") return br } if byteReader, ok := r.(io.ByteReader); ok { br.r = byteReader } else { br.r = bufio.NewReader(r) } return br }
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#GAP
GAP
# Dirty implementation # Only P3 format, an image is a list of 3 matrices (r, g, b) # Max color is always 255 WriteImage := function(name, img) local f, r, g, b, i, j, maxcolor, nrow, ncol, dim; f := OutputTextFile(name, false); r := img[1]; g := img[2]; b := img[3]; dim := DimensionsMat(r); nrow := dim[1]; ncol := dim[2]; maxcolor := 255; WriteLine(f, "P3"); WriteLine(f, Concatenation(String(ncol), " ", String(nrow), " ", String(maxcolor))); for i in [1 .. nrow] do for j in [1 .. ncol] do WriteLine(f, Concatenation(String(r[i][j]), " ", String(g[i][j]), " ", String(b[i][j]))); od; od; CloseStream(f); end;   PutPixel := function(img, i, j, color) img[1][i][j] := color[1]; img[2][i][j] := color[2]; img[3][i][j] := color[3]; end;   GetPixel := function(img, i, j) return [img[1][i][j], img[2][i][j], img[3][i][j]]; end;   NewImage := function(nrow, ncol, color) local r, g, b; r := color[1] + NullMat(nrow, ncol); g := color[2] + NullMat(nrow, ncol); b := color[3] + NullMat(nrow, ncol); return [r, g, b]; end;   # Reproducing the example from Wikipedia black := [ 0, 0, 0 ]; g := NewImage(2, 3, black); PutPixel(g, 1, 1, [255, 0, 0]); PutPixel(g, 1, 2, [0, 255, 0]); PutPixel(g, 1, 3, [0, 0, 255]); PutPixel(g, 2, 1, [255, 255, 0]); PutPixel(g, 2, 2, [255, 255, 255]); PutPixel(g, 2, 3, [0, 0, 0]); WriteImage("example.ppm", g);
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Go
Go
package raster   import ( "fmt" "io" "os" )   // WriteTo outputs 8-bit P6 PPM format to an io.Writer. func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { // magic number if _, err = fmt.Fprintln(w, "P6"); err != nil { return }   // comments for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } }   // x, y, depth _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return }   // raster data in a single write b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return }   // WriteFile writes to the specified filename. func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Nim
Nim
import strutils import bitmap import streams   type FormatError = object of CatchableError   # States used to parse the header. type State = enum waitingMagic, waitingWidth, waitingHeight, waitingColors   #---------------------------------------------------------------------------------------------------   iterator tokens(f: Stream): tuple[value: string, lastInLine: bool] = ## Yield the tokens in the header. for line in f.lines: if not line.startsWith('#'): let fields = line.splitWhitespace() for i, t in fields: yield (t, i == fields.high)   #---------------------------------------------------------------------------------------------------   proc getInt(s: string): int {.inline.} = ## Try to parse an int. Raise an exception if not an integer. try: result = s.parseInt() except ValueError: raise newException(FormatError, "Invalid value")   #---------------------------------------------------------------------------------------------------   proc header(f: Stream): tuple[width, height: Index] = ## Read the header and retrun the image width and height. var state = waitingMagic for (token, lastInLine) in f.tokens: case state of waitingMagic: if token != "P6": raise newException(FormatError, "Invalid file header") of waitingWidth: result.width = token.getInt() of waitingHeight: result.height = token.getInt() of waitingColors: if token.getInt() != 255: raise newException(FormatError, "Invalid number of colors") if not lastInLine: raise newException(FormatError, "Invalid data after number of colors") break state = succ(state)   #---------------------------------------------------------------------------------------------------   proc readPPM*(f: Stream): Image = ## Read a PPM file from a stream into an image.   let header = f.header() result = newImage(header.width, header.height)   var arr: array[256, int8] read = f.readData(addr(arr), 256) pos = 0   while read != 0: for i in 0 ..< read: case pos mod 3 of 0: result.pixels[pos div 3].r = arr[i].uint8 of 1: result.pixels[pos div 3].g = arr[i].uint8 of 2: result.pixels[pos div 3].b = arr[i].uint8 else: discard inc pos   read = f.readData(addr(arr), 256)   if pos != 3 * result.w * result.h: raise newException(FormatError, "Truncated file")   #---------------------------------------------------------------------------------------------------   proc readPPM*(filename: string): Image = ## Load a PPM file into an image.   var file = openFileStream(filename, fmRead) result = file.readPPM() file.close()   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: let image = readPPM("output.ppm") echo image.h, " ", image.w
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#OCaml
OCaml
let read_ppm ~filename = let ic = open_in filename in let line = input_line ic in if line <> "P6" then invalid_arg "not a P6 ppm file"; let line = input_line ic in let line = try if line.[0] = '#' (* skip comments *) then input_line ic else line with _ -> line in let width, height = Scanf.sscanf line "%d %d" (fun w h -> (w, h)) in let line = input_line ic in if line <> "255" then invalid_arg "not a 8 bit depth image"; let all_channels = let kind = Bigarray.int8_unsigned and layout = Bigarray.c_layout in Bigarray.Array3.create kind layout 3 width height in let r_channel = Bigarray.Array3.slice_left_2 all_channels 0 and g_channel = Bigarray.Array3.slice_left_2 all_channels 1 and b_channel = Bigarray.Array3.slice_left_2 all_channels 2 in for y = 0 to pred height do for x = 0 to pred width do r_channel.{x,y} <- (input_byte ic); g_channel.{x,y} <- (input_byte ic); b_channel.{x,y} <- (input_byte ic); done; done; close_in ic; (all_channels, r_channel, g_channel, b_channel)
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#ACL2
ACL2
PROC Test(BYTE v) PrintF("Variable v has value %B%E",v) IF v THEN PrintE("Condition IF v is satisfied.") ELSE PrintE("Condition IF v is not satisfied.") FI IF v=0 THEN PrintE("Condition IF v=0 is satisfied.") ELSE PrintE("Condition IF v=0 is not satisfied.") FI IF v<>0 THEN PrintE("Condition IF v<>0 is satisfied.") ELSE PrintE("Condition IF v<>0 is not satisfied.") FI IF v#0 THEN PrintE("Condition IF v#0 is satisfied.") ELSE PrintE("Condition IF v#0 is not satisfied.") FI PutE() RETURN   PROC Main() Test(0) Test(1) Test(86) RETURN
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Action.21
Action!
PROC Test(BYTE v) PrintF("Variable v has value %B%E",v) IF v THEN PrintE("Condition IF v is satisfied.") ELSE PrintE("Condition IF v is not satisfied.") FI IF v=0 THEN PrintE("Condition IF v=0 is satisfied.") ELSE PrintE("Condition IF v=0 is not satisfied.") FI IF v<>0 THEN PrintE("Condition IF v<>0 is satisfied.") ELSE PrintE("Condition IF v<>0 is not satisfied.") FI IF v#0 THEN PrintE("Condition IF v#0 is satisfied.") ELSE PrintE("Condition IF v#0 is not satisfied.") FI PutE() RETURN   PROC Main() Test(0) Test(1) Test(86) RETURN
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Ring
Ring
  # Project : Caesar cipher   cipher = "pack my box with five dozen liquor jugs" abc = "abcdefghijklmnopqrstuvwxyz" see "text is to be encrypted:" + nl see cipher+ nl + nl str = "" key = random(24) + 1 see "key = " + key + nl + nl see "encrypted:" + nl caesarencode(cipher, key) see str + nl + nl cipher = str see "decrypted again:" + nl caesardecode(cipher, key) see str + nl   func caesarencode(cipher, key) str = "" for n = 1 to len(cipher) if cipher[n] != " " pos = substr(abc, cipher[n]) if pos + key < len(abc) str = str + abc[pos + key] else if (pos+key)-len(abc) != 0 str = str + abc[(pos+key)%len(abc)] else str = str +abc[key+pos] ok ok else str = str + " " ok next return str   func caesardecode(cipher, key) str = "" for n= 1 to len(cipher) if cipher[n] != " " pos = substr(abc, cipher[n]) if (pos - key) > 0 and pos != key str = str + abc[pos - key] loop else if pos = key str = str + char(122) else str = str + abc[len(abc)-(key-pos)] ok ok else str = str + " " ok next return str  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Haskell
Haskell
import Data.List import Data.Char import Control.Monad import Control.Arrow import System.Environment   int2bin :: Int -> [Int] int2bin = unfoldr(\x -> if x==0 then Nothing else Just (uncurry(flip(,)) (divMod x 2)))   bin2int :: [Int] -> Int bin2int = foldr ((.(2 *)).(+)) 0   bitReader = map (chr.bin2int). takeWhile(not.null). unfoldr(Just. splitAt 7) . (take =<< (7 *) . (`div` 7) . length)   bitWriter xs = tt ++ z00 where tt = concatMap (take 7.(++repeat 0).int2bin.ord) xs z00 = replicate (length xs `mod` 8) 0   main = do (xs:_) <- getArgs let bits = bitWriter xs   putStrLn "Text to compress:" putStrLn $ '\t' : xs putStrLn $ "Uncompressed text length is " ++ show (length xs) putStrLn $ "Compressed text has " ++ show (length bits `div` 8) ++ " bytes." putStrLn "Read and decompress:" putStrLn $ '\t' : bitReader bits
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Haskell
Haskell
{-# LANGUAGE ScopedTypeVariables #-}   module Bitmap.Netpbm(readNetpbm, writeNetpbm) where   import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST   nil :: a nil = undefined   readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c)   writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Oz
Oz
functor import Bitmap Open export Read %% Write define fun {Read Filename} F = {New Open.file init(name:Filename)}   fun {ReadColor8 _} Bytes = {F read(list:$ size:3)} in {List.toTuple color Bytes} end   fun {ReadColor16 _} Bytes = {F read(list:$ size:6)} in {List.toTuple color {Map {PairUp Bytes} FromBytes}} end in try Magic = {F read(size:2 list:$)} if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end Width = {ReadNumber F} Height = {ReadNumber F} MaxVal = {ReadNumber F} MaxVal =< 0xffff = true Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end B = {Bitmap.new Width Height} in {Bitmap.transform B Reader} B finally {F close} end end   fun {ReadNumber F} Ds in {SkipWS F} Ds = for collect:Collect break:Break do [C] = {F read(list:$ size:1)} in if {Char.isDigit C} then {Collect C} else {Break} end end {SkipWS F} {String.toInt Ds} end   proc {SkipWS F} [C] = {F read(list:$ size:1)} in if {Char.isSpace C} then {SkipWS F} elseif C == &# then {SkipLine F} else {F seek(whence:current offset:~1)} end end   proc {SkipLine F} [C] = {F read(list:$ size:1)} in if C \= &\n andthen C \= &\r then {SkipLine F} end end   fun {PairUp Xs} case Xs of X1|X2|Xr then [X1 X2]|{PairUp Xr} [] nil then nil end end   fun {FromBytes [C1 C2]} C1 * 0x100 + C2 end   %% Omitted: Write end
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Ada
Ada
type Boolean is (False, True);
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#ALGOL_68
ALGOL 68
BOOL f = FALSE, t = TRUE; []BOOL ft = (f, t); STRING or = " or "; FOR key TO UPB ft DO BOOL val = ft[key]; UNION(VOID, INT) void = (val|666|EMPTY); REF STRING ref = (val|HEAP STRING|NIL); INT int = ABS val; REAL real = ABS val; COMPL compl = ABS val; BITS bits = BIN ABS val; # or bitspack(val); # BYTES bytes = bytes pack((val|"?"|null char)*bytes width); CHAR char = (val|"?"|null char); STRING string = (val|"?"|"");   print((((val | "TRUE" | "FALSE" ), ": ", val, or, (val|flip|flop), new line))); print((" void: ", " => ", (void|(VOID):FALSE|TRUE), new line)); print((" ref: ", " => ", ref ISNT REF STRING(NIL), new line)); print((" int: ", int , " => ", int /= 0, new line)); print((" real: ", real , " => ", real /= 0, new line)); print((" compl: ", compl , " => ", compl /= 0, new line)); print((" bits: ", bits , " => ", ABS bits /= 0, or, bits /= 2r0, or, bits width ELEM bits, or, []BOOL(bits)[bits width], new line)); print((" bytes: """, STRING(bytes) , """ => ", 1 ELEM bytes /= null char, or, STRING(bytes) /= null char*bytes width, or, STRING(bytes)[1] /= null char, new line)); print((" char: """, char , """ => ", ABS char /= 0 , or, char /= null char, new line)); print(("string: """, string , """ => ", string /= "", or, UPB string /= 0, new line)); print((new line)) OD
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Ruby
Ruby
class String ALFABET = ("A".."Z").to_a   def caesar_cipher(num) self.tr(ALFABET.join, ALFABET.rotate(num).join) end   end   #demo: encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3) decrypted = encypted.caesar_cipher(-3)  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#J
J
bitReader =: a. {~ _7 #.\ ({.~ <.&.(%&7)@#) bitWriter =: , @ ((7$2) & #: @ (a.&i.)), 0 $~ 8 | #
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Julia
Julia
  function compress7(inio, outio) nextwritebyte = read(inio, UInt8) & 0x7f filled = 7 while !eof(inio) inbyte = read(inio, UInt8) write(outio, UInt8(nextwritebyte | inbyte << filled)) nextwritebyte = inbyte >> (8 - filled) filled = (filled + 7) % 8 if filled == 0 if eof(inio) break end nextwritebyte = read(inio, UInt8) & 0x7f filled = 7 end end if filled != 0 write(outio, UInt8(nextwritebyte)) end end   function expand7(inio, outio) newbyte = read(inio, UInt8) write(outio, UInt8(newbyte & 0x7f)) residualbyte::UInt8 = newbyte >> 7 filled = 1 while !eof(inio) inbyte = read(inio, UInt8) write(outio, UInt8((residualbyte | inbyte << filled) & 0x7f)) residualbyte = inbyte >> (7 - filled) filled = (filled + 1) % 7 if filled == 0 write(outio, UInt8(residualbyte & 0x7f)) residualbyte = 0 end end end   str = b"These bit oriented I/O functions can be used to implement compressors and decompressors." ins = IOBuffer(str) outs = IOBuffer() newouts = IOBuffer() compress7(ins, outs) seek(outs,0) expand7(outs, newouts) println("Initial string of length $(length(str)): ", String(ins.data)) println("Compressed to length $(length(outs.data)) on line below:\n", String(outs.data)) println("Decompressed string: ", String(newouts.data))  
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#J
J
require 'files'   NB. ($x) is height, width, colors per pixel writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Java
Java
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets;   public class PPMWriter {   public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete();   try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight());   bw.write(header.getBytes(StandardCharsets.US_ASCII));   for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Perl
Perl
#! /usr/bin/perl   use strict; use Image::Imlib2;   my $img = Image::Imlib2->load("out0.ppm");   # let's do something with it now $img->set_color(255, 255, 255, 255); $img->draw_line(0,0, $img->width,$img->height); $img->image_set_format("png"); $img->save("out1.png");   exit 0;
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#ALGOL_W
ALGOL W
  1 ^ 1 1 1 ^ 0 0  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#APL
APL
  1 ^ 1 1 1 ^ 0 0  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Run_BASIC
Run BASIC
input "Gimme a ofset:";ofst ' set any offset you like   a$ = "Pack my box with five dozen liquor jugs" print " Original: ";a$ a$ = cipher$(a$,ofst) print "Encrypted: ";a$ print "Decrypted: ";cipher$(a$,ofst+6)   FUNCTION cipher$(a$,ofst) for i = 1 to len(a$) aa$ = mid$(a$,i,1) code$ = " " if aa$ <> " " then ua$ = upper$(aa$) a = asc(ua$) - 64 code$ = chr$((((a mod 26) + ofst) mod 26) + 65) if ua$ <> aa$ then code$ = lower$(code$) end if cipher$ = cipher$;code$ next i END FUNCTION
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Kotlin
Kotlin
// version 1.2.31   import java.io.File   class BitFilter(val f: File, var accu: Int = 0, var bits: Int = 0) {   private val bw = f.bufferedWriter() private val br = f.bufferedReader()   fun write(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { var nBits = _nBits var index = start + _shift / 8 var shift = _shift % 8   while (nBits != 0 || bits >= 8) { while (bits >= 8) { bits -= 8 bw.write(accu ushr bits) accu = accu and ((1 shl bits) - 1) } while (bits < 8 && nBits != 0) { val b = buf[index].toInt() accu = (accu shl 1) or (((128 ushr shift) and b) ushr (7 - shift)) nBits-- bits++ if (++shift == 8) { shift = 0; index++ } } } }   fun read(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { var nBits = _nBits var index = start + _shift / 8 var shift = _shift % 8   while (nBits != 0) { while (bits != 0 && nBits != 0) { val mask = 128 ushr shift if ((accu and (1 shl (bits - 1))) != 0) buf[index] = (buf[index].toInt() or mask).toByte() else buf[index] = (buf[index].toInt() and mask.inv()).toByte() nBits-- bits-- if (++shift >= 8) { shift = 0; index++ } } if (nBits == 0) break accu = (accu shl 8) or br.read() bits += 8 } }   fun closeWriter() { if (bits != 0) { accu = (accu shl (8 - bits)) bw.write(accu) } bw.close() accu = 0 bits = 0 }   fun closeReader() { br.close() accu = 0 bits = 0 } }   fun main(args: Array<String>) { val s = "abcdefghijk".toByteArray(Charsets.UTF_8) val f = File("test.bin") val bf = BitFilter(f)   /* for each byte in s, write 7 bits skipping 1 */ for (i in 0 until s.size) bf.write(s, i, 7, 1) bf.closeWriter()   /* read 7 bits and expand to each byte of s2 skipping 1 bit */ val s2 = ByteArray(s.size) for (i in 0 until s2.size) bf.read(s2, i, 7, 1) bf.closeReader() println(String(s2, Charsets.UTF_8)) }
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Julia
Julia
using Images, FileIO   h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end   save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Kotlin
Kotlin
// Version 1.2.40   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage import java.io.FileOutputStream   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)   fun fill(c: Color) { val g = image.graphics g.color = c g.fillRect(0, 0, image.width, image.height) }   fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())   fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) }   fun main(args: Array<String>) { // create BasicBitmapStorage object val width = 640 val height = 640 val bbs = BasicBitmapStorage(width, height) for (y in 0 until height) { for (x in 0 until width) { val c = Color(x % 256, y % 256, (x * y) % 256) bbs.setPixel(x, y, c) } }   // now write it to a PPM file val fos = FileOutputStream("output.ppm") val buffer = ByteArray(width * 3) // write one line at a time fos.use { val header = "P6\n$width $height\n255\n".toByteArray() with (it) { write(header) for (y in 0 until height) { for (x in 0 until width) { val c = bbs.getPixel(x, y) buffer[x * 3] = c.red.toByte() buffer[x * 3 + 1] = c.green.toByte() buffer[x * 3 + 2] = c.blue.toByte() } write(buffer) } } } }
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Phix
Phix
-- demo\rosetta\Bitmap_read_ppm.exw (runnable version)   function read_ppm(string filename) sequence image, line integer dimx, dimy, maxcolor atom fn = open(filename, "rb") if fn<0 then return -1 -- unable to open end if line = gets(fn) if line!="P6\n" then return -1 -- only ppm6 files are supported end if line = gets(fn) {{dimx,dimy}} = scanf(line,"%d %d%s") line = gets(fn) {{maxcolor}} = scanf(line,"%d%s") image = repeat(repeat(0,dimy),dimx) for y=1 to dimy do for x=1 to dimx do image[x][y] = getc(fn)*#10000 + getc(fn)*#100 + getc(fn) end for end for close(fn) return image end function   --include ppm.e -- read_ppm(), write_ppm(), to_grey() (as distributed, instead of the above)   sequence img = read_ppm("Lena.ppm") img = to_grey(img) write_ppm("LenaGray.ppm",img)
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#PicoLisp
PicoLisp
(de ppmRead (File) (in File (unless (and `(hex "5036") (rd 2)) # P6 (quit "Wrong file format" File) ) (rd 1) (let (DX 0 DY 0 Max 0 C) (while (>= 9 (setq C (- (rd 1) `(char "0"))) 0) (setq DX (+ (* 10 DX) C)) ) (while (>= 9 (setq C (- (rd 1) `(char "0"))) 0) (setq DY (+ (* 10 DY) C)) ) (while (>= 9 (setq C (- (rd 1) `(char "0"))) 0) (setq Max (+ (* 10 Max) C)) ) (prog1 (make (do DY (link (need DX)))) (for Y @ (map '((X) (set X (list (rd 1) (rd 1) (rd 1)))) Y ) ) ) ) ) )
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#AppleScript
AppleScript
1 > 2 --> false not false --> true   {true as integer, false as integer, 1 as boolean, 0 as boolean} --> {1, 0, true, false}   true = 1 --> false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program areaString.s */   /* Constantes */ @ The are no TRUE or FALSE constants in ARM Assembly .equ FALSE, 0 @ or other value .equ TRUE, 1 @ or other value .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessTrue: .asciz "The value is true.\n" szMessFalse: .asciz "The value is false.\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */   mov r0,#0 //mov r0,#1 @uncomment pour other test cmp r0,#TRUE bne 1f @ value true ldr r0,iAdrszMessTrue bl affichageMess b 100f 1: @ value False ldr r0,iAdrszMessFalse bl affichageMess   100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrszMessTrue: .int szMessTrue iAdrszMessFalse: .int szMessFalse /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */      
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Rust
Rust
use std::io::{self, Write}; use std::fmt::Display; use std::{env, process};   fn main() { let shift: u8 = env::args().nth(1) .unwrap_or_else(|| exit_err("No shift provided", 2)) .parse() .unwrap_or_else(|e| exit_err(e, 3));   let plain = get_input() .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));   let cipher = plain.chars() .map(|c| { let case = if c.is_uppercase() {'A'} else {'a'} as u8; if c.is_alphabetic() { (((c as u8 - case + shift) % 26) + case) as char } else { c } }).collect::<String>();   println!("Cipher text: {}", cipher.trim()); }     fn get_input() -> io::Result<String> { print!("Plain text: "); try!(io::stdout().flush());   let mut buf = String::new(); try!(io::stdin().read_line(&mut buf)); Ok(buf) }   fn exit_err<T: Display>(msg: T, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg); process::exit(code); }
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Lingo
Lingo
-- parent script "BitArray"   property ancestor property bitSize property _pow2   ---------------------------------------- -- @constructor -- @param {integer} [bSize=0] ---------------------------------------- on new (me, bSize) if voidP(bitSize) then bitSize=0 me.bitSize = bSize byteSize = bitSize/8 + (bitSize mod 8>0) me._pow2 = [128,64,32,16,8,4,2,1] -- pow2 lookup list me.ancestor = ByteArray(byteSize) return me end   ---------------------------------------- -- Sets bit at position <bitPos> to <bitValue>. -- @param {integer} bitPos - starts at 1, as ByteArray's native byte access functions -- @param {boolean} bitValue ---------------------------------------- on setBit (me, bitPos, bitValue) bytePos = (bitPos-1)/8 + 1 bitPos = (bitPos-1) mod 8 + 1 if bitValue then me[bytePos] = bitOr(me[bytePos], me._pow2[bitPos]) else me[bytePos] = bitAnd(me[bytePos], bitNot(me._pow2[bitPos])) end if end   ---------------------------------------- -- Gets bit value at position <bitPos>. -- @param {integer} bitPos - starts at 1, as ByteArray's native byte access functions -- @return {boolean} bitValue ---------------------------------------- on getBit (me, bitPos) bytePos = (bitPos-1)/8 + 1 bitPos = (bitPos-1) mod 8 + 1 return bitAnd(me[bytePos], me._pow2[bitPos])<>0 end   ---------------------------------------- -- Returns all bits as string. To be in accordance with ByteArray's native toHexString(), -- returned string is separated with SPACE (e.g. "0 1 1 0...") -- @param {integer} [bitSizeOnly=FALSE] - if TRUE, only <bitSize> bits without byte-padding -- @return {string} ---------------------------------------- on toBinString (me, bitSizeOnly) res = "" repeat with i = 1 to me.length byte = me[i] repeat with j = 1 to 8 put (bitAnd(byte, me._pow2[j])<>0)&" " after res if bitSizeOnly and (i-1)*8+j=me.bitSize then exit repeat end repeat end repeat delete the last char of res return res end
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Lua
Lua
local function BitWriter() return { accumulator = 0, -- For current byte. bitCount = 0, -- Bits set in current byte. outChars = {},   -- writer:writeBit( bit ) writeBit = function(writer, bit) writer.bitCount = writer.bitCount + 1 if bit > 0 then writer.accumulator = writer.accumulator + 2^(8-writer.bitCount) end if writer.bitCount == 8 then writer:_flush() end end,   -- writer:writeLsb( value, width ) writeLsb = function(writer, value, width) for i = 1, width do writer:writeBit(value%2) value = math.floor(value/2) end end,   -- dataString = writer:getOutput( ) getOutput = function(writer) writer:_flush() return table.concat(writer.outChars) end,   _flush = function(writer) if writer.bitCount == 0 then return end   table.insert(writer.outChars, string.char(writer.accumulator)) writer.accumulator = 0 writer.bitCount = 0 end, } end   local function BitReader(data) return { bitPosition = 0, -- Absolute position in 'data'.   -- bit = reader:readBit( ) -- Returns nil at end-of-data. readBit = function(reader) reader.bitPosition = reader.bitPosition + 1 local bytePosition = math.floor((reader.bitPosition-1)/8) + 1   local byte = data:byte(bytePosition) if not byte then return nil end   local bitIndex = ((reader.bitPosition-1)%8) + 1 return math.floor(byte / 2^(8-bitIndex)) % 2 end,   -- value = reader:readLsb( width ) -- Returns nil at end-of-data. readLsb = function(reader, width) local accumulator = 0   for i = 1, width do local bit = reader:readBit() if not bit then return nil end   if bit > 0 then accumulator = accumulator + 2^(i-1) end end   return accumulator end, } end
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Lua
Lua
    -- helper function, simulates PHP's array_fill function local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end   Bitmap = {} Bitmap.__index = Bitmap   function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end   function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end   function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end   function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end   function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end   function Bitmap:setPixel(x, y, color) if x >= self.width then --error("x is bigger than self.width!") return false elseif x < 0 then --error("x is smaller than 0!") return false elseif y >= self.height then --error("y is bigger than self.height!") return false elseif y < 0 then --error("y is smaller than 0!") return false end self.data[y][x] = color return true end   function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) --b:fill(2, 2, 18, 18, {240,240,240}) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end   example_colorful_stripes():writeP6('p6.ppm')  
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#PL.2FI
PL/I
  /* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */ test: procedure options (main); declare (m, n, max_color, i, j) fixed binary (31); declare ch character (1), ID character (2); declare 1 pixel union, 2 color bit(24) aligned, 2 primary_colors, 3 R char (1), 3 G char (1), 3 B char (1); declare in file record;   open file (in) title ('/IMAGE.PPM,TYPE(FIXED),RECSIZE(1)' ) input;   call get_char; ID = ch; call get_char; substr(ID, 2,1) = ch; /* Read in the dimensions of the image */ call get_integer (m); call get_integer (n);   /* Read in the maximum color size used */ call get_integer (max_color); /* The previous call reads in ONE line feed or CR or other terminator */ /* character. */   begin; declare image (0:m-1,0:n-1) bit (24);   do i = 0 to hbound(image, 1); do j = 0 to hbound(image,2); read file (in) into (R); read file (in) into (G); read file (in) into (B); image(i,j) = color; end; end; end;   get_char: procedure; do until (ch ^= ' '); read file (in) into (ch); end; end get_char;   get_integer: procedure (value); declare value fixed binary (31);   do until (ch = ' '); read file (in) into (ch); end; value = 0; do until (is_digit(ch)); value = value*10 + ch; read file (in) into (ch); end; end get_integer;   is_digit: procedure (ch) returns (bit(1)); declare ch character (1); return (index('0123456789', ch) > 0); end is_digit; end test;
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Arturo
Arturo
a: true b: false   if? a [ print "yep" ] else [ print "nope" ]   if? b -> print "nope" else -> print "yep"
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Scala
Scala
object Caesar { private val alphaU='A' to 'Z' private val alphaL='a' to 'z'   def encode(text:String, key:Int)=text.map{ case c if alphaU.contains(c) => rot(alphaU, c, key) case c if alphaL.contains(c) => rot(alphaL, c, key) case c => c } def decode(text:String, key:Int)=encode(text,-key) private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size) }
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#MIPS_Assembly
MIPS Assembly
type BitWriter * = tuple file: File bits: uint8 nRemain: int   BitReader * = tuple file: File bits: uint8 nRemain: int nRead: int   proc newBitWriter * (file: File) : ref BitWriter = result = new BitWriter result.file = file result.bits = 0 result.nRemain = 8   proc flushBits (stream : ref BitWriter) = discard stream.file.writeBuffer(stream.bits.addr, 1) stream.nRemain = 8 stream.bits = 0   proc write * (stream: ref BitWriter, bits: uint8, nBits: int) = assert(nBits <= 8)   for ii in countdown((nBits - 1), 0) : stream.bits = (stream.bits shl 1) or ((bits shr ii) and 1) stream.nRemain.dec(1) if stream.nRemain == 0: stream.flushBits   proc flush * (stream: ref BitWriter) = if stream.nRemain < 8: stream.bits = stream.bits shl stream.nRemain stream.flushBits   proc newBitReader * (file: File) : ref BitReader = result = new BitReader result.file = file result.bits = 0 result.nRemain = 0 result.nRead = 0   proc read * (stream: ref BitReader, nBits: int) : uint8 = assert(nBits <= 8)   result = 0 for ii in 0 ..< nBits : if stream.nRemain == 0: stream.nRead = stream.file.readBuffer(stream.bits.addr, 1) if stream.nRead == 0: break stream.nRemain = 8   result = (result shl 1) or ((stream.bits shr 7) and 1)   stream.bits = stream.bits shl 1 stream.nRemain.dec(1)     when isMainModule: var file: File writer: ref BitWriter reader: ref BitReader   file = open("testfile.dat", fmWrite) writer = newBitWriter(file)   for ii in 0 .. 255: writer.write(ii.uint8, 7)   writer.flush file.close   var dataCtr = 0   file = open("testfile.dat", fmRead) reader = newBitReader(file)   while true: let aByte = reader.read(7)   if reader.nRead == 0: break   assert((dataCtr and 0x7f).uint8 == aByte)   inc dataCtr   assert(dataCtr == 256)   file.close   echo "OK"
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Nim
Nim
type BitWriter * = tuple file: File bits: uint8 nRemain: int   BitReader * = tuple file: File bits: uint8 nRemain: int nRead: int   proc newBitWriter * (file: File) : ref BitWriter = result = new BitWriter result.file = file result.bits = 0 result.nRemain = 8   proc flushBits (stream : ref BitWriter) = discard stream.file.writeBuffer(stream.bits.addr, 1) stream.nRemain = 8 stream.bits = 0   proc write * (stream: ref BitWriter, bits: uint8, nBits: int) = assert(nBits <= 8)   for ii in countdown((nBits - 1), 0) : stream.bits = (stream.bits shl 1) or ((bits shr ii) and 1) stream.nRemain.dec(1) if stream.nRemain == 0: stream.flushBits   proc flush * (stream: ref BitWriter) = if stream.nRemain < 8: stream.bits = stream.bits shl stream.nRemain stream.flushBits   proc newBitReader * (file: File) : ref BitReader = result = new BitReader result.file = file result.bits = 0 result.nRemain = 0 result.nRead = 0   proc read * (stream: ref BitReader, nBits: int) : uint8 = assert(nBits <= 8)   result = 0 for ii in 0 ..< nBits : if stream.nRemain == 0: stream.nRead = stream.file.readBuffer(stream.bits.addr, 1) if stream.nRead == 0: break stream.nRemain = 8   result = (result shl 1) or ((stream.bits shr 7) and 1)   stream.bits = stream.bits shl 1 stream.nRemain.dec(1)     when isMainModule: var file: File writer: ref BitWriter reader: ref BitReader   file = open("testfile.dat", fmWrite) writer = newBitWriter(file)   for ii in 0 .. 255: writer.write(ii.uint8, 7)   writer.flush file.close   var dataCtr = 0   file = open("testfile.dat", fmRead) reader = newBitReader(file)   while true: let aByte = reader.read(7)   if reader.nRead == 0: break   assert((dataCtr and 0x7f).uint8 == aByte)   inc dataCtr   assert(dataCtr == 256)   file.close   echo "OK"
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#LiveCode
LiveCode
  export image "test" to file "~/Test.PPM" as paint -- paint format is one of PBM, PGM, or PPM  
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function Bitmap (x as long, y as long) { if x<1 or y<1 then Error "Wrong dimensions" structure rgb { red as byte green as byte blue as byte } m=len(rgb)*x mod 4 if m>0 then m=4-m ' add some bytes to raster line m+=len(rgb) *x Structure rasterline { { pad as byte*m } \\ union pad+hline hline as rgb*x }   Structure Raster { magic as integer*4 w as integer*4 h as integer*4 lines as rasterline*y } Buffer Clear Image1 as Raster \\ 24 chars as header to be used from bitmap render build in functions Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) \\ fill white (all 255) \\ Str$(string) convert to ascii, so we get all characters from words width to byte width Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) Buffer Clear Pad as Byte*4 SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ where=alines+3*x+blines*y if c>0 then c=color(c) c-! Return Pad, 0:=c as long Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte   } GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ where=alines+3*x+blines*y =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) } StrDib$=Lambda$ Image1, Raster -> { =Eval$(Image1, 0, Len(Raster)) } CopyImage=Lambda Image1 (image$) -> { if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { Return Image1, 0:=Image$ } Else Error "Can't Copy Image" } Export2File=Lambda Image1, x, y (f) -> { \\ use this between open and close Print #f, "P3" Print #f,"# Created using M2000 Interpreter" Print #f, x;" ";y Print #f, 255 x2=x-1 where=24 For y1= 0 to y-1 { a$="" For x1=0 to x2 { Print #f, a$;Eval(Image1, where +2 as byte);" "; Print #f, Eval(Image1, where+1 as byte);" "; Print #f, Eval(Image1, where as byte); where+=3 a$=" " } Print #f m=where mod 4 if m<>0 then where+=4-m } } Group Bitmap { SetPixel=SetPixel GetPixel=GetPixel Image$=StrDib$ Copy=CopyImage ToFile=Export2File } =Bitmap }   A=Bitmap(10, 10) Call A.SetPixel(5,5, color(128,0,255)) Open "A2.PPM" for Output as #F Call A.ToFile(F) Close #f ' is the same as this one Try { Open "A.PPM" for Output as #F Print #f, "P3" Print #f,"# Created using M2000 Interpreter" Print #f, 10;" ";10 Print #f, 255 For y=10-1 to 0 { a$="" For x=0 to 10-1 { rgb=-A.GetPixel(x, y) Print #f, a$;Binary.And(rgb, 0xFF); " "; Print #f, Binary.And(Binary.Shift(rgb, -8), 0xFF); " "; Print #f, Binary.Shift(rgb, -16); a$=" " } Print #f } Close #f } } Checkit    
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#PureBasic
PureBasic
Structure PPMColor r.c g.c b.c EndStructure   Procedure LoadImagePPM(Image, file$) ; Author Roger Rösch (Nickname Macros) IDFile = ReadFile(#PB_Any, file$) If IDFile If CreateImage(Image, 1, 1) Format$ = ReadString(IDFile) ReadString(IDFile) ; skip comment Dimensions$ = ReadString(IDFile) w = Val(StringField(Dimensions$, 1, " ")) h = Val(StringField(Dimensions$, 2, " ")) ResizeImage(Image, w, h) StartDrawing(ImageOutput(Image)) max = Val(ReadString(IDFile)) ; Maximal Value for a color Select Format$ Case "P3" ; File in ASCII format ; Exract everey number remaining in th file into an array using an RegEx Stringlen = Lof(IDFile) - Loc(IDFile) content$ = Space(Stringlen) Dim color.s(0) ReadData(IDFile, @content$, Stringlen) CreateRegularExpression(1, "\d+") ExtractRegularExpression(1, content$, color()) ; Plot color information on our empty Image For y = 0 To h - 1 For x = 0 To w - 1 pos = (y*w + x)*3 r=Val(color(pos))*255 / max g=Val(color(pos+1))*255 / max b=Val(color(pos+2))*255 / max Plot(x, y, RGB(r,g,b)) Next Next Case "P6" ;File In binary format ; Read whole bytes into a buffer because its faster than reading single ones Bufferlen = Lof(IDFile) - Loc(IDFile) *Buffer = AllocateMemory(Bufferlen) ReadData(IDFile, *Buffer, Bufferlen) ; Plot color information on our empty Image For y = 0 To h - 1 For x = 0 To w - 1 *color.PPMColor = pos + *Buffer Plot(x, y, RGB(*color\r*255 / max, *color\g*255 / max, *color\b*255 / max)) pos + 3 Next Next EndSelect StopDrawing() ; Return 1 if successfully loaded to behave as other PureBasic functions ProcedureReturn 1 EndIf EndIf EndProcedure
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#AutoHotkey
AutoHotkey
BEGIN { # Do not put quotes round the numeric values, or the tests will fail a = 1 # True b = 0 # False   # Boolean evaluations if (a) { print "first test a is true" } # This should print if (b) { print "second test b is true" } # This should not print if (!a) { print "third test a is false" } # This should not print if (!b) { print "forth test b is false" } # This should print   # Boolean evaluation using comparison against zero if (a == 0) { print "fifth test a is false" } # This should not print if (b == 0) { print "sixth test b is false" } # This should print if (a != 0) { print "seventh test a is true" } # This should print if (b != 0) { print "eighth test b is true" } # This should not print   }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Avail
Avail
BEGIN { # Do not put quotes round the numeric values, or the tests will fail a = 1 # True b = 0 # False   # Boolean evaluations if (a) { print "first test a is true" } # This should print if (b) { print "second test b is true" } # This should not print if (!a) { print "third test a is false" } # This should not print if (!b) { print "forth test b is false" } # This should print   # Boolean evaluation using comparison against zero if (a == 0) { print "fifth test a is false" } # This should not print if (b == 0) { print "sixth test b is false" } # This should print if (a != 0) { print "seventh test a is true" } # This should print if (b != 0) { print "eighth test b is true" } # This should not print   }
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Scheme
Scheme
; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; (cond-expand (chicken (use srfi-13)) (gauche (use srfi-13)) (kawa (import (srfi :13))) (else (import (scheme base) (scheme write)))) ; R7RS     (define msg "The quick brown fox jumps over the lazy dog.") (define key 13)   (define (caesar char) (define A (char->integer #\A)) (define Z (char->integer #\Z)) (define a (char->integer #\a)) (define z (char->integer #\z)) (define c (char->integer char)) (integer->char (cond ((<= A c Z) (+ A (modulo (+ key (- c A)) 26))) ((<= a c z) (+ a (modulo (+ key (- c a)) 26))) (else c)))) ; Return other characters verbatim.   (display (string-map caesar msg)) (newline)  
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#OCaml
OCaml
let write_7bit_string ~filename ~str = let oc = open_out filename in let ob = IO.output_bits(IO.output_channel oc) in String.iter (fun c -> IO.write_bits ob 7 (int_of_char c)) str; IO.flush_bits ob; close_out oc; ;;
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Perl
Perl
#! /usr/bin/perl   use strict;   # $buffer = write_bits(*STDOUT, $buffer, $number, $bits) sub write_bits( $$$$ ) { my ($out, $l, $num, $q) = @_; $l .= substr(unpack("B*", pack("N", $num)), -$q); if ( (length($l) > 8) ) { my $left = substr($l, 8); print $out pack("B8", $l); $l = $left; } return $l; }   # flush_bits(*STDOUT, $buffer) sub flush_bits( $$ ) { my ($out, $b) = @_; print $out pack("B*", $b); }   # ($val, $buf) = read_bits(*STDIN, $buf, $n) sub read_bits( $$$ ) { my ( $in, $b, $n ) = @_; # we put a limit in the number of bits we can read # with one shot; this should mirror the limit of the max # integer value perl can hold if ( $n > 32 ) { return 0; } while ( length($b) < $n ) { my $v; my $red = read($in, $v, 1); if ( $red < 1 ) { return ( 0, -1 ); } $b .= substr(unpack("B*", $v), -8); } my $bits = "0" x ( 32-$n ) . substr($b, 0, $n); my $val = unpack("N", pack("B32", $bits)); $b = substr($b, $n); return ($val, $b); }
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Mathematica.2F_Wolfram_Language
Mathematica/ Wolfram Language
Export["file.ppm",image,"PPM"]
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#MATLAB_.2F_Octave
MATLAB / Octave
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0];     r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n%i %i\n255\n',size(R)); fwrite(fid,[r,g,b]','uint8'); fclose(fid);
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Python
Python
# With help from http://netpbm.sourceforge.net/doc/ppm.html   # String masquerading as ppm file (version P3) import io   ppmtxt = '''P3 # feep.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0 '''     def tokenize(f): for line in f: if line[0] != '#': for t in line.split(): yield t   def ppmp3tobitmap(f): t = tokenize(f) nexttoken = lambda : next(t) assert 'P3' == nexttoken(), 'Wrong filetype' width, height, maxval = (int(nexttoken()) for i in range(3)) bitmap = Bitmap(width, height, Colour(0, 0, 0)) for h in range(height-1, -1, -1): for w in range(0, width): bitmap.set(w, h, Colour( *(int(nexttoken()) for i in range(3))))   return bitmap   print('Original Colour PPM file') print(ppmtxt) ppmfile = io.StringIO(ppmtxt) bitmap = ppmp3tobitmap(ppmfile) print('Grey PPM:') bitmap.togreyscale() ppmfileout = io.StringIO('') bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue())     ''' The print statements above produce the following output:   Original Colour PPM file P3 # feep.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0   Grey PPM: P3 # generated from Bitmap.writeppmp3 4 4 11 0 0 0 0 0 0 0 0 0 4 4 4 0 0 0 11 11 11 0 0 0 0 0 0 0 0 0 0 0 0 11 11 11 0 0 0 4 4 4 0 0 0 0 0 0 0 0 0   '''
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#AWK
AWK
BEGIN { # Do not put quotes round the numeric values, or the tests will fail a = 1 # True b = 0 # False   # Boolean evaluations if (a) { print "first test a is true" } # This should print if (b) { print "second test b is true" } # This should not print if (!a) { print "third test a is false" } # This should not print if (!b) { print "forth test b is false" } # This should print   # Boolean evaluation using comparison against zero if (a == 0) { print "fifth test a is false" } # This should not print if (b == 0) { print "sixth test b is false" } # This should print if (a != 0) { print "seventh test a is true" } # This should print if (b != 0) { print "eighth test b is true" } # This should not print   }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Axe
Axe
10 LET A%=0 20 LET B%=NOT(A%) 30 PRINT "THIS VERSION OF BASIC USES" 40 PRINT B%; " AS ITS TRUE VALUE" 50 IF A% THEN PRINT "TEST ONE DOES NOT PRINT" 60 IF B% THEN PRINT "TEST TWO DOES PRINT" 70 IF A%=0 THEN PRINT "TEST THREE (FALSE BY COMPARISON) DOES PRINT" 80 IF B%=0 THEN PRINT "TEST FOUR (FALSE BY COMPARISON) DOES NOT PRINT" 90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT" 100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT" 110 END
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#sed
sed
#!/bin/sed -rf # Input: <number 0..25>\ntext to encode   /^[0-9]+$/ { # validate a number and translate it to analog form s/$/;9876543210dddddddddd/ s/([0-9]);.*\1.{10}(.?)/\2/ s/2/11/ s/1/dddddddddd/g /[3-9]|d{25}d+/ { s/.*/Error: Key must be <= 25/ q } # append from-table s/$/\nabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ # .. and to-table s/$/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ # rotate to-table, lower and uppercase independently, removing one `d' at a time : rotate s/^d(.*\n[^Z]+Z)(.)(.{25})(.)(.{25})/\1\3\2\5\4/ t rotate s/\n// h d }   # use \n to mark character to convert s/^/\n/ # append conversion table to pattern space G : loop # look up converted character and place it instead of old one s/\n(.)(.*\n.*\1.{51}(.))/\n\3\2/ # advance \n even if prev. command fails, thus skip non-alphabetical characters /\n\n/! s/\n([^\n])/\1\n/ t loop s/\n\n.*//
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Action.21
Action!
INCLUDE "H6:LOADPPM5.ACT"   DEFINE HISTSIZE="256"   PROC PutBigPixel(INT x,y BYTE col) IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN y==LSH 2 col==RSH 4 IF col<0 THEN col=0 ELSEIF col>15 THEN col=15 FI Color=col Plot(x,y) DrawTo(x,y+3) FI RETURN   PROC DrawImage(GrayImage POINTER image INT x,y) INT i,j BYTE c   FOR j=0 TO image.gh-1 DO FOR i=0 TO image.gw-1 DO c=GetGrayPixel(image,i,j) PutBigPixel(x+i,y+j,c) OD OD RETURN   PROC CalcHistogram(GrayImage POINTER image INT ARRAY hist) INT i,j BYTE c   Zero(hist,HISTSIZE*2) FOR j=0 TO image.gh-1 DO FOR i=0 TO image.gw-1 DO c=GetGrayPixel(image,i,j) hist(c)==+1 OD OD RETURN   BYTE FUNC CalcThresholdValue(INT width,height INT ARRAY hist) INT i,sum,total,curr   total=width*height sum=0 FOR i=0 TO HISTSIZE-1 DO curr=hist(i) IF sum>=(total-curr)/2 THEN RETURN (i) FI sum==+curr OD RETURN (HISTSIZE-1)   PROC Binarize(GrayImage POINTER src,dst BYTE threshold) INT i,j BYTE c   FOR j=0 TO src.gh-1 DO FOR i=0 TO src.gw-1 DO c=GetGrayPixel(src,i,j) IF c<threshold THEN c=0 ELSE c=255 FI SetGrayPixel(dst,i,j,c) OD OD RETURN   PROC Main() BYTE CH=$02FC ;Internal hardware value for last key pressed BYTE ARRAY dataIn(900),dataOut(900) GrayImage in,out INT ARRAY hist(HISTSIZE) BYTE threshold INT size=[30],x,y   Put(125) PutE() ;clear the screen   InitGrayImage(in,size,size,dataIn) InitGrayImage(out,size,size,dataOut) PrintE("Loading source image...") LoadPPM5(in,"H6:LENA30G.PPM") PrintE("Calc histogram...") CalcHistogram(in,hist) PrintE("Calc threshold value...") threshold=CalcThresholdValue(in.gw,in.gh,hist) PrintE("Binarization...") Binarize(in,out,threshold)   Graphics(9) x=(40-size)/2 y=(48-size)/2 DrawImage(in,x,y) DrawImage(out,x+40,y)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#Phix
Phix
without js -- (file i/o) enum FN, V, BITS -- fields of a bitwiseioreader/writer function new_bitwiseio(string filename, mode) integer fn = open(filename,mode) return {fn,0,0} -- ie {FN,V=0,BITS=0} end function function new_bitwiseiowriter(string filename) return new_bitwiseio(filename,"wb") end function function new_bitwiseioreader(string filename) return new_bitwiseio(filename,"rb") end function function write_bits(sequence writer, integer v, bits) integer {fn,wv,wb} = writer, p2 = power(2,bits), ch if v!=and_bits(v,p2*2-1) then ?9/0 end if wv = wv*p2+v wb += bits while wb>=8 do wb -= 8 p2 = power(2,wb) ch = floor(wv/p2) puts(fn,ch) wv -= ch*p2 end while if wv>=#100 then ?9/0 end if if wb>=8 then ?9/0 end if writer[V]= wv writer[BITS]= wb return writer end function function close_bitwiseiowriter(sequence writer) integer {fn,wv,wb} = writer if wb then if wb>=8 then ?9/0 end if -- sanity check writer = write_bits(writer,0,8-wb) end if if writer[V]!=0 then ?9/0 end if if writer[BITS]!=0 then ?9/0 end if close(fn) writer[FN]=-1 return writer end function function read_bits(sequence reader, integer bits) integer {fn,rv,rb} = reader, ch, p2 while bits>rb do ch = getc(fn) if ch=-1 then return {-1,reader} end if rv = rv*#100+ch rb += 8 end while rb -= bits p2 = power(2,rb) ch = floor(rv/p2) rv -= ch*p2 reader[V]= rv reader[BITS]= rb return {ch,reader} end function function as_hexb(string s, fmt="%02x ") -- helper funtion, returns hex string, or binary if fmt="%08b " string res = "" for i=1 to length(s) do res &= sprintf(fmt,s[i]) end for return trim(res) end function constant test = "This is a test." --constant test = "This is a test" --constant test = "abcdefghijk" --constant test = "STRING" --constant test = "This is an ascii string that will be crunched, written, read and expanded." printf(1,"\"%s\" as bytes: %s (length %d)\n",{test,as_hexb(test),length(test)}) printf(1," original bits: %s\n",{as_hexb(test,"%08b ")}) sequence writer = new_bitwiseiowriter("test.bin") for i=1 to length(test) do writer = write_bits(writer,test[i],7) end for writer = close_bitwiseiowriter(writer) integer fn = open("test.bin","rb") string bytes = get_text(fn,GT_WHOLE_FILE) printf(1,"Written bitstream: %s\n",{as_hexb(bytes,"%08b ")}) printf(1,"Written bytes: %s (length %d)\n",{as_hexb(bytes),length(bytes)}) close(fn) sequence reader = new_bitwiseioreader("test.bin") bytes = "" integer ch while true do {ch,reader} = read_bits(reader,7) if ch=-1 then exit end if bytes &= ch end while printf(1,"\"%s\" as bytes: %s (length %d)\n",{bytes,as_hexb(bytes),length(bytes)})
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Modula-3
Modula-3
INTERFACE PPM;   IMPORT Bitmap, Pathname;   PROCEDURE Create(imgfile: Pathname.T; img: Bitmap.T);   END PPM.
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Nim
Nim
import bitmap import streams   #---------------------------------------------------------------------------------------------------   proc writePPM*(img: Image, stream: Stream) = ## Write an image to a PPM stream.   stream.writeLine("P6 ", $img.w, " ", $img.h, " 255")   for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b))   #---------------------------------------------------------------------------------------------------   proc writePPM*(img: Image; filename: string) = ## Write an image in a PPM file.   var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close()   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Racket
Racket
  #lang racket (require racket/draw)   (define (read-ppm port) (parameterize ([current-input-port port]) (define magic (read)) (define width (read)) (define height (read)) (define maxcol (read)) (define bm (make-object bitmap% width height)) (define dc (new bitmap-dc% [bitmap bm])) (send dc set-smoothing 'unsmoothed) (define (adjust v) (* 255 (/ v maxcol))) (for/list ([x width]) (for/list ([y height]) (define red (read)) (define green (read)) (define blue (read)) (define color (make-object color% (adjust red) (adjust green) (adjust blue))) (send dc set-pen color 1 'solid) (send dc draw-point x y))) bm))  
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @.data; }   role PGM { has @.GS; method P5 returns Blob { "P5\n{self.width} {self.height}\n255\n".encode('ascii') ~ Blob.new: self.GS } }   sub load-ppm ( $ppm ) { my $fh = $ppm.IO.open( :enc('ISO-8859-1') ); my $type = $fh.get; my ($width, $height) = $fh.get.split: ' '; my $depth = $fh.get; Bitmap.new( width => $width.Int, height => $height.Int, data => ( $fh.slurp.ords.rotor(3).map: { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } ) ) }   sub grayscale ( Bitmap $bmp ) { $bmp.GS = map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data; }   my $filename = './camelia.ppm';   my Bitmap $b = load-ppm( $filename ) but PGM;   grayscale($b);   './camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#BASIC
BASIC
10 LET A%=0 20 LET B%=NOT(A%) 30 PRINT "THIS VERSION OF BASIC USES" 40 PRINT B%; " AS ITS TRUE VALUE" 50 IF A% THEN PRINT "TEST ONE DOES NOT PRINT" 60 IF B% THEN PRINT "TEST TWO DOES PRINT" 70 IF A%=0 THEN PRINT "TEST THREE (FALSE BY COMPARISON) DOES PRINT" 80 IF B%=0 THEN PRINT "TEST FOUR (FALSE BY COMPARISON) DOES NOT PRINT" 90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT" 100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT" 110 END
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Batch_File
Batch File
  @echo off ::true set "a=x" ::false set "b="   if defined a ( echo a is true ) else ( echo a is false ) if defined b ( echo b is true ) else ( echo b is false )   pause>nul  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: rot (in string: stri, in integer: encodingKey) is func result var string: encodedStri is ""; local var char: ch is ' '; var integer: index is 0; begin encodedStri := stri; for ch key index range stri do if ch >= 'a' and ch <= 'z' then ch := chr((ord(ch) - ord('a') + encodingKey) rem 26 + ord('a')); elsif ch >= 'A' and ch <= 'Z' then ch := chr((ord(ch) - ord('A') + encodingKey) rem 26 + ord('A')); end if; encodedStri @:= [index] ch; end for; end func;   const proc: main is func local const integer: exampleKey is 3; const string: testText is "The five boxing wizards jump quickly"; begin writeln("Original: " <& testText); writeln("Encrypted: " <& rot(testText, exampleKey)); writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey)); end func;
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Ada
Ada
type Pixel_Count is mod 2**64; type Histogram is array (Luminance) of Pixel_Count;   function Get_Histogram (Picture : Grayscale_Image) return Histogram is Result : Histogram := (others => 0); begin for I in Picture'Range (1) loop for J in Picture'Range (2) loop declare Count : Pixel_Count renames Result (Picture (I, J)); begin Count := Count + 1; end; end loop; end loop; return Result; end Get_Histogram;
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   Width% = 200 Height% = 200   VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lenagrey   DIM hist%(255), idx%(255) FOR i% = 0 TO 255 : idx%(i%) = i% : NEXT   REM Build histogram: FOR y% = 0 TO Height%-1 FOR x% = 0 TO Width%-1 l% = FNgetpixel(x%,y%) AND &FF hist%(l%) += 1 NEXT NEXT y%   REM Sort histogram: C% = 256 CALL Sort%, hist%(0), idx%(0)   REM Find median: total% = SUM(hist%()) half% = 0 FOR i% = 0 TO 255 half% += hist%(i%) IF half% >= total%/2 THEN median% = idx%(i%) EXIT FOR ENDIF NEXT   REM Display black & white version: FOR y% = 0 TO Height%-1 FOR x% = 0 TO Width%-1 l% = FNgetpixel(x%,y%) AND &FF IF l% > median% THEN PROCsetpixel(x%,y%,255,255,255) ELSE PROCsetpixel(x%,y%,0,0,0) ENDIF NEXT NEXT y% END   DEF PROCsetpixel(x%,y%,r%,g%,b%) COLOUR 1,r%,g%,b% GCOL 1 LINE x%*2,y%*2,x%*2,y%*2 ENDPROC   DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#11l
11l
V x = 10 V y = 2 print(‘x = ’x) print(‘y = ’y) print(‘NOT x = ’(-)x) print(‘x AND y = ’(x [&] y)) print(‘x OR y = ’(x [|] y)) print(‘x XOR y = ’(x (+) y)) print(‘x SHL y = ’(x << y)) print(‘x SHR y = ’(x >> y)) print(‘x ROL y = ’rotl(x, y)) print(‘x ROR y = ’rotr(x, y))
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#11l
11l
T Colour Byte r, g, b   F (r, g, b) .r = r .g = g .b = b   F ==(other) R .r == other.r & .g == other.g & .b == other.b   V black = Colour(0, 0, 0) V white = Colour(255, 255, 255)   T Bitmap Int width, height Colour background [[Colour]] map   F (width = 40, height = 40, background = white) assert(width > 0 & height > 0) .width = width .height = height .background = background .map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))   F fillrect(x, y, width, height, colour = black) assert(x >= 0 & y >= 0 & width > 0 & height > 0) L(h) 0 .< height L(w) 0 .< width .map[y + h][x + w] = colour   F chardisplay() V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’)) txt = txt.map(row -> ‘|’row‘|’) txt.insert(0, ‘+’(‘-’ * .width)‘+’) txt.append(‘+’(‘-’ * .width)‘+’) print(reversed(txt).join("\n"))   F set(x, y, colour = black) .map[y][x] = colour   F get(x, y) R .map[y][x]   F circle(x0, y0, radius, colour = black) V f = 1 - radius V ddf_x = 1 V ddf_y = -2 * radius V x = 0 V y = radius .set(x0, y0 + radius, colour) .set(x0, y0 - radius, colour) .set(x0 + radius, y0, colour) .set(x0 - radius, y0, colour)   L x < y I f >= 0 y-- ddf_y += 2 f += ddf_y x++ ddf_x += 2 f += ddf_x .set(x0 + x, y0 + y, colour) .set(x0 - x, y0 + y, colour) .set(x0 + x, y0 - y, colour) .set(x0 - x, y0 - y, colour) .set(x0 + y, y0 + x, colour) .set(x0 - y, y0 + x, colour) .set(x0 + y, y0 - x, colour) .set(x0 - y, y0 - x, colour)   V bitmap = Bitmap(25, 25) bitmap.circle(x0' 12, y0' 12, radius' 12) bitmap.chardisplay()
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#PicoLisp
PicoLisp
(de write7bitwise (Lst) (let (Bits 0 Byte) (for N Lst (if (=0 Bits) (setq Bits 7 Byte (* 2 N)) (wr (| Byte (>> (dec 'Bits) N))) (setq Byte (>> (- Bits 8) N)) ) ) (unless (=0 Bits) (wr Byte) ) ) )   (de read7bitwise () (make (let (Bits 0 Byte) (while (rd 1) (let N @ (link (if (=0 Bits) (>> (one Bits) N) (| Byte (>> (inc 'Bits) N)) ) ) (setq Byte (& 127 (>> (- Bits 7) N))) ) ) (when (= 7 Bits) (link Byte) ) ) ) )
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always quantized by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a rough (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see LZW compression) use fixed or variable words nine (or more) bits long. Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. Errors handling is not mandatory
#PL.2FI
PL/I
declare onebit bit(1) aligned, bs bit (1000) varying aligned; on endfile (sysin) go to ending; bs = ''b; do forever; get edit (onebit) (F(1)); bs = bs || onebit; end; ending: bs = bs || copy('0'b, mod(length(bs), 8) ); /* pad length to a multiple of 8 */ put edit (bs) (b);
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#OCaml
OCaml
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Oz
Oz
functor import Bitmap Open export %% Read Write define %% Omitted: Read   proc {Write B=bitmap(array2d(width:W height:H ...)) Filename} F = {New Open.file init(name:Filename flags:[write create truncate binary])}   proc {WriteColor8 color(R G B)} {F write(vs:[R G B])} end   fun {ToBytes C} [C div 0x100 C mod 0x100] end   proc {WriteColor16 color(R G B)} {F write(vs:{Flatten {Map [R G B] ToBytes}})} end   MaxCol = {Bitmap.maxValue B} MaxVal#Writer = if MaxCol =< 0xff then 0xff#WriteColor8 else 0xffff#WriteColor16 end Header = "P6\n"#W#" "#H#" "#MaxVal#"\n" in try {F write(vs:Header)} {Bitmap.forAllPixels B Writer} finally {F close} end end end
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#REXX
REXX
/*REXX program reads a PPM formatted image file, and creates a gray─scale image of it. */ parse arg iFN oFN /*obtain optional argument from the CL.*/ if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/ if oFN=='' | oFN=="," then oFN= 'greyscale' /* " " " " " " */ iFID= iFN'.ppm'; oFID= oFN'.ppm' /*complete the input and output FIDs.*/ call charin iFID, 1, 0 /*set the position of the input file. */ y=charin(iFID, , copies(9, digits() ) ) /*read the entire input file ───► X */ parse var y id 3 c 4 3 width height # pixels /*extract header info from the PPM hdr.*/ LF= 'a'x /*define a comment separator (in hdr).*/ /* ◄─── LF delimiters & comments*/ if c==LF then do; commentEND=pos(LF, y, 4) /*point to the last char in the comment*/ /* ◄─── LF delimiters & comments*/ parse var y =(commentEND) +1 width height # pixels /* ◄─── LF delimiters & comments*/ end /* ◄─── LF delimiters & comments*/ /* [↓] has an alternative delimiter? */ /* ◄─── LF delimiters & comments*/ z=pos(LF, height); if z\==0 then parse var height height =(z) +1 # pixels /* ◄─── LF delimiters & comments*/ z=pos(LF, # ); if z\==0 then parse var # # =(z) +1 pixels /* ◄─── LF delimiters & comments*/ chunk=4000 /*chunk size to be written at one time.*/ LenPixels= length(pixels)   do j=0 for 256; _=d2c(j); @._=j; @@.j=_ /*build two tables for fast conversions*/ end /*j*/   call charout oFID, , 1 /*set the position of the output file. */ call charout oFID, id || width height #' ' /*write the header followed by a blank.*/ !=1 do until !>=LenPixels; $= /*$: partial output string so far.*/ do !=! by 3 for chunk /*chunk: # pixels converted at 1 time.*/ parse var pixels =(!) r +1 g +1 b +1 /*obtain the next RGB of a PPM pixel.*/ if r=='' then leave /*has the end─of─string been reached? */ _=(.2126*@.r + .7152*@.g + .0722*@.b )%1 /*an integer RGB greyscale of a pixel. */ $=$ || @@._ || @@._ || @@._ /*lump (grey) R G B pixels together. */ end /*!*/ /* [↑] D2C converts decimal ───► char*/ call charout oFID, $ /*write the next bunch of pixels. */ end /*until*/   call charout oFID /*close the output file just to be safe*/ say 'File ' oFID " was created." /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#bc
bc
{1?34} 34 {⟨⟩?34} ERROR
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Befunge
Befunge
{1?34} 34 {⟨⟩?34} ERROR
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#SequenceL
SequenceL
import <Utilities/Sequence.sl>; import <Utilities/Conversion.sl>;   lowerAlphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; upperAlphabet := "abcdefghijklmnopqrstuvwxyz";   caesarEncrypt(ch, key) := let correctAlphabet := lowerAlphabet when some(ch = lowerAlphabet) else upperAlphabet;   index := Sequence::firstIndexOf(correctAlphabet, ch);   newIndex := (index + key - 1) mod 26 + 1; in ch when not(some(ch = lowerAlphabet) or some(ch = upperAlphabet)) else correctAlphabet[newIndex];   caesarDecrypt(ch, key) := caesarEncrypt(ch, 26 - key);   main(args(2)) := let key := Conversion::stringToInt(args[2]); encrypted := caesarEncrypt(args[1], key); decrypted := caesarDecrypt(encrypted, key); in "Input: \t" ++ args[1] ++ "\n" ++ "Encrypted:\t" ++ encrypted ++ "\n" ++ "Decrypted:\t" ++ decrypted;
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#11l
11l
V majors = ‘north east south west’.split(‘ ’) majors *= 2 V quarter1 = ‘N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N’.split(‘,’) V quarter2 = quarter1.map(p -> p.replace(‘NE’, ‘EN’))   F degrees2compasspoint(=d) d = (d % 360) + 360 / 64 V majorindex = Int(d / 90) V minorindex = Int((d % 90 * 4) I/ 45) V p1 = :majors[majorindex] V p2 = :majors[majorindex + 1] [String] q I p1 C (‘north’, ‘south’) q = :quarter1 E q = :quarter2 R q[minorindex].replace(‘N’, p1).replace(‘E’, p2).capitalize()   :start: L(i) 33 V d = i * 11.25 S i % 3 1 d += 5.62 2 d -= 5.62 V n = i % 32 + 1 print(‘#2.0 #<18 #4.2°’.format(n, degrees2compasspoint(d), d))
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#C
C
typedef unsigned int histogram_t; typedef histogram_t *histogram;   #define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )   histogram get_histogram(grayimage im); luminance histogram_median(histogram h);
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height. Test task Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows: Convert image to grayscale; Compute the histogram Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance. Replace each pixel of luminance lesser than the median to black, and others to white. Use read/write ppm file, and grayscale image solutions.
#Common_Lisp
Common Lisp
(defpackage #:histogram (:use #:cl #:opticl))   (in-package #:histogram)   (defun color->gray-image (image) (check-type image 8-bit-rgb-image) (let ((gray-image (with-image-bounds (height width) image (make-8-bit-gray-image height width :initial-element 0)))) (do-pixels (i j) image (multiple-value-bind (r g b) (pixel image i j) (let ((gray (+ (* 0.2126 r) (* 0.7152 g) (* 0.0722 b)))) (setf (pixel gray-image i j) (round gray))))) gray-image))   (defun make-histogram (image) (check-type image 8-bit-gray-image) (let ((histogram (make-array 256 :element-type 'fixnum :initial-element 0))) (do-pixels (i j) image (incf (aref histogram (pixel image i j)))) histogram))   (defun find-median (histogram) (loop with num-pixels = (loop for count across histogram sum count) with half = (/ num-pixels 2) for count across histogram for i from 0 sum count into acc when (>= acc half) return i))   (defun gray->black&white-image (image) (check-type image 8-bit-gray-image) (let* ((histogram (make-histogram image)) (median (find-median histogram)) (bw-image (with-image-bounds (height width) image (make-1-bit-gray-image height width :initial-element 0)))) (do-pixels (i j) image (setf (pixel bw-image i j) (if (<= (pixel image i j) median) 1 0))) bw-image))   (defun main () (let* ((image (read-jpeg-file "lenna.jpg")) (bw-image (gray->black&white-image (color->gray-image image)))) (write-pbm-file "lenna-bw.pbm" bw-image)))
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#360_Assembly
360 Assembly
* Bitwise operations 15/02/2017 BITWISE CSECT USING BITWISE,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 L R1,A XDECO R1,PG MVC OP,=CL7'A=' XPRNT OP,L'OP+L'PG L R1,B XDECO R1,PG MVC OP,=CL7'B=' XPRNT OP,L'OP+L'PG * And L R1,A N R1,B XDECO R1,PG MVC OP,=C'A AND B' XPRNT OP,L'OP+L'PG * Or L R1,A O R1,B XDECO R1,PG MVC OP,=C'A OR B' XPRNT OP,L'OP+L'PG * Xor L R1,A X R1,B XDECO R1,PG MVC OP,=C'A XOR B' XPRNT OP,L'OP+L'PG * Not L R1,A X R1,=X'FFFFFFFF' not (by xor -1) XDECO R1,PG MVC OP,=CL7'NOT A' XPRNT OP,L'OP+L'PG * MVC A,=X'80000008' a=-2147483640 (-2^31+8) L R1,A XDECO R1,PG MVC OP,=CL7'A=' XPRNT OP,L'OP+L'PG * shift right arithmetic (on 31 bits) L R1,A SRA R1,3 XDECO R1,PG MVC OP,=C'A SRA 3' XPRNT OP,L'OP+L'PG * shift left arithmetic (on 31 bits) L R1,A SLA R1,3 XDECO R1,PG MVC OP,=C'A SLA 3' XPRNT OP,L'OP+L'PG * shift right logical (on 32 bits) L R1,A SRL R1,3 XDECO R1,PG MVC OP,=C'A SRL 3' XPRNT OP,L'OP+L'PG * shift left logical (on 32 bits) L R1,A SLL R1,3 XDECO R1,PG MVC OP,=C'A SLL 3' XPRNT OP,L'OP+L'PG * RETURN L R13,4(0,R13) LM R14,R12,12(R13) XR R15,R15 BR R14 A DC F'21' B DC F'3' OP DS CL7 PG DS CL12 YREGS END BITWISE
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Action.21
Action!
INCLUDE "H6:RGBCIRCL.ACT" ;from task Midpoint circle algorithm   RGB black,yellow,violet,blue   PROC DrawImage(RgbImage POINTER img BYTE x,y) RGB POINTER ptr BYTE i,j   ptr=img.data FOR j=0 TO img.h-1 DO FOR i=0 TO img.w-1 DO IF RgbEqual(ptr,yellow) THEN Color=1 ELSEIF RgbEqual(ptr,violet) THEN Color=2 ELSEIF RgbEqual(ptr,blue) THEN Color=3 ELSE Color=0 FI Plot(x+i,y+j) ptr==+RGBSIZE OD OD RETURN   PROC Main() RgbImage img BYTE CH=$02FC,width=[81],height=[51],st=[3] BYTE ARRAY ptr(12393) BYTE n INT x,y RGB POINTER col   Graphics(7+16) SetColor(0,13,12) ;yellow SetColor(1,4,8)  ;violet SetColor(2,8,6)  ;blue SetColor(4,0,0)  ;black   RgbBlack(black) RgbYellow(yellow) RgbViolet(violet) RgbBlue(blue)   InitRgbImage(img,width,height,ptr) FillRgbImage(img,black)   FOR n=0 TO height/st DO IF n MOD 3=0 THEN col=yellow ELSEIF n MOD 3=1 THEN col=violet ELSE col=blue FI RgbCircle(img,width/2,height/2,st*n,col) OD   DrawImage(img,(160-width)/2,(96-height)/2)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Ada
Ada
procedure Circle ( Picture : in out Image; Center  : Point; Radius  : Natural; Color  : Pixel ) is F  : Integer := 1 - Radius; ddF_X : Integer := 0; ddF_Y : Integer := -2 * Radius; X  : Integer := 0; Y  : Integer := Radius; begin Picture (Center.X, Center.Y + Radius) := Color; Picture (Center.X, Center.Y - Radius) := Color; Picture (Center.X + Radius, Center.Y) := Color; Picture (Center.X - Radius, Center.Y) := Color; while X < Y loop if F >= 0 then Y := Y - 1; ddF_Y := ddF_Y + 2; F := F + ddF_Y; end if; X := X + 1; ddF_X := ddF_X + 2; F := F + ddF_X + 1; Picture (Center.X + X, Center.Y + Y) := Color; Picture (Center.X - X, Center.Y + Y) := Color; Picture (Center.X + X, Center.Y - Y) := Color; Picture (Center.X - X, Center.Y - Y) := Color; Picture (Center.X + Y, Center.Y + X) := Color; Picture (Center.X - Y, Center.Y + X) := Color; Picture (Center.X + Y, Center.Y - X) := Color; Picture (Center.X - Y, Center.Y - X) := Color; end loop; end Circle;