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/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #zkl | zkl | fcn waterCollected(walls){
// compile max wall heights from left to right and right to left
// then each pair is left/right wall of that cell.
// Then the min of each wall pair == water height for that cell
scanl(walls,(0).max) // scan to right, f is max(0,a,b)
.zipWith((0).MAX.min, // f is MAX.min(a,b) == min(a,b)
scanl(walls.reverse(),(0).max).reverse()) // right to left
// now subtract the wall height from the water level and add 'em up
.zipWith('-,walls).filter('>(0)).sum(0);
}
fcn scanl(xs,f,i=0){ // aka reduce but save list of results
xs.reduce('wrap(s,x,a){ s=f(s,x); a.append(s); s },i,ss:=List());
ss
} // scanl((1,5,3,7,2),max,0) --> (1,5,5,7,7) |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Cowgol | Cowgol | include "cowgol.coh";
record Vector is
x: int32; # Cowgol does not have floating point types,
y: int32; # but for the examples it does not matter.
z: int32;
end record;
sub print_signed(n: int32) is
if n < 0 then
print_char('-');
n := -n;
end if;
print_i32(n as uint32);
end sub;
sub print_vector(v: [Vector]) is
print_char('(');
print_signed(v.x);
print(", ");
print_signed(v.y);
print(", ");
print_signed(v.z);
print_char(')');
print_nl();
end sub;
sub dot(a: [Vector], b: [Vector]): (r: int32) is
r := a.x * b.x + a.y * b.y + a.z * b.z;
end sub;
# Unfortunately it is impossible to return a complex type
# from a function. We have to have the caller pass in a pointer
# and have this function set its fields.
sub cross(a: [Vector], b: [Vector], r: [Vector]) is
r.x := a.y * b.z - a.z * b.y;
r.y := a.z * b.x - a.x * b.z;
r.z := a.x * b.y - a.y * b.x;
end sub;
sub scalarTriple(a: [Vector], b: [Vector], c: [Vector]): (r: int32) is
var v: Vector;
cross(b, c, &v);
r := dot(a, &v);
end sub;
sub vectorTriple(a: [Vector], b: [Vector], c: [Vector], r: [Vector]) is
var v: Vector;
cross(b, c, &v);
cross(a, &v, r);
end sub;
var a: Vector := {3, 4, 5};
var b: Vector := {4, 3, 5};
var c: Vector := {-5, -12, -13};
var scratch: Vector;
print(" a = "); print_vector(&a);
print(" b = "); print_vector(&b);
print(" c = "); print_vector(&c);
print(" a . b = "); print_signed(dot(&a, &b)); print_nl();
print(" a x b = "); cross(&a, &b, &scratch); print_vector(&scratch);
print("a . b x c = "); print_signed(scalarTriple(&a, &b, &c)); print_nl();
print("a x b x c = "); vectorTriple(&a, &b, &c, &scratch);
print_vector(&scratch); |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Fortran | Fortran | program isin
use ctype
implicit none
character(20) :: test(7) = ["US0378331005 ", &
"US0373831005 ", &
"U50378331005 ", &
"US03378331005 ", &
"AU0000XVGZA3 ", &
"AU0000VXGZA3 ", &
"FR0000988040 "]
print *, check_isin(test)
contains
elemental logical function check_isin(a)
character(*), intent(in) :: a
integer :: s(24)
integer :: i, j, k, n, v
check_isin = .false.
n = len_trim(a)
if (n /= 12) return
! Convert to an array of digits
j = 0
do i = 1, n
k = iachar(a(i:i))
if (k >= 48 .and. k <= 57) then
if (i < 3) return
k = k - 48
j = j + 1
s(j) = k
else if (k >= 65 .and. k <= 90) then
if (i == 12) return
k = k - 65 + 10
j = j + 1
s(j) = k / 10
j = j + 1
s(j) = mod(k, 10)
else
return
end if
end do
! Compute checksum
v = 0
do i = j - 1, 1, -2
k = 2 * s(i)
if (k > 9) k = k - 9
v = v + k
end do
do i = j, 1, -2
v = v + s(i)
end do
check_isin = 0 == mod(v, 10)
end function
end program |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Ela | Ela | open random number list
vdc bs n = vdc' 0.0 1.0 n
where vdc' v d n
| n > 0 = vdc' v' d' n'
| else = v
where
d' = d * bs
rem = n % bs
n' = truncate (n / bs)
v' = v + rem / d' |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Elixir | Elixir | defmodule Van_der_corput do
def sequence( n, base \\ 2 ) do
"0." <> (Integer.to_string(n, base) |> String.reverse )
end
def float( n, base \\ 2 ) do
Integer.digits(n, base) |> Enum.reduce(0, fn i,acc -> (i + acc) / base end)
end
def fraction( n, base \\ 2 ) do
str = Integer.to_string(n, base) |> String.reverse
denominator = Enum.reduce(1..String.length(str), 1, fn _,acc -> acc*base end)
reduction( String.to_integer(str, base), denominator )
end
defp reduction( 0, _ ), do: "0"
defp reduction( numerator, denominator ) do
gcd = gcd( numerator, denominator )
"#{ div(numerator, gcd) }/#{ div(denominator, gcd) }"
end
defp gcd( a, 0 ), do: a
defp gcd( a, b ), do: gcd( b, rem(a, b) )
end
funs = [ {"Float(Base):", &Van_der_corput.sequence/2},
{"Float(Decimal):", &Van_der_corput.float/2 },
{"Fraction:", &Van_der_corput.fraction/2} ]
Enum.each(funs, fn {title, fun} ->
IO.puts title
Enum.each(2..5, fn base ->
IO.puts " Base #{ base }: #{ Enum.map_join(0..9, ", ", &fun.(&1, base)) }"
end)
end) |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #Apex | Apex | EncodingUtil.urlDecode('http%3A%2F%2Ffoo%20bar%2F', 'UTF-8');
EncodingUtil.urlDecode('google.com/search?q=%60Abdu%27l-Bah%C3%A1', 'UTF-8'); |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #AppleScript | AppleScript | AST URL decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1" |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #ALGOL_W | ALGOL W | begin
string(80) s;
integer n;
write( "Enter a string > " );
read( s );
write( "Enter an integer> " );
read( n )
end. |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
#import lib/input.bas.lib
#include include/flow-input.h
DEF-MAIN(argv,argc)
CLR-SCR
MSET( número, cadena )
LOCATE(2,2), PRNL( "Input an string : "), LOC-COL(20), LET( cadena := READ-STRING( cadena ) )
LOCATE(3,2), PRNL( "Input an integer: "), LOC-COL(20), LET( número := INT( VAL(READ-NUMBER( número )) ) )
LOCATE(5,2), PRNL( cadena, "\n ",número )
END
|
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputWin64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ YPOSTEXTINPUT, 18
.equ LGBUFFER, 50
.equ FONTSIZE, 6
/* constantes X11 */
.equ KeyPressed, 2
.equ ButtonPress, 4
.equ ButtonPress, 4
.equ EnterNotify, 7
.equ LeaveNotify, 8
.equ ClientMessage, 33
.equ KeyPressMask, 1
.equ ButtonPressMask, 4
.equ ButtonReleaseMask, 8
.equ ExposureMask, 1<<15
.equ StructureNotifyMask, 1<<17
.equ EnterWindowMask, 1<<4
.equ LeaveWindowMask, 1<<5
.equ CWBorderWidth, 1<<4
/* structures descriptions are in end oh this program */
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szRetourligne: .asciz "\n"
szMessErreur: .asciz "Server X11 not found.\n"
szMessErrfen: .asciz "Error create X11 window.\n"
szMessErrGC: .asciz "Error create Graphic Context.\n"
szMessErrButton: .asciz "Error create button.\n"
szMessErrButtonGC: .asciz "Error create button Graphic Context.\n"
szMessErrInput: .asciz "Error create input window.\n"
szMessErrInputGC: .asciz "Error create input Graphic Context.\n"
//szMessGoodBye: .asciz "There have been no clicks yet"
szCursor: .asciz "_"
szTextButton: .asciz "PUSH"
szMessResult: .asciz "Text : @ Value @ "
szLibText: .asciz "Text :"
szLibValue: .asciz "Value : "
szLibDW: .asciz "WM_DELETE_WINDOW" // message close window
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
qDisplay: .skip 8 // Display address
qDefScreen: .skip 8 // Default screen address
identWin: .skip 8 // window ident
qCounterClic: .skip 8 // counter clic button
//qLongTexte: .skip 8
//ptZoneS: .skip 8 // pointeur zone saisie
ptMessage: .skip 8 // final message pointer
sZoneConv: .skip 24
wmDeleteMessage: .skip 16 // ident close message
stEvent: .skip 400 // provisional size
stButton: .skip BT_fin
buffer: .skip 500
stInputText: .skip Input_fin
stInputValue: .skip Input_fin
stWindowChge: .skip XWCH_fin
sSaisieCar: .skip LGBUFFER
sTexteSaisi: .skip LGBUFFER
sValueSaisi: .skip LGBUFFER
key: .skip 4 // code touche
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main // program entry
main: // INFO: main
mov x0,#0 // open server X
bl XOpenDisplay
cmp x0,#0
beq erreur
// Ok return Display address
ldr x1,qAdrqDisplay
str x0,[x1] // store Display address for future use
mov x28,x0 // and in register 28
ldr x2,[x28,Disp_default_screen] // load default screen
ldr x1,qAdrqDefScreen
str x2,[x1] //store default_screen
mov x2,x28
ldr x0,[x2,Disp_screens] // screen list
//screen areas
ldr x5,[x0,Screen_white_pixel] // white pixel
ldr x3,[x0,Screen_black_pixel] // black pixel
ldr x4,[x0,Screen_root_depth] // bits par pixel
ldr x1,[x0,Screen_root] // root windows
// create window x11
mov x0,x28 //display
mov x2,#0 // position X
mov x3,#0 // position Y
mov x4,600 // weight
mov x5,400 // height
mov x6,0 // bordure ???
ldr x7,0 // ?
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq erreurF
ldr x1,qAdridentWin
str x0,[x1] // store window ident for future use
mov x27,x0 // and in register 27
// Correction of window closing error
mov x0,x28 // Display address
ldr x1,qAdrszLibDW // atom name address
mov x2,#1 // False create atom if not exist
bl XInternAtom
cmp x0,#0
ble erreurF
ldr x1,qAdrwmDeleteMessage // address message
str x0,[x1]
mov x2,x1 // address atom create
mov x0,x28 // display address
mov x1,x27 // window ident
mov x3,#1 // number of protocoles
bl XSetWMProtocols
cmp x0,#0
ble erreurF
// authorization of seizures
mov x0,x28 // display address
mov x1,x27 // window ident
ldr x2,qFenetreMask // mask
bl XSelectInput
cmp x0,#0
ble 99f
// create Graphic Context
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC // GC address -> x26
cbz x0,erreurF
// create Graphic Context 1
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC1 // GC address -> x25
cbz x0,erreurF
// Display window
mov x1,x27 // ident window
mov x0,x28 // Display address
bl XMapWindow
ldr x0,qAdrszLibText
mov x1,x27
mov x2,5
mov x3,70
bl displayText
ldr x0,qAdrszLibValue
mov x1,x27
mov x2,280
mov x3,70
bl displayText
bl createButton // create button on screen
bl createInputText // create input text window
bl createInputValue // create input value window
1: // events loop
bl traitEvents
// other events
cbz x0,1b // and loop
//TODO: close ??
mov x0,0 // end Ok
b 100f
//TODO: close ??
3:
ldr x0,qAdrstEvent // events structure address
bl evtButtonMouse
b 1b
erreurF: // error create window
ldr x0,qAdrszMessErrfen
bl affichageMess
mov x0,1
b 100f
erreur: // error no server x11 active
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,1
100: // program standard end
mov x8,EXIT
svc 0
qBlanc: .quad 0xF0F0F0F0
qAdrqDisplay: .quad qDisplay
qAdrqDefScreen: .quad qDefScreen
qAdridentWin: .quad identWin
qAdrstEvent: .quad stEvent
qAdrszMessErrfen: .quad szMessErrfen
qAdrszMessErreur: .quad szMessErreur
qAdrwmDeleteMessage: .quad wmDeleteMessage
qAdrszLibDW: .quad szLibDW
//qAdrszMessGoodBye: .quad szMessGoodBye
qAdrszLibText: .quad szLibText
qAdrszLibValue: .quad szLibValue
qFenetreMask: .quad KeyPressMask|ButtonPressMask|StructureNotifyMask|ExposureMask|EnterWindowMask
/********************************************************************/
/* Events ***/
/********************************************************************/
traitEvents: // INFO: traitEvents
stp x20,lr,[sp,-16]! // save registers
mov x0,x28 // Display address
ldr x1,qAdrstEvent // events structure address
bl XNextEvent
ldr x0,qAdrstEvent // events structure address
ldr x1,[x0,#XAny_window] // what window ?
cmp x1,x27 // main window ?
bne 1f
bl evtMainWindow // yes
b 100f
1:
ldr x10,qAdrstInputText // input text window ?
ldr x11,[x10,Input_adresse]
cmp x1,x11
bne 2f
bl evtInputWindowText
mov x0,0 // other events
b 100f
2:
ldr x10,qAdrstInputValue // input value window
ldr x11,[x10,Input_adresse]
cmp x1,x11
bne 3f
bl evtInputWindowValue
mov x0,0 // other events
b 100f
3:
ldr x10,[x0,XAny_window] // window of event
ldr x11,qAdrstButton // load button ident
ldr x12,[x11,BT_adresse]
cmp x10,x12 // equal ?
bne 4f // no
bl evtButton
mov x0,0 // other events
b 100f
4: // other windows
mov x0,0 // other events
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* main windows events */
/******************************************************************/
/* x0 contains the events */
/* x1 contains the ident Window */
/* x0 return 0 if continue , 1 if program end */
evtMainWindow: // INFO: evtMainWindow
stp x20,lr,[sp,-16]! // save registers
ldr w0,[x0] // type in 4 first bytes
cmp w0,#ClientMessage // message for close window
beq 2f // yes -> end
mov x0,0 // other events
b 100f // and loop
2:
ldr x0,qAdrstEvent // events structure address
ldr x1,[x0,56] // location message code
ldr x2,qAdrwmDeleteMessage // equal ?
ldr x2,[x2]
mov x0,0
cmp x1,x2
bne 100f // no loop
mov x0,1 // end program
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* input text windows events */
/******************************************************************/
/* x0 contains the events */
/* x1 contains the ident Window */
evtButton: // INFO: evtButton
stp x20,lr,[sp,-16]! // save registers
ldr x10,[x0,#XAny_type]
cmp x10,ButtonPress
bne 1f
bl evtButtonMouse
b 100f
1:
cmp x10,#EnterNotify // mouse is on the button
bne 2f
ldr x3,qAdrstWindowChge // and change window border
mov x2,3
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
2:
cmp x10,#LeaveNotify // mouse is off the button
bne 3f
ldr x3,qAdrstWindowChge // and change window border
mov x2,1
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
3: // other event
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* input text windows events */
/******************************************************************/
/* x0 contains the events */
/* x1 contains the ident Window */
evtInputWindowText: // INFO: evtInputWindowText
stp x20,lr,[sp,-16]! // save registers
ldr x10,[x0,#XAny_type]
mov x20,x1
cmp x10,#KeyPressed // key character ?
bne 2f
// x0 events x1 window ident
ldr x2,qAdrstInputText
bl traitImput
b 100f
2:
cmp x10,#EnterNotify // mouse is on the window
bne 3f
ldr x0,qAdrstInputText // display text and cursor
bl displayInput
mov x1,x20
ldr x3,qAdrstWindowChge // and change window border
mov x2,3
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
3:
cmp x10,#LeaveNotify // the mouse is out the window
bne 4f
ldr x0,qAdrszCursor // erase the cursor
ldr x2,qAdrstInputText
ldr x2,[x2,Input_cursor]
mov x10,FONTSIZE
mul x2,x2,x10
mov x3,YPOSTEXTINPUT
bl eraseText1
mov x1,x20
ldr x3,qAdrstWindowChge // and chane window border
mov x2,1
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
4: // other event
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qFenSMask: .quad CWBorderWidth
qAdrstWindowChge: .quad stWindowChge
/******************************************************************/
/* input text windows events */
/******************************************************************/
/* x0 contains the events */
/* x1 contains the ident Window */
evtInputWindowValue: // INFO: evtInputWindowValue
stp x20,lr,[sp,-16]! // save registers
ldr x10,[x0,#XAny_type]
mov x20,x1
cmp x10,#KeyPressed // cas d'une touche
bne 2f
// x0 events x1 window ident
ldr x2,qAdrstInputValue
bl traitImput
b 100f
2:
cmp x10,#EnterNotify // mouse is on the window
bne 3f
ldr x0,qAdrstInputValue // display text and cursor
bl displayInput
mov x1,x20
ldr x3,qAdrstWindowChge // and change window border
mov x2,3
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
3:
cmp x10,#LeaveNotify // the mouse is out the window
bne 4f
ldr x0,qAdrszCursor // erase the cursor
ldr x2,qAdrstInputValue
ldr x2,[x2,Input_cursor]
mov x10,FONTSIZE
mul x2,x2,x10
mov x3,YPOSTEXTINPUT
bl eraseText1
mov x1,x20
ldr x3,qAdrstWindowChge // and chane window border
mov x2,1
str x2,[x3,#XWCH_border_width]
mov x0,x28 // display
ldr x2,qFenSMask
bl XConfigureWindow
b 100f
4: // other event
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* traitement Key pressed */
/******************************************************************/
/* x0 contains the event */
/* x1 contains the ident Window */
/* x2 contains address structure window*/
traitImput: // INFO: traitImput
stp x20,lr,[sp,-16]! // save registers
mov x20,x2 // save structure address
mov x21,x1 // save ident window
ldr x1,qAdrsSaisieCar // character input buffer
mov x2,#4 // buffer lenght
ldr x3,qAdrkey // code character
mov x4,0 // Specifies or returns the XComposeStatus structure or NULL.
bl XLookupString
cmp x0,#1 // character key ?
bne 1f
ldr x0,qAdrsSaisieCar // input character area
ldrb w22,[x0] // load byte
cmp x22,#13 // enter ?
beq 1f
ldr x0,[x20,Input_text] // erase input area
mov x1,x21
mov x2,0
mov x3,YPOSTEXTINPUT
bl eraseText1
ldr x0,qAdrszCursor
ldr x2,[x20,Input_cursor] // erase cursor
mov x1,x21
mov x10,FONTSIZE // Font size
mul x2,x2,x10
mov x3,YPOSTEXTINPUT
bl eraseText1
ldr x13,[x20,Input_text]
cmp x22,#8 // back
beq back
// voir autre touche
ldr x4,[x20,Input_cursor] //
strb w22,[x13,x4] // store input character at text end
add x4,x4,1
str x4,[x20,Input_cursor] // maj cursor location
b suiteaff
back:
ldr x4,[x20,Input_cursor] // text size
sub x4,x4,#1
str x4,[x20,Input_cursor] // maj cursor location
suiteaff:
strb wzr,[x13,x4] // zero -> text end
mov x0,x20
bl displayInput
b 100f
1: // other key
mov x0,x28
mov x1,#50
bl XBell // sound on
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsSaisieCar: .quad sSaisieCar
qAdrkey: .quad key
qAdrsTexteSaisi: .quad sTexteSaisi
/******************************************************************/
/* create Graphic Context */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC: // INFO: createGC
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x26,x0 // save GC
mov x0,x20 // display address
mov x1,x26
ldr x2,qRed // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x26 // return GC
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszMessErrGC: .quad szMessErrGC
qRed: .quad 0xFF0000
qGreen: .quad 0xFF00
qBlue: .quad 0xFF
qBlack: .quad 0x0
/******************************************************************/
/* create Graphic Context 1 */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC1: // INFO: createGC1
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x25,x0 // save GC
mov x0,x20 // display address
mov x1,x25
ldr x2,qBlanc // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x25 // return GC1
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* create button on screen */
/******************************************************************/
createButton: // INFO: createButton
stp x21,lr,[sp,-16]! // save registers
// create button window
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,500 // X position
mov x3,50 // Y position
mov x4,60 // weight
mov x5,30 // height
mov x6,1 // border
ldr x7,qBlack
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq 99f
ldr x21,qAdrstButton
str x0,[x21,BT_adresse] // save ident button
str xzr,[x21,BT_cbdata] // for next use
// autorisation des saisies
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
ldr x2,qButtonMask // mask
bl XSelectInput
// create Graphic Contexte of button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button ident
mov x2,#0
mov x3,#0
bl XCreateGC
cmp x0,#0
beq 98f
str x0,[x21,BT_GC] // store GC
// display button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
bl XMapWindow
ldr x0,qAdrszTextButton // text address
ldr x1,[x21,BT_adresse] // ident button
mov x2,#18 // position x
mov x3,#18 // position y
bl displayText
b 100f
98:
ldr x0,qAdrszMessErrButtonGC
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrButton
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrstButton: .quad stButton
qAdrszTextButton: .quad szTextButton
qAdrszMessErrButtonGC: .quad szMessErrButtonGC
qAdrszMessErrButton: .quad szMessErrButton
qButtonMask: .quad ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ExposureMask|LeaveWindowMask|EnterWindowMask
/******************************************************************/
/* create window input text */
/******************************************************************/
createInputText: // INFO: createInputText
stp x21,lr,[sp,-16]! // save registers
// create button window
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,50 // X position
mov x3,50 // Y position
mov x4,200 // weight
mov x5,30 // height
mov x6,1 // border
ldr x7,qBlack
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq 99f
ldr x21,qAdrstInputText
str x0,[x21,Input_adresse] // save ident button
// autorisation des saisies
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button address
ldr x2,qInputMask // mask
bl XSelectInput
// create Graphic Contexte of button
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button ident
mov x2,#0
mov x3,#0
bl XCreateGC
cmp x0,#0
beq 98f
str x0,[x21,Input_GC] // store GC
// display button
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button address
bl XMapWindow
ldr x6,qAdrsTexteSaisi
str x6,[x21,Input_text]
str xzr,[x21,Input_cursor]
b 100f
98:
ldr x0,qAdrszMessErrInputGC
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrInput
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrstInputText: .quad stInputText
qAdrszMessErrInputGC: .quad szMessErrInputGC
qAdrszMessErrInput: .quad szMessErrInput
qInputMask: .quad KeyPressMask|StructureNotifyMask|ExposureMask|LeaveWindowMask|EnterWindowMask
/******************************************************************/
/* create window input text */
/******************************************************************/
createInputValue: // INFO: createInputValue
stp x21,lr,[sp,-16]! // save registers
// create window
mov x0,x28 // display address
mov x1,x27 // ident main window
mov x2,340 // X position
mov x3,50 // Y position
mov x4,50 // weight
mov x5,30 // height
mov x6,1 // border
ldr x7,qBlack
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq 99f
ldr x21,qAdrstInputValue
str x0,[x21,Input_adresse] // save ident button
// autorisation des saisies
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button address
ldr x2,qInputMask // mask
bl XSelectInput
// create Graphic Contexte of button
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button ident
mov x2,#0
mov x3,#0
bl XCreateGC
cmp x0,#0
beq 98f
str x0,[x21,Input_GC] // store GC
// display button
mov x0,x28 // display address
ldr x1,[x21,Input_adresse] // button address
bl XMapWindow
ldr x6,qAdrsValueSaisi
str x6,[x21,Input_text]
str xzr,[x21,Input_cursor]
b 100f
98:
ldr x0,qAdrszMessErrInputGC
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrInput
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrstInputValue: .quad stInputValue
qAdrsValueSaisi: .quad sValueSaisi
/******************************************************************/
/* display text on screen */
/******************************************************************/
/* x0 contains the address of text */
/* x1 contains ident window */
/* x2 position X */
/* x3 position Y */
displayText: // INFO: displayText
stp x1,lr,[sp,-16]! // save registers
mov x5,x0 // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
mov x4,x3 // position y
mov x3,x2 // position x
mov x2,x26 // GC address
bl XDrawString
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* erase text on screen */
/******************************************************************/
/* x0 contains the address of text */
/* x1 window ident */
/* x2 position x */
/* x3 position y */
eraseText1: // INFO: eraseText1
stp x1,lr,[sp,-16]! // save registers
mov x5,x0 // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
mov x4,x3
mov x3,x2
mov x2,x25 // GC1 address
bl XDrawString
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* events clic mouse button */
/******************************************************************/
/* x0 contains the address of event */
evtButtonMouse: // INFO: evtButtonMouse
stp x20,lr,[sp,-16]! // save registers
ldr x10,[x0,XBE_window] // windows of event
ldr x11,qAdrstButton // load button ident
ldr x12,[x11,BT_adresse]
cmp x10,x12 // equal ?
bne 100f // no
ldr x20,qAdrptMessage // first entry
ldr x0,[x20]
cbz x0,1f
mov x1,x27
mov x2,50
mov x3,200
bl eraseText1 // yes erase the text
1:
ldr x1,qAdrstInputText // input text
ldr x1,[x1,Input_text]
ldrb w2,[x1]
cbz w2,100f // no input text
ldr x0,qAdrszMessResult
bl strInsertAtCharInc // insert text at @ character
mov x5,x0
ldr x1,qAdrstInputValue // input text
ldr x0,[x1,Input_text]
bl conversionAtoD // conversion value to decimal
// x0 contains the input value
ldr x1,qAdrsZoneConv // and decimal conversion
bl conversion10
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and insert result at @ character
str x0,[x20] // save message address
mov x1,x27
mov x2,50
mov x3,200
bl displayText // and display new text
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqCounterClic: .quad qCounterClic
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrptMessage: .quad ptMessage
/******************************************************************/
/* display input area */
/******************************************************************/
/* x0 contains area structure */
displayInput: // INFO: displayInput
stp x1,lr,[sp,-16]! // save registers
mov x10,x0 // save structure
ldr x0,[x10,Input_text] // text
ldr x6,[x10,Input_cursor] // position curseur
cbz x6,1f // if zero no text
mov x0,x28 // display address
ldr x1,[x10,Input_adresse] // ident window
ldr x2,[x10,Input_GC] // GC address
mov x3,0 // position x
mov x4,YPOSTEXTINPUT // position y
ldr x5,[x10,Input_text] // text
bl XDrawString
1: // display cursor
mov x0,x28 // Display address
ldr x1,[x10,Input_adresse] // ident window
ldr x2,[x10,Input_GC] // GC address
ldr x3,[x10,Input_cursor] // position x
mov x10,FONTSIZE
mul x3,x3,x10
mov x4,YPOSTEXTINPUT // position y
ldr x5,qAdrszCursor // cursor text
mov x6,1 // length
bl XDrawString
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszCursor: .quad szCursor
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
/*******************************************/
/* Structures */
/********************************************/
/*************************************************/
/* INFO: Structures */
/*********************************************/
/* Display définition */
.struct 0
Disp_ext_data: /* hook for extension to hang data */
.struct Disp_ext_data + 8
Disp_private1:
.struct Disp_private1 + 8
Disp_fd: /* Network socket. */
.struct Disp_fd + 4
Disp_private2:
.struct Disp_private2 + 4
Disp_proto_major_version: /* major version of server's X protocol */
.struct Disp_proto_major_version + 4
Disp_proto_minor_version: /* minor version of servers X protocol */
.struct Disp_proto_minor_version + 4
Disp_vendor: /* vendor of the server hardware OK*/
.struct Disp_vendor + 8
Disp_private3:
.struct Disp_private3 + 8
Disp_private8:
.struct Disp_private8 + 8
Disp_private5:
.struct Disp_private5 + 8
Disp_private6:
.struct Disp_private6 + 8
Disp_resource_alloc:
.struct Disp_resource_alloc + 8
Disp_byte_order: /* screen byte order, LSBFirst, MSBFirst */
.struct Disp_byte_order+ 4
Disp_bitmap_unit: /* padding and data requirements */
.struct Disp_bitmap_unit + 4
Disp_bitmap_pad: /* padding requirements on bitmaps */
.struct Disp_bitmap_pad + 4
Disp_bitmap_bit_order: /* LeastSignificant or MostSignificant */
.struct Disp_bitmap_bit_order + 4
Disp_nformats: /* number of pixmap formats in list */
.struct Disp_nformats + 8
Disp_pixmap_format: /* pixmap format list */
.struct Disp_pixmap_format + 8
Disp_private28:
.struct Disp_private28 + 4
Disp_release: /* release of the server */
.struct Disp_release + 4
Disp_private9:
.struct Disp_private9 + 8
Disp_private10:
.struct Disp_private10 + 8
Disp_qlen: /* Length of input event queue */
.struct Disp_qlen + 8 /* correction dec19 */
Disp_last_request_read: /* seq number of last event read */
.struct Disp_last_request_read + 8
Disp_request: /* sequence number of last request. */
.struct Disp_request + 8
Disp_private11:
.struct Disp_private11 + 8
Disp_private12:
.struct Disp_private12 + 8
Disp_private13:
.struct Disp_private13 + 8
Disp_private14:
.struct Disp_private14 + 8 /* correction Vim */
Disp_max_request_size: /* maximum number 32 bit words in request*/
.struct Disp_max_request_size + 8
Disp_db:
.struct Disp_db + 8 /* correction Vim */
Disp_private15:
.struct Disp_private15 + 8 /* correction Vim */
Disp_display_name: /* "host:display" string used on this connect*/
.struct Disp_display_name + 8
Disp_default_screen: /* default screen for operations */
.struct Disp_default_screen + 4
Disp_nscreens: /* number of screens on this server*/
.struct Disp_nscreens + 4
Disp_screens: /* pointer to list of screens */
.struct Disp_screens + 8
Disp_motion_buffer: /* size of motion buffer */
.struct Disp_motion_buffer + 8
Disp_private16:
.struct Disp_private16 + 8
Disp_min_keycode: /* minimum defined keycode */
.struct Disp_min_keycode + 4
Disp_max_keycode: /* maximum defined keycode */
.struct Disp_max_keycode + 4
Disp_private17:
.struct Disp_private17 + 8
Disp_private18:
.struct Disp_private18 + 8
Disp_private19:
.struct Disp_private19 + 8
Disp_xdefaults: /* contents of defaults from server */
.struct Disp_xdefaults + 8
Disp_fin:
/*****************************************/
/* Screen définition */
.struct 0
Screen_ext_data: /* hook for extension to hang data */
.struct Screen_ext_data + 8
Screen_Xdisplay: /* back pointer to display structure */
.struct Screen_Xdisplay + 8
Screen_root: /* Root window id. */
.struct Screen_root + 8
Screen_width:
.struct Screen_width + 4
Screen_height:
.struct Screen_height + 4
Screen_mwidth: /* width and height of in millimeters */
.struct Screen_mwidth + 4
Screen_mheight:
.struct Screen_mheight + 4
Screen_ndepths: /* number of depths possible */
.struct Screen_ndepths + 8
Screen_depths: /* list of allowable depths on the screen */
.struct Screen_depths + 8
Screen_root_depth: /* bits per pixel */
.struct Screen_root_depth + 8
Screen_root_visual: /* root visual */
.struct Screen_root_visual + 8
Screen_default_gc: /* GC for the root root visual */
.struct Screen_default_gc + 8
Screen_cmap: /* default color map */
.struct Screen_cmap + 8
Screen_white_pixel:
.struct Screen_white_pixel + 8
Screen_black_pixel:
.struct Screen_black_pixel + 8
Screen_max_maps: /* max and min color maps */
.struct Screen_max_maps + 4
Screen_min_maps:
.struct Screen_min_maps + 4
Screen_backing_store: /* Never, WhenMapped, Always */
.struct Screen_backing_store + 8
Screen_save_unders:
.struct Screen_save_unders + 8
Screen_root_input_mask: /* initial root input mask */
.struct Screen_root_input_mask + 8
Screen_fin:
/**********************************************/
/* Button structure */
.struct 0
BT_cbdata:
.struct BT_cbdata + 8
BT_adresse:
.struct BT_adresse + 8
BT_GC:
.struct BT_GC + 8
BT_Font:
.struct BT_Font + 8
BT_fin:
/****************************************/
/* Input text structure */
.struct 0
Input_adresse:
.struct Input_adresse + 8
Input_GC:
.struct Input_GC + 8
Input_text:
.struct Input_text + 8
Input_cursor:
.struct Input_cursor + 8
Input_Font:
.struct Input_Font + 8
Input_fin:
/***************************************************/
/* structure XButtonEvent */
.struct 0
XBE_type: //event type
.struct XBE_type + 8
XBE_serial: // No last request processed server */
.struct XBE_serial + 8
XBE_send_event: // true if this came from a SendEvent request */
.struct XBE_send_event + 8
XBE_display: // Display the event was read from
.struct XBE_display + 8
XBE_window: // "event" window it is reported relative to
.struct XBE_window + 8
XBE_root: // root window that the event occurred on
.struct XBE_root + 8
XBE_subwindow: // child window
.struct XBE_subwindow + 8
XBE_time: // milliseconds
.struct XBE_time + 8
XBE_x: // pointer x, y coordinates in event window
.struct XBE_x + 8
XBE_y:
.struct XBE_y + 8
XBE_x_root: // coordinates relative to root
.struct XBE_x_root + 8
XBE_y_root:
.struct XBE_y_root + 8
XBE_state: // key or button mask
.struct XBE_state + 8
XBE_button: // detail
.struct XBE_button + 8
XBE_same_screen: // same screen flag
.struct XBE_same_screen + 8
XBE_fin:
/***************************************************/
/* structure XAnyEvent */
.struct 0
XAny_type:
.struct XAny_type + 8
XAny_serial:
.struct XAny_serial + 8 /* # of last request processed by server */
XAny_send_event:
.struct XAny_send_event + 8 /* true if this came from a SendEvent request */
XAny_display:
.struct XAny_display + 8 /* Display the event was read from */
XAny_window:
.struct XAny_window + 8 /* window on which event was requested in event mask */
Xany_fin:
/****************************************/
/* structure de type XWindowChanges */
.struct 0
XWCH_x:
.struct XWCH_x + 4
XWCH_y:
.struct XWCH_y + 4
XWCH_width:
.struct XWCH_width + 4
XWCH_height:
.struct XWCH_height + 4
XWCH_border_width:
.struct XWCH_border_width + 4
XWCH_sibling:
.struct XWCH_sibling + 4
XWCH_stack_mode:
.struct XWCH_stack_mode + 4
XWCH_fin:
|
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #Ada | Ada | with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Ada.Integer_Text_IO;
with Ada.Text_IO;
with Ada.Wide_Wide_Text_IO;
procedure UTF8_Encode_And_Decode
is
package TIO renames Ada.Text_IO;
package WWTIO renames Ada.Wide_Wide_Text_IO;
package WWS renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
function To_Hex
(i : in Integer;
width : in Natural := 0;
fill : in Character := '0') return String
is
holder : String(1 .. 20);
begin
Ada.Integer_Text_IO.Put(holder, i, 16);
declare
hex : constant String := holder(Index(holder, "#")+1 .. holder'Last-1);
filled : String := Natural'Max(width, hex'Length) * fill;
begin
filled(filled'Last - hex'Length + 1 .. filled'Last) := hex;
return filled;
end;
end To_Hex;
input : constant Wide_Wide_String := "AöЖ€𝄞";
begin
TIO.Put_Line("Character Unicode UTF-8 encoding (hex)");
TIO.Put_Line(43 * '-');
for WWC of input loop
WWTIO.Put(WWC & " ");
declare
filled : String := 11 * ' ';
unicode : constant String := "U+" & To_Hex(Wide_Wide_Character'Pos(WWC), width => 4);
utf8_string : constant String := WWS.Encode((1 => WWC));
begin
filled(filled'First .. filled'First + unicode'Length - 1) := unicode;
TIO.Put(filled);
for C of utf8_string loop
TIO.Put(To_Hex(Character'Pos(C)) & " ");
end loop;
TIO.New_Line;
end;
end loop;
end UTF8_Encode_And_Decode; |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #C.2B.2B | C++ | #include <string>
using std::string;
// C++ functions with extern "C" can get called from C.
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
// Check that Message fits in Data.
if (*Length < Message.length())
return false; // C++ converts bool to int.
*Length = Message.length();
Message.copy(Data, *Length);
return true;
} |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #COBOL | COBOL | identification division.
program-id. Query.
environment division.
configuration section.
special-names.
call-convention 0 is extern.
repository.
function all intrinsic.
data division.
working-storage section.
01 query-result.
05 filler value "Here I am".
linkage section.
01 data-reference.
05 data-buffer pic x occurs 0 to 8192 times
depending on length-reference.
01 length-reference usage binary-long.
procedure division extern using data-reference length-reference.
if length(query-result) less than or equal to length-reference
and length-reference less than 8193 then
move query-result to data-reference
move length(query-result) to length-reference
move 1 to return-code
end-if
goback.
end program Query. |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #F.23 | F# | open System
open System.Text.RegularExpressions
let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v
let toUri = fun s -> Uri(s.ToString())
let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri)
urisFromString """
foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass?one
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
"""
|> Seq.iter (fun u ->
writeline "\nURI:" (u.ToString())
writeline " scheme:" (u.Scheme)
writeline " host:" (u.Host)
writeline " port:" (if u.Port < 0 then "" else u.Port.ToString())
writeline " path:" (u.AbsolutePath)
writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "")
writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "")
) |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #AWK | AWK | BEGIN {
for (i = 0; i <= 255; i++)
ord[sprintf("%c", i)] = i
}
# Encode string with application/x-www-form-urlencoded escapes.
function escape(str, c, len, res) {
len = length(str)
res = ""
for (i = 1; i <= len; i++) {
c = substr(str, i, 1);
if (c ~ /[0-9A-Za-z]/)
#if (c ~ /[-._*0-9A-Za-z]/)
res = res c
#else if (c == " ")
# res = res "+"
else
res = res "%" sprintf("%02X", ord[c])
}
return res
}
# Escape every line of input.
{ print escape($0) } |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #BBC_BASIC | BBC BASIC | PRINT FNurlencode("http://foo bar/")
END
DEF FNurlencode(url$)
LOCAL c%, i%
WHILE i% < LEN(url$)
i% += 1
c% = ASCMID$(url$, i%)
IF c%<&30 OR c%>&7A OR c%>&39 AND c%<&41 OR c%>&5A AND c%<&61 THEN
url$ = LEFT$(url$,i%-1) + "%" + RIGHT$("0"+STR$~c%,2) + MID$(url$,i%+1)
ENDIF
ENDWHILE
= url$ |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #C | C | int j; |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #C.23 | C# | int j; |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Comal | Comal | 0010 DIM eck#(0:1000)
0020 FOR i#:=1 TO 999 DO
0030 j#:=i#-1
0040 WHILE j#>0 AND eck#(i#)<>eck#(j#) DO j#:-1
0050 IF j#<>0 THEN eck#(i#+1):=i#-j#
0060 ENDFOR i#
0070 ZONE 5
0080 FOR i#:=1 TO 10 DO PRINT eck#(i#),
0090 PRINT
0100 FOR i#:=991 TO 1000 DO PRINT eck#(i#),
0110 PRINT
0120 END |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Common_Lisp | Common Lisp |
;;Tested using CLISP
(defun VanEck (x) (reverse (VanEckh x 0 0 '(0))))
(defun VanEckh (final index curr lst)
(if (eq index final)
lst
(VanEckh final (+ index 1) (howfar curr lst) (cons curr lst))))
(defun howfar (x lst) (howfarh x lst 0))
(defun howfarh (x lst runningtotal)
(cond
((null lst) 0)
((eq x (car lst)) (+ runningtotal 1))
(t (howfarh x (cdr lst) (+ runningtotal 1)))))
(format t "The first 10 elements are ~a~%" (VanEck 9))
(format t "The 990-1000th elements are ~a~%" (nthcdr 990 (VanEck 999)))
|
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #J | J |
Filter=: (#~`)(`:6)
odd =: 2&|
even =: -.@:odd
factors =: [: ([: /:~ [: */"1 ([: x: [) ^"1 [: > [: , [: { [: <@:i.@>: ])/ __ q: ]
digits =: 10&(#.inv)
tally =: # : [:
half =: -: : [:
even_number_of_digits =: even@:tally@:digits
same_digits =: digits@:[ -:&(/:~) ,&digits/@:]
assert 1 -: 1234 same_digits 23 14
assert 0 -: 1234 same_digits 23 140
half_the_digits =: (half@:tally@:digits@:[ = tally@:digits&>@:]) # ]
factors_with_half_the_digits =: half_the_digits factors
large =: (> <.@:%:)~ # ]
candidates =: large factors_with_half_the_digits
one_trailing_zero_permitted =: (0 < [: tally 0 -.~ 10&|)"1 Filter
pairs =: (% ,. ]) one_trailing_zero_permitted@:candidates
fangs =: (same_digits"0 1 # ]) pairs
A=:(0 2 -.@:-: $)&>Filter<@fangs"0]1000+i.1e4
B=:(0 2 -.@:-: $)&>Filter<@fangs"0]100000+i.25501
(,: */@:{.&.>)A,B
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐
│21 60│15 93│35 41│30 51│21 87│27 81│80 86│201 510│260 401│210 501│204 516│150 705│135 801│158 701│152 761│161 725│167 701│141 840│201 600│231 534│281 443│152 824│231 543│246 510│251 500│
│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │204 615│ │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤
│1260 │1395 │1435 │1530 │1827 │2187 │6880 │102510 │104260 │105210 │105264 │105750 │108135 │110758 │115672 │116725 │117067 │118440 │120600 │123354 │124483 │125248 │125433 │125460 │125500 │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘
<@fangs"0[] 16758243290880 24959017348650 14593825548650
┌───────────────┬───────────────┬──┐
│2817360 5948208│4230765 5899410│ │
│2751840 6089832│4129587 6043950│ │
│2123856 7890480│4125870 6049395│ │
│1982736 8452080│2949705 8461530│ │
│ │2947050 8469153│ │
└───────────────┴───────────────┴──┘
fangs f. NB. <laugh>
((10&(#.^:_1)@:[ -:&(/:~) ,&(10&(#.^:_1))/@:])"0 1 # ]) ((% ,. ]) (#~ (0 < [: # :[: 0 -.~ 10&|)"1)@:(((> <.@:%:)~ # ]) (((-: :[:@:(# :[:)@:(10&(#.^:_1))@:[ = # :[:@:(10&(#.^:_1))&>@:]) # ]) ([: ([: /:~ [: */"1 ([: x: [) ^"1 [: > [: , [: { [: <@:i.@>: ])/ __ q: ]))))
|
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Io | Io | printAll := method(call message arguments foreach(println)) |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #J | J | A=:2
B=:3
C=:5
sum=:+/
sum 1,A,B,4,C
15 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Rust | Rust | use std::mem;
fn main() {
// Specify type
assert_eq!(4, mem::size_of::<i32>());
// Provide a value
let arr: [u16; 3] = [1, 2, 3];
assert_eq!(6, mem::size_of_val(&arr));
}
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Scala | Scala | def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8
val primitives: List[(Any, Long)] =
List((Byte, Byte.MaxValue),
(Short, Short.MaxValue),
(Int, Int.MaxValue),
(Long, Long.MaxValue))
primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes")) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Swift | Swift | sizeofValue(x) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Tcl | Tcl | string bytelength $var |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #PicoLisp | PicoLisp | (de add (A B)
(mapcar + A B) )
(de sub (A B)
(mapcar - A B) )
(de mul (A B)
(mapcar '((X) (* X B)) A) )
(de div (A B)
(mapcar '((X) (*/ X B)) A) )
(let (X (5 7) Y (2 3))
(println (add X Y))
(println (sub X Y))
(println (mul X 11))
(println (div X 2)) ) |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #PL.2FI | PL/I | *process source attributes xref or(!);
vectors: Proc Options(main);
Dcl (v,w,x,y,z) Dec Float(9) Complex;
real(v)=12; imag(v)=-3; Put Edit(pp(v))(Skip,a);
real(v)=6-1; imag(v)=4-1; Put Edit(pp(v))(Skip,a);
real(v)=2*cosd(45);
imag(v)=2*sind(45); Put Edit(pp(v))(Skip,a);
w=v+v; Put Edit(pp(w))(Skip,a);
x=v-w; Put Edit(pp(x))(Skip,a);
y=x*3; Put Edit(pp(y))(Skip,a);
z=x/.1; Put Edit(pp(z))(Skip,a);
pp: Proc(c) Returns(Char(50) Var);
Dcl c Dec Float(9) Complex;
Dcl res Char(50) Var;
Put String(res) Edit('[',real(c),',',imag(c),']')
(3(a,f(9,5)));
Return(res);
End;
End; |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #PureBasic | PureBasic | Procedure prepString(text.s, Array letters(1))
;convert characters to an ordinal (0-25) and remove non-alphabetic characters,
;returns dimension size of result array letters()
Protected *letter.Character, index
Dim letters(Len(text))
text = UCase(text)
*letter = @text
While *letter\c
Select *letter\c
Case 'A' To 'Z'
letters(index) = *letter\c - 65
index + 1
EndSelect
*letter + SizeOf(Character)
Wend
If index > 0
Redim letters(index - 1)
EndIf
ProcedureReturn index - 1
EndProcedure
Procedure.s VC_encrypt(text.s, keyText.s, reverse = 0)
;if reverse <> 0 then reverse the key (decrypt)
Protected *letter.Character
Dim text(0)
Dim keyText(0)
If prepString(text, text()) < 0 Or prepString(keyText, keyText()) < 0: ProcedureReturn: EndIf ;exit, nothing to work with
Protected i, keyLength = ArraySize(keyText())
If reverse
For i = 0 To keyLength
keyText(i) = 26 - keyText(i)
Next
EndIf
Protected textLength = ArraySize(text()) ;zero-based length
Protected result.s = Space(textLength + 1), *resultLetter.Character
keyLength + 1 ;convert from zero-based to one-based count
*resultLetter = @result
For i = 0 To textLength
*resultLetter\c = ((text(i) + keyText(i % keyLength)) % 26) + 65
*resultLetter + SizeOf(Character)
Next
ProcedureReturn result
EndProcedure
Procedure.s VC_decrypt(cypherText.s, keyText.s)
ProcedureReturn VC_encrypt(cypherText, keyText.s, 1)
EndProcedure
If OpenConsole()
Define VignereCipher.s, plainText.s, encryptedText.s, decryptedText.s
VignereCipher.s = "VIGNERECIPHER"
plainText = "The quick brown fox jumped over the lazy dogs.": PrintN(RSet("Plain text = ", 17) + #DQUOTE$ + plainText + #DQUOTE$)
encryptedText = VC_encrypt(plainText, VignereCipher): PrintN(RSet("Encrypted text = ", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)
decryptedText = VC_decrypt(encryptedText, VignereCipher): PrintN(RSet("Decrypted text = ", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Wren | Wren | import "io" for Directory, File
import "/pattern" for Pattern
import "/sort" for Sort
var walk // recursive function
walk = Fn.new { |dir, pattern, found|
if (!Directory.exists(dir)) Fiber.abort("Directory %(dir) does not exist.")
var files = Directory.list(dir)
for (f in files) {
var path = dir + "/%(f)"
if (File.exists(path)) { // it's a file not a directory
if (pattern.isMatch(f)) found.add(f)
} else {
walk.call(path, pattern, found)
}
}
}
// get all C header files beginning with 'va' or 'vf'
var p = Pattern.new("v[a|f]+0^..h", Pattern.whole)
var found = []
walk.call("/usr/include", p, found)
Sort.quick(found)
for (f in found) System.print(f) |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Crystal | Crystal | class Vector
property x, y, z
def initialize(@x : Int64, @y : Int64, @z : Int64) end
def dot_product(other : Vector)
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
end
def cross_product(other : Vector)
Vector.new(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
end
def scalar_triple_product(b : Vector, c : Vector)
self.dot_product(b.cross_product(c))
end
def vector_triple_product(b : Vector, c : Vector)
self.cross_product(b.cross_product(c))
end
def to_s
"(#{self.x}, #{self.y}, #{self.z})\n"
end
end
a = Vector.new(3, 4, 5)
b = Vector.new(4, 3, 5)
c = Vector.new(-5, -12, -13)
puts "a = #{a.to_s}"
puts "b = #{b.to_s}"
puts "c = #{c.to_s}"
puts "a dot b = #{a.dot_product b}"
puts "a cross b = #{a.cross_product(b).to_s}"
puts "a dot (b cross c) = #{a.scalar_triple_product b, c}"
puts "a cross (b cross c) = #{a.vector_triple_product(b, c).to_s}" |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #FreeBASIC | FreeBASIC | ' version 27-10-2016
' compile with: fbc -s console
#Ifndef TRUE ' define true and false for older freebasic versions
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function luhntest(cardnr As String) As Long
cardnr = Trim(cardnr) ' remove spaces
Dim As String reverse_nr = cardnr
Dim As Long i, j, s1, s2, l = Len(cardnr) -1
' reverse string
For i = 0 To l
reverse_nr[i] = cardnr[l - i]
Next
' sum odd numbers
For i = 0 To l Step 2
s1 = s1 + (reverse_nr[i] - Asc("0"))
Next
' sum even numbers
For i = 1 To l Step 2
j = reverse_nr[i] - Asc("0")
j = j * 2
If j > 9 Then j = j Mod 10 +1
s2 = s2 + j
Next
If (s1 + s2) Mod 10 = 0 Then
Return TRUE
Else
Return FALSE
End If
End Function
' ------=< MAIN >=-----
Dim As String test_str
Dim As String test_set(1 To ...) = { "US0378331005", "US0373831005", _
"U50378331005", "US03378331005", "AU0000XVGZA3", _
"AU0000VXGZA3", "FR0000988040" }
Dim As Long i, l, n, x
For i = 1 To UBound(test_set)
test_str = ""
l = Len(test_set(i))
If l <> 12 Then
Print test_set(i), "Invalid, length <> 12 char."
Continue For
End If
If test_set(i)[0] < Asc("A") Or test_set(i)[1] < Asc("A") Then
Print test_set(i), "Invalid, number needs to start with 2 characters"
Continue For
End If
For n = 0 To l -1
x = test_set(i)[n] - Asc("0")
' if test_set(i)[i] is a letter we to correct for that
If x > 9 Then x = x -7
If x < 10 Then
test_str = test_str + Str(x)
Else ' two digest number
test_str = test_str + Str(x \ 10) + Str(x Mod 10)
End If
Next
Print test_set(i), IIf(luhntest(test_str) = TRUE, "Valid","Invalid, checksum error")
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Erlang | Erlang |
-module( van_der_corput ).
-export( [sequence/1, sequence/2, task/0] ).
sequence( N ) -> sequence( N, 2 ).
sequence( 0, _Base ) -> 0.0;
sequence( N, Base ) -> erlang:list_to_float( "0." ++ lists:flatten([erlang:integer_to_list(X) || X <- sequence_loop(N, Base)]) ).
task() -> [task(X) || X <- lists:seq(2, 5)].
sequence_loop( 0, _Base ) -> [];
sequence_loop( N, Base ) ->
New_n = N div Base,
Digit = N rem Base,
[Digit | sequence_loop( New_n, Base )].
task( Base ) ->
io:fwrite( "Base ~p:", [Base] ),
[io:fwrite( " ~p", [sequence(X, Base)] ) || X <- lists:seq(0, 9)],
io:fwrite( "~n" ).
|
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #Arturo | Arturo | print decode.url "http%3A%2F%2Ffoo%20bar%2F"
print decode.url "google.com/search?q=%60Abdu%27l-Bah%C3%A1" |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #AutoHotkey | AutoHotkey | encURL := "http%3A%2F%2Ffoo%20bar%2F"
SetFormat, Integer, hex
Loop Parse, encURL
If A_LoopField = `%
reading := 2, read := ""
else if reading
{
read .= A_LoopField, --reading
if not reading
out .= Chr("0x" . read)
}
else out .= A_LoopField
MsgBox % out ; http://foo bar/
|
http://rosettacode.org/wiki/Update_a_configuration_file | Update a configuration file | We have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.
# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# How many bananas we have
NUMBEROFBANANAS 48
The task is to manipulate the configuration file as follows:
Disable the needspeeling option (using a semicolon prefix)
Enable the seedsremoved option by removing the semicolon and any leading whitespace
Change the numberofbananas parameter to 1024
Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000
Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case.
Options should always be disabled by prefixing them with a semicolon.
Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file.
If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry.
For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.)
The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons).
Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single
space, and any non-ASCII extended characters, tabs characters, or control codes
(other than end of line markers), should also be removed.
Related tasks
Read a configuration file
| #11l | 11l | T.enum EntryType
EMPTY
ENABLED
DISABLED
COMMENT
IGNORE
T Entry
EntryType etype
String name
String value
F (etype, name = ‘’, value = ‘’)
.etype = etype
.name = name
.value = value
T Config
String path
[Entry] entries
F (path)
.path = path
L(=line) File(path).read_lines()
line = line.ltrim(‘ ’)
I line.empty
.entries.append(Entry(EntryType.EMPTY))
E I line[0] == ‘#’
.entries.append(Entry(EntryType.COMMENT, line))
E
line = line.replace(re:‘[^a-zA-Z0-9\x20;]’, ‘’)
V m = re:‘^(;*)\s*([a-zA-Z0-9]+)\s*([a-zA-Z0-9]*)’.search(line)
I m & !m.group(2).empty
V t = I m.group(1).empty {EntryType.ENABLED} E EntryType.DISABLED
.addOption(m.group(2), m.group(3), t)
F enableOption(name)
Int? i = .getOptionIndex(name)
I i != N
.entries[i].etype = EntryType.ENABLED
F disableOption(name)
Int? i = .getOptionIndex(name)
I i != N
.entries[i].etype = EntryType.DISABLED
F setOption(name, value)
Int? i = .getOptionIndex(name)
I i != N
.entries[i].value = value
F addOption(name, val, t = EntryType.ENABLED)
.entries.append(Entry(t, name.uppercase(), val))
F removeOption(name)
Int? i = .getOptionIndex(name)
I i != N
.entries[i].etype = EntryType.IGNORE
F getOptionIndex(name) -> Int?
L(e) .entries
I e.etype !C (EntryType.ENABLED, EntryType.DISABLED)
L.continue
I e.name == name.uppercase()
R L.index
R N
F store()
V f = File(.path, ‘w’)
L(e) .entries
I e.etype == EMPTY
f.write("\n")
E I e.etype == ENABLED
f.write("#. #.\n".format(e.name, e.value))
E I e.etype == DISABLED
f.write("; #. #.\n".format(e.name, e.value))
E I e.etype == COMMENT
f.write(e.name"\n")
V cfg = Config(‘config.txt’)
cfg.enableOption(‘seedsremoved’)
cfg.disableOption(‘needspeeling’)
cfg.setOption(‘numberofbananas’, ‘1024’)
cfg.addOption(‘numberofstrawberries’, ‘62000’)
cfg.store() |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #APL | APL | str←⍞
int←⎕ |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program inputText.s */
/* Constantes */
.equ BUFFERSIZE, 100
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessDeb: .asciz "Enter text : \n"
szMessNum: .asciz "Enter number : \n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
ldr r0,iAdrszMessDeb
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7, #READ @ request to read datas
swi 0 @ call system
ldr r1,iAdrsBuffer @ buffer address
mov r2,#0 @ end of string
strb r2,[r1,r0] @ store byte at the end of input string (r0 contains number of characters)
ldr r0,iAdrsBuffer @ buffer address
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszMessNum
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7, #READ @ request to read datas
swi 0 @ call system
ldr r1,iAdrsBuffer @ buffer address
mov r2,#0 @ end of string
strb r2,[r1,r0] @ store byte at the end of input string (r0
@
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD @ conversion string in number in r0
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
iAdrszMessDeb: .int szMessDeb
iAdrszMessNum: .int szMessNum
iAdrsBuffer: .int sBuffer
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* 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 */
/******************************************************************/
/* Convert a string to a number stored in a registry */
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number */
conversionAtoD:
push {fp,lr} @ save 2 registers
push {r1-r7} @ save others registers
mov r1,#0
mov r2,#10 @ factor
mov r3,#0 @ counter
mov r4,r0 @ save address string -> r4
mov r6,#0 @ positive sign by default
mov r0,#0 @ initialization to 0
1: /* early space elimination loop */
ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position
cmp r5,#0 @ end of string -> end routine
beq 100f
cmp r5,#0x0A @ end of string -> end routine
beq 100f
cmp r5,#' ' @ space ?
addeq r3,r3,#1 @ yes we loop by moving one byte
beq 1b
cmp r5,#'-' @ first character is -
moveq r6,#1 @ 1 -> r6
beq 3f @ then move on to the next position
2: /* beginning of digit processing loop */
cmp r5,#'0' @ character is not a number
blt 3f
cmp r5,#'9' @ character is not a number
bgt 3f
/* character is a number */
sub r5,#48
ldr r1,iMaxi @ check the overflow of the register
cmp r0,r1
bgt 99f @ overflow error
mul r0,r2,r0 @ multiply par factor 10
add r0,r5 @ add to r0
3:
add r3,r3,#1 @ advance to the next position
ldrb r5,[r4,r3] @ load byte
cmp r5,#0 @ end of string -> end routine
beq 4f
cmp r5,#0x0A @ end of string -> end routine
beq 4f
b 2b @ loop
4:
cmp r6,#1 @ test r6 for sign
moveq r1,#-1
muleq r0,r1,r0 @ if negatif, multiply par -1
b 100f
99: /* overflow error */
ldr r0,=szMessErrDep
bl affichageMess
mov r0,#0 @ return zero if error
100:
pop {r1-r7} @ restaur other registers
pop {fp,lr} @ restaur 2 registers
bx lr @return procedure
/* constante program */
iMaxi: .int 1073741824
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"
|
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Ada | Ada | with Gtk.Button; use Gtk.Button;
with Gtk.GEntry; use Gtk.GEntry;
with Gtk.Label; use Gtk.Label;
with Gtk.Window; use Gtk.Window;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Table; use Gtk.Table;
with Gtk.Handlers;
with Gtk.Main;
procedure Graphic_Input is
Window : Gtk_Window;
Grid : Gtk_Tnetable;
Label : Gtk_Label;
Message : Gtk_Label;
Edit : Gtk_GEntry;
Button : Gtk_Button;
package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
package Return_Handlers is
new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
function Delete_Event (Widget : access Gtk_Widget_Record'Class)
return Boolean is
begin
return False;
end Delete_Event;
procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
begin
Gtk.Main.Main_Quit;
end Destroy;
procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
begin
if Get_Text (Label) = "Enter integer:" then
Set_Text (Message, "Entered:" & Integer'Image (Integer'Value (Get_Text (Edit))));
Set_Sensitive (Button, False);
else
Set_Text (Message, "Entered:" & Get_Text (Edit));
Set_Text (Label, "Enter integer:");
end if;
exception
when Constraint_Error =>
Set_Text (Message, "Error integer input");
end Clicked;
begin
Gtk.Main.Init;
Gtk.Window.Gtk_New (Window);
Gtk_New (Grid, 2, 3, False);
Add (Window, Grid);
Gtk_New (Label, "Enter string:");
Attach (Grid, Label, 0, 1, 0, 1);
Gtk_New (Edit);
Attach (Grid, Edit, 1, 2, 0, 1);
Gtk_New (Button, "OK");
Attach (Grid, Button, 2, 3, 0, 1);
Gtk_New (Message);
Attach (Grid, Message, 0, 3, 1, 2);
Return_Handlers.Connect
( Window,
"delete_event",
Return_Handlers.To_Marshaller (Delete_Event'Access)
);
Handlers.Connect
( Window,
"destroy",
Handlers.To_Marshaller (Destroy'Access)
);
Handlers.Connect
( Button,
"clicked",
Handlers.To_Marshaller (Clicked'Access)
);
Show_All (Grid);
Show (Window);
Gtk.Main.Main;
end Graphic_Input; |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #ATS | ATS | (*
UTF-8 encoding and decoding in ATS2.
This is adapted from library code I wrote long ago and actually
handles the original 1-to-6-byte encoding, as well. Valid Unicode
requires only 1 to 4 bytes.
What is remarkable about the following rather lengthy code is its
use of proofs of what is and what is not valid UTF-8. Much of what
follows is proofs rather than executable code. It seemed simpler to
"mostly copy" my old code, than to try to pare that code down to a
minimum that still demonstrated some of what makes ATS different
from all but a few (if any) other languages.
*)
#define ATS_EXTERN_PREFIX "utf8_encoding_"
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
(* A variant of ‘andalso’, with dependent types. *)
fn {}
andalso1 {b1, b2 : bool} (b1 : bool b1, b2 : bool b2) :<>
[b3 : bool | b3 == (b1 && b2)] bool b3 =
if b1 then
b2
else
false
infixl (&&) &&&
macdef &&& = andalso1
(*###################### C CODE ####################################*)
%{^
_Static_assert (4 <= sizeof (int),
"sizeof(int) must equal at least 4");
#define utf8_encoding_2_entries(v) \
(v), (v)
#define utf8_encoding_4_entries(v) \
utf8_encoding_2_entries (v), \
utf8_encoding_2_entries (v)
#define utf8_encoding_8_entries(v) \
utf8_encoding_4_entries (v), \
utf8_encoding_4_entries (v)
#define utf8_encoding_16_entries(v) \
utf8_encoding_8_entries (v), \
utf8_encoding_8_entries (v)
#define utf8_encoding_32_entries(v) \
utf8_encoding_16_entries (v), \
utf8_encoding_16_entries (v)
#define utf8_encoding_64_entries(v) \
utf8_encoding_32_entries (v), \
utf8_encoding_32_entries (v)
#define utf8_encoding_128_entries(v) \
utf8_encoding_64_entries (v), \
utf8_encoding_64_entries (v)
static const atstype_int8 utf8_encoding_extended_utf8_lengths__[256] = {
utf8_encoding_128_entries (1),
utf8_encoding_64_entries (-1),
utf8_encoding_32_entries (2),
utf8_encoding_16_entries (3),
utf8_encoding_8_entries (4),
utf8_encoding_4_entries (5),
utf8_encoding_2_entries (6),
utf8_encoding_2_entries (-1)
};
static const atstype_int8 utf8_encoding_utf8_lengths__[256] = {
utf8_encoding_128_entries (1),
utf8_encoding_64_entries (-1),
utf8_encoding_32_entries (2),
utf8_encoding_16_entries (3),
utf8_encoding_8_entries (4),
utf8_encoding_4_entries (-1),
utf8_encoding_2_entries (-1),
utf8_encoding_2_entries (-1)
};
#define utf8_encoding_extended_utf8_character_length(c) \
(utf8_encoding_extended_utf8_lengths__[(atstype_uint8) (c)])
#define utf8_encoding_utf8_character_length(c) \
(utf8_encoding_utf8_lengths__[(atstype_uint8) (c)])
%}
(*###################### INTERFACE #################################*)
stadef
is_valid_unicode_code_point (u : int) : bool =
(0x0 <= u && u < 0xD800) || (0xE000 <= u && u <= 0x10FFFF)
extern fun {}
is_valid_unicode_code_point :
{u : int} int u -<>
[b : bool | b == is_valid_unicode_code_point u]
bool b
(*------------------------------------------------------------------*)
stadef
is_extended_utf8_1byte_first_byte (c0 : int) : bool =
0x00 <= c0 && c0 <= 0x7F
stadef
is_extended_utf8_2byte_first_byte (c0 : int) : bool =
0xC0 <= c0 && c0 <= 0xDF
stadef
is_extended_utf8_3byte_first_byte (c0 : int) : bool =
0xE0 <= c0 && c0 <= 0xEF
stadef
is_extended_utf8_4byte_first_byte (c0 : int) : bool =
0xF0 <= c0 && c0 <= 0xF7
stadef
is_extended_utf8_5byte_first_byte (c0 : int) : bool =
0xF8 <= c0 && c0 <= 0xFB
stadef
is_extended_utf8_6byte_first_byte (c0 : int) : bool =
0xFC <= c0 && c0 <= 0xFD
stadef
extended_utf8_character_length (c0 : int) : int =
ifint (is_extended_utf8_1byte_first_byte c0, 1,
ifint (is_extended_utf8_2byte_first_byte c0, 2,
ifint (is_extended_utf8_3byte_first_byte c0, 3,
ifint (is_extended_utf8_4byte_first_byte c0, 4,
ifint (is_extended_utf8_5byte_first_byte c0, 5,
ifint (is_extended_utf8_6byte_first_byte c0, 6, ~1))))))
stadef
extended_utf8_char_length_relation (c0 : int, n : int) : bool =
(n == 1 && is_extended_utf8_1byte_first_byte c0) ||
(n == 2 && is_extended_utf8_2byte_first_byte c0) ||
(n == 3 && is_extended_utf8_3byte_first_byte c0) ||
(n == 4 && is_extended_utf8_4byte_first_byte c0) ||
(n == 5 && is_extended_utf8_5byte_first_byte c0) ||
(n == 6 && is_extended_utf8_6byte_first_byte c0)
extern prfun
extended_utf8_char_length_relation_to_length :
{c0 : int}
{n : int | extended_utf8_char_length_relation (c0, n) ||
(n == ~1 && ((c0 < 0x00) ||
(0x7F < c0 && c0 < 0xC0) ||
(0xFD < c0)))}
() -<prf> [n == extended_utf8_character_length c0] void
extern prfun
extended_utf8_char_length_to_length_relation :
{c0 : int}
{n : int | n == extended_utf8_character_length c0}
() -<prf>
[extended_utf8_char_length_relation (c0, n) ||
(n == ~1 && ((c0 < 0x00) || (0x7F < c0 && c0 < 0xC0) || (0xFD < c0)))]
void
// extended_utf8_character_length:
//
// Return value = 1, 2, 3, or 4 indicates that there may be a valid
// UTF-8 character, of the given length. It may also be a `valid'
// overlong sequence. Otherwise there definitely is not a valid
// character of any sort starting with the given byte. Return
// value = 5 or 6 indicates the possible start of an `extended
// UTF-8' character of the given length, including code points up
// to 0xffffffff. Return value = ~1 means the byte is not the
// start of a valid sequence.
extern fun
extended_utf8_character_length :
{c0 : int | 0x00 <= c0; c0 <= 0xFF} int c0 -<>
[n : int | n == extended_utf8_character_length c0] int n = "mac#%"
stadef
utf8_character_length (c0 : int) : int =
ifint (is_extended_utf8_1byte_first_byte c0, 1,
ifint (is_extended_utf8_2byte_first_byte c0, 2,
ifint (is_extended_utf8_3byte_first_byte c0, 3,
ifint (is_extended_utf8_4byte_first_byte c0, 4, ~1))))
stadef
utf8_char_length_relation (c0 : int, n : int) : bool =
(n == 1 && is_extended_utf8_1byte_first_byte c0) ||
(n == 2 && is_extended_utf8_2byte_first_byte c0) ||
(n == 3 && is_extended_utf8_3byte_first_byte c0) ||
(n == 4 && is_extended_utf8_4byte_first_byte c0)
extern prfun
utf8_char_length_relation_to_length :
{c0 : int}
{n : int | utf8_char_length_relation (c0, n) ||
(n == ~1 && ((c0 < 0x00) ||
(0x7F < c0 && c0 < 0xC0) ||
(0xF7 < c0)))}
() -<prf> [n == utf8_character_length c0] void
extern prfun
utf8_char_length_to_length_relation :
{c0 : int}
{n : int | n == utf8_character_length c0}
() -<prf>
[utf8_char_length_relation (c0, n) ||
(n == ~1 && ((c0 < 0x00) || (0x7F < c0 && c0 < 0xC0) || (0xF7 < c0)))]
void
extern fun
utf8_character_length :
{c0 : int | 0x00 <= c0; c0 <= 0xFF} int c0 -<>
[n : int | n == utf8_character_length c0] int n = "mac#%"
(*------------------------------------------------------------------*)
stadef
is_valid_utf8_continuation_byte (c : int) : bool =
0x80 <= c && c <= 0xBF
stadef
is_invalid_utf8_continuation_byte (c : int) : bool =
c < 0x80 || 0xBF < c
extern fun {}
is_valid_utf8_continuation_byte :
{c : int} int c -<>
[b : bool | b == is_valid_utf8_continuation_byte c] bool b
(*------------------------------------------------------------------*)
stadef
extended_utf8_char_1byte_decoding (c0 : int) : int =
c0
stadef
extended_utf8_char_2byte_decoding (c0 : int, c1 : int) : int =
64 * (c0 - 0xC0) + (c1 - 0x80)
stadef
extended_utf8_char_3byte_decoding (c0 : int, c1 : int, c2 : int) : int =
64 * 64 * (c0 - 0xE0) + 64 * (c1 - 0x80) + (c2 - 0x80)
stadef
extended_utf8_char_4byte_decoding (c0 : int, c1 : int, c2 : int,
c3 : int) : int =
64 * 64 * 64 * (c0 - 0xF0) + 64 * 64 * (c1 - 0x80) +
64 * (c2 - 0x80) + (c3 - 0x80)
stadef
extended_utf8_char_5byte_decoding (c0 : int, c1 : int, c2 : int,
c3 : int, c4 : int) : int =
64 * 64 * 64 * 64 * (c0 - 0xF8) + 64 * 64 * 64 * (c1 - 0x80) +
64 * 64 * (c2 - 0x80) + 64 * (c3 - 0x80) + (c4 - 0x80)
stadef
extended_utf8_char_6byte_decoding (c0 : int, c1 : int, c2 : int,
c3 : int, c4 : int, c5 : int) : int =
64 * 64 * 64 * 64 * 64 * (c0 - 0xFC) + 64 * 64 * 64 * 64 * (c1 - 0x80) +
64 * 64 * 64 * (c2 - 0x80) + 64 * 64 * (c3 - 0x80) +
64 * (c4 - 0x80) + (c5 - 0x80)
dataprop EXTENDED_UTF8_CHAR (length : int, u : int, c0 : int, c1 : int,
c2 : int, c3 : int, c4 : int, c5 : int) =
| {u, c0 : int |
0 <= u; u <= 0x7F;
is_extended_utf8_1byte_first_byte c0;
u == extended_utf8_char_1byte_decoding (c0)}
EXTENDED_UTF8_CHAR_1byte (1, u, c0, ~1, ~1, ~1, ~1, ~1)
//
| {u, c0, c1 : int |
0 <= u; u <= 0x7FF;
is_extended_utf8_2byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
u == extended_utf8_char_2byte_decoding (c0, c1)}
EXTENDED_UTF8_CHAR_2byte (2, u, c0, c1, ~1, ~1, ~1, ~1)
//
| {u, c0, c1, c2 : int |
0 <= u; u <= 0xFFFF;
is_extended_utf8_3byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
u == extended_utf8_char_3byte_decoding (c0, c1, c2)}
EXTENDED_UTF8_CHAR_3byte (3, u, c0, c1, c2, ~1, ~1, ~1)
//
| {u, c0, c1, c2, c3 : int |
0 <= u; u <= 0x1FFFFF;
is_extended_utf8_4byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
u == extended_utf8_char_4byte_decoding (c0, c1, c2, c3)}
EXTENDED_UTF8_CHAR_4byte (4, u, c0, c1, c2, c3, ~1, ~1)
//
| {u, c0, c1, c2, c3, c4 : int |
0 <= u; u <= 0x3FFFFFF;
is_extended_utf8_5byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
is_valid_utf8_continuation_byte c4;
u == extended_utf8_char_5byte_decoding (c0, c1, c2, c3, c4)}
EXTENDED_UTF8_CHAR_5byte (5, u, c0, c1, c2, c3, c4, ~1)
//
| {u, c0, c1, c2, c3, c4, c5 : int |
0 <= u; u <= 0x7FFFFFFF;
is_extended_utf8_6byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
is_valid_utf8_continuation_byte c4;
is_valid_utf8_continuation_byte c5;
u == extended_utf8_char_6byte_decoding (c0, c1, c2, c3, c4, c5)}
EXTENDED_UTF8_CHAR_6byte (6, u, c0, c1, c2, c3, c4, c5)
extern prfun
decode_extended_utf8_istot :
{n : int | 1 <= n; n <= 6}
{c0, c1, c2, c3, c4, c5 : int |
extended_utf8_char_length_relation (c0, n);
n <= 1 || is_valid_utf8_continuation_byte c1;
n <= 2 || is_valid_utf8_continuation_byte c2;
n <= 3 || is_valid_utf8_continuation_byte c3;
n <= 4 || is_valid_utf8_continuation_byte c4;
n <= 5 || is_valid_utf8_continuation_byte c5;
1 < n || c1 == ~1;
2 < n || c2 == ~1;
3 < n || c3 == ~1;
4 < n || c4 == ~1;
5 < n || c5 == ~1}
() -<prf> [u : int] EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5)
extern prfun
decode_extended_utf8_isfun :
{na : int | 1 <= na; na <= 6}
{ua : int}
{c0a, c1a, c2a, c3a, c4a, c5a : int}
{nb : int | nb == na}
{ub : int}
{c0b, c1b, c2b, c3b, c4b, c5b : int |
c0b == c0a;
c1b == c1a;
c2b == c2a;
c3b == c3a;
c4b == c4a;
c5b == c5a}
(EXTENDED_UTF8_CHAR (na, ua, c0a, c1a, c2a, c3a, c4a, c5a),
EXTENDED_UTF8_CHAR (nb, ub, c0b, c1b, c2b, c3b, c4b, c5b)) -<prf>
[ua == ub] void
extern prfun
lemma_extended_utf8_char_length :
{n : int} {u : int} {c0, c1, c2, c3, c4, c5 : int}
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) -<prf>
[n == extended_utf8_character_length c0] void
extern fun {}
decode_extended_utf8_1byte :
{c0 : int | 0x00 <= c0; c0 <= 0x7F} int c0 -<>
[u : int] (EXTENDED_UTF8_CHAR (1, u, c0, ~1, ~1, ~1, ~1, ~1) | int u)
extern fun {}
decode_extended_utf8_2byte :
{c0, c1 : int | 0xC0 <= c0; c0 <= 0xDF;
is_valid_utf8_continuation_byte c1}
(int c0, int c1) -<>
[u : int] (EXTENDED_UTF8_CHAR (2, u, c0, c1, ~1, ~1, ~1, ~1) | int u)
extern fun {}
decode_extended_utf8_3byte :
{c0, c1, c2 : int | 0xE0 <= c0; c0 <= 0xEF;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2}
(int c0, int c1, int c2) -<>
[u : int] (EXTENDED_UTF8_CHAR (3, u, c0, c1, c2, ~1, ~1, ~1) | int u)
extern fun {}
decode_extended_utf8_4byte :
{c0, c1, c2, c3 : int | 0xF0 <= c0; c0 <= 0xF7;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3}
(int c0, int c1, int c2, int c3) -<>
[u : int] (EXTENDED_UTF8_CHAR (4, u, c0, c1, c2, c3, ~1, ~1) | int u)
extern fun {}
decode_extended_utf8_5byte :
{c0, c1, c2, c3, c4 : int | 0xF8 <= c0; c0 <= 0xFB;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
is_valid_utf8_continuation_byte c4}
(int c0, int c1, int c2, int c3, int c4) -<>
[u : int] (EXTENDED_UTF8_CHAR (5, u, c0, c1, c2, c3, c4, ~1) | int u)
extern fun {}
decode_extended_utf8_6byte :
{c0, c1, c2, c3, c4, c5 : int | 0xFC <= c0; c0 <= 0xFD;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
is_valid_utf8_continuation_byte c4;
is_valid_utf8_continuation_byte c5}
(int c0, int c1, int c2, int c3, int c4, int c5) -<>
[u : int]
(EXTENDED_UTF8_CHAR (6, u, c0, c1, c2, c3, c4, c5) | int u)
(*------------------------------------------------------------------*)
stadef extended_utf8_shortest_length (u : int) =
ifint (u < 0, ~1,
ifint (u <= 0x7F, 1,
ifint (u <= 0x7FF, 2,
ifint (u <= 0xFFFF, 3,
ifint (u <= 0x1FFFFF, 4,
ifint (u <= 0x3FFFFFF, 5,
ifint (u <= 0x7FFFFFFF, 6, ~1)))))))
dataprop EXTENDED_UTF8_SHORTEST (length : int, u : int, c0 : int, c1 : int,
c2 : int, c3 : int, c4 : int, c5 : int) =
| {u, c0 : int |
0 <= u; u <= 0x7F;
c0 == u}
EXTENDED_UTF8_SHORTEST_1byte (1, u, c0, ~1, ~1, ~1, ~1, ~1) of
EXTENDED_UTF8_CHAR (1, u, c0, ~1, ~1, ~1, ~1, ~1)
//
| {u, c0, c1 : int |
0x7F < u; u <= 0x7FF;
c0 == 0xC0 + (u \ndiv 64);
c1 == 0x80 + (u \nmod 64)}
EXTENDED_UTF8_SHORTEST_2byte (2, u, c0, c1, ~1, ~1, ~1, ~1) of
EXTENDED_UTF8_CHAR (2, u, c0, c1, ~1, ~1, ~1, ~1)
//
| {u, c0, c1, c2 : int |
0x7FF < u; u <= 0xFFFF;
c0 == 0xE0 + (u \ndiv (64 * 64));
c1 == 0x80 + ((u \ndiv 64) \nmod 64);
c2 == 0x80 + (u \nmod 64)}
EXTENDED_UTF8_SHORTEST_3byte (3, u, c0, c1, c2, ~1, ~1, ~1) of
EXTENDED_UTF8_CHAR (3, u, c0, c1, c2, ~1, ~1, ~1)
//
| {u, c0, c1, c2, c3 : int |
0xFFFF < u; u <= 0x1FFFFF;
c0 == 0xF0 + (u \ndiv (64 * 64 * 64));
c1 == 0x80 + ((u \ndiv (64 * 64)) \nmod 64);
c2 == 0x80 + ((u \ndiv 64) \nmod 64);
c3 == 0x80 + (u \nmod 64)}
EXTENDED_UTF8_SHORTEST_4byte (4, u, c0, c1, c2, c3, ~1, ~1) of
EXTENDED_UTF8_CHAR (4, u, c0, c1, c2, c3, ~1, ~1)
//
| {u, c0, c1, c2, c3, c4 : int |
0x1FFFFF < u; u <= 0x3FFFFFF;
c0 == 0xF8 + (u \ndiv (64 * 64 * 64 * 64));
c1 == 0x80 + ((u \ndiv (64 * 64 * 64)) \nmod 64);
c2 == 0x80 + ((u \ndiv (64 * 64)) \nmod 64);
c3 == 0x80 + ((u \ndiv 64) \nmod 64);
c4 == 0x80 + (u \nmod 64)}
EXTENDED_UTF8_SHORTEST_5byte (5, u, c0, c1, c2, c3, c4, ~1) of
EXTENDED_UTF8_CHAR (5, u, c0, c1, c2, c3, c4, ~1)
//
| {u, c0, c1, c2, c3, c4, c5 : int |
0x3FFFFFF < u; u <= 0x7FFFFFFF;
c0 == 0xFC + (u \ndiv (64 * 64 * 64 * 64 * 64));
c1 == 0x80 + ((u \ndiv (64 * 64 * 64 * 64)) \nmod 64);
c2 == 0x80 + ((u \ndiv (64 * 64 * 64)) \nmod 64);
c3 == 0x80 + ((u \ndiv (64 * 64)) \nmod 64);
c4 == 0x80 + ((u \ndiv 64) \nmod 64);
c5 == 0x80 + (u \nmod 64)}
EXTENDED_UTF8_SHORTEST_6byte (6, u, c0, c1, c2, c3, c4, c5) of
EXTENDED_UTF8_CHAR (6, u, c0, c1, c2, c3, c4, c5)
extern prfun
extended_utf8_shortest_is_char :
{n : int} {u : int} {c0, c1, c2, c3, c4, c5 : int}
EXTENDED_UTF8_SHORTEST (n, u, c0, c1, c2, c3, c4, c5) -<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5)
extern prfun
lemma_extended_utf8_shortest_length :
{n : int} {u : int} {c0, c1, c2, c3, c4, c5 : int}
EXTENDED_UTF8_SHORTEST (n, u, c0, c1, c2, c3, c4, c5) -<prf>
[n == extended_utf8_shortest_length u] void
extern fun {}
encode_extended_utf8_character :
{u : nat | u <= 0x7FFFFFFF}
int u -<>
[n : int] [c0, c1, c2, c3, c4, c5 : int]
@(EXTENDED_UTF8_SHORTEST (n, u, c0, c1, c2, c3, c4, c5) |
int n, int c0, int c1, int c2, int c3, int c4, int c5)
(*------------------------------------------------------------------*)
//
// A valid UTF-8 character is one that encodes a valid Unicode
// code point and is not overlong.
//
dataprop UTF8_CHAR_INVALID_CASES (c0 : int, c1 : int, c2 : int, c3 : int) =
// The cases are not mutually exclusive.
| {c0, c1, c2, c3 : int | extended_utf8_character_length c0 == ~1}
// We might not be using this case, presently (has that changed?),
// but it is included for completeness.
UTF8_CHAR_INVALID_bad_c0 (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int | 2 <= extended_utf8_character_length c0;
~(is_valid_utf8_continuation_byte c1)}
UTF8_CHAR_INVALID_bad_c1 (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int | 3 <= extended_utf8_character_length c0;
~(is_valid_utf8_continuation_byte c2)}
UTF8_CHAR_INVALID_bad_c2 (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int | extended_utf8_character_length c0 == 4;
~(is_valid_utf8_continuation_byte c3)}
UTF8_CHAR_INVALID_bad_c3 (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int |
extended_utf8_character_length c0 == 2;
extended_utf8_char_2byte_decoding (c0, c1) <= 0x7F}
UTF8_CHAR_INVALID_invalid_2byte (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int |
extended_utf8_character_length c0 == 3
&& (extended_utf8_char_3byte_decoding (c0, c1, c2) <= 0x7FF
|| ~(is_valid_unicode_code_point
(extended_utf8_char_3byte_decoding (c0, c1, c2))))}
UTF8_CHAR_INVALID_invalid_3byte (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int |
extended_utf8_character_length c0 == 4
&& (extended_utf8_char_4byte_decoding (c0, c1, c2, c3) <= 0xFFFF
|| ~(is_valid_unicode_code_point
(extended_utf8_char_4byte_decoding (c0, c1, c2, c3))))}
UTF8_CHAR_INVALID_invalid_4byte (c0, c1, c2, c3)
dataprop UTF8_CHAR_VALID_BYTES (c0 : int, c1 : int, c2 : int, c3 : int) =
| {c0 : int | 0 <= c0 && c0 <= 0x7F}
UTF8_CHAR_VALID_BYTES_1byte (c0, ~1, ~1, ~1)
| {c0, c1 : int | 0xC2 <= c0 && c0 <= 0xDF;
is_valid_utf8_continuation_byte c1}
UTF8_CHAR_VALID_BYTES_2byte (c0, c1, ~1, ~1)
| {c0, c1, c2 : int | (0xE1 <= c0 && c0 <= 0xEC)
|| c0 == 0xEE
|| c0 == 0xEF
|| (c0 == 0xE0 && 0xA0 <= c1)
|| (c0 == 0xED && c1 < 0xA0);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2}
UTF8_CHAR_VALID_BYTES_3byte (c0, c1, c2, ~1)
| {c0, c1, c2, c3 : int | (0xF1 <= c0 && c0 <= 0xF3)
|| (c0 == 0xF0 && 0x90 <= c1)
|| (c0 == 0xF4 && c1 < 0x90);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3}
UTF8_CHAR_VALID_BYTES_4byte (c0, c1, c2, c3)
dataprop UTF8_CHAR_INVALID_BYTES (c0 : int, c1 : int, c2 : int, c3 : int) =
| // This should never occur.
{c0 : int | is_extended_utf8_1byte_first_byte c0}
UTF8_CHAR_INVALID_BYTES_1byte (c0, ~1, ~1, ~1)
| {c0, c1 : int | is_extended_utf8_2byte_first_byte c0;
c0 == 0xC0 || c0 == 0xC1 ||
is_invalid_utf8_continuation_byte c1}
UTF8_CHAR_INVALID_BYTES_2byte (c0, c1, ~1, ~1)
| {c0, c1, c2 : int | is_extended_utf8_3byte_first_byte c0;
(c0 == 0xE0 && c1 < 0xA0) ||
(c0 == 0xED && 0xA0 <= c1) ||
is_invalid_utf8_continuation_byte c1 ||
is_invalid_utf8_continuation_byte c2}
UTF8_CHAR_INVALID_BYTES_3byte (c0, c1, c2, ~1)
| {c0, c1, c2, c3 : int | is_extended_utf8_4byte_first_byte c0;
0xF4 < c0 ||
(c0 == 0xF0 && c1 < 0x90) ||
(c0 == 0xF4 && 0x90 <= c1) ||
is_invalid_utf8_continuation_byte c1 ||
is_invalid_utf8_continuation_byte c2 ||
is_invalid_utf8_continuation_byte c3}
UTF8_CHAR_INVALID_BYTES_4byte (c0, c1, c2, c3)
| {c0, c1, c2, c3 : int | ~(is_extended_utf8_1byte_first_byte c0);
~(is_extended_utf8_2byte_first_byte c0);
~(is_extended_utf8_3byte_first_byte c0);
~(is_extended_utf8_4byte_first_byte c0)}
UTF8_CHAR_INVALID_BYTES_bad_c0 (c0, c1, c2, c3)
dataprop UTF8_CHAR_VALIDITY (n : int, u : int, c0 : int, c1 : int,
c2 : int, c3 : int, b : bool) =
| {n : int} {u : int | is_valid_unicode_code_point u}
{c0, c1, c2, c3 : int}
UTF8_CHAR_valid (n, u, c0, c1, c2, c3, true) of
(EXTENDED_UTF8_SHORTEST (n, u, c0, c1, c2, c3, ~1, ~1),
UTF8_CHAR_VALID_BYTES (c0, c1, c2, c3))
| {n : int} {u : int} {c0, c1, c2, c3 : int}
UTF8_CHAR_invalid (n, u, c0, c1, c2, c3, false) of
(UTF8_CHAR_INVALID_CASES (c0, c1, c2, c3),
UTF8_CHAR_INVALID_BYTES (c0, c1, c2, c3))
propdef UTF8_CHAR_VALID (n : int, u : int, c0 : int, c1 : int,
c2 : int, c3 : int) =
UTF8_CHAR_VALIDITY (n, u, c0, c1, c2, c3, true)
propdef UTF8_CHAR_INVALID (c0 : int, c1 : int, c2 : int, c3 : int) =
[n : int] [u : int] UTF8_CHAR_VALIDITY (n, u, c0, c1, c2, c3, false)
extern prfun
utf8_char_valid_implies_shortest :
{n : int} {u : int} {c0, c1, c2, c3 : int}
UTF8_CHAR_VALID (n, u, c0, c1, c2, c3) -<prf>
EXTENDED_UTF8_SHORTEST (n, u, c0, c1, c2, c3, ~1, ~1)
extern prfun
lemma_valid_utf8_character_1byte :
{u, c0 : int |
is_extended_utf8_1byte_first_byte c0;
u == extended_utf8_char_1byte_decoding c0;
0 <= u; u <= 0x7F}
() -<prf> UTF8_CHAR_VALID (1, u, c0, ~1, ~1, ~1)
extern prfun
lemma_valid_utf8_character_2byte :
{u, c0, c1 : int |
is_extended_utf8_2byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
u == extended_utf8_char_2byte_decoding (c0, c1);
0x7F < u; u <= 0x7FF}
() -<prf> UTF8_CHAR_VALID (2, u, c0, c1, ~1, ~1)
extern prfun
lemma_valid_utf8_character_3byte :
{u, c0, c1, c2 : int |
is_extended_utf8_3byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
u == extended_utf8_char_3byte_decoding (c0, c1, c2);
0x7FF < u; u <= 0xFFFF;
//
// Exclude the UTF-16 surrogate halves.
//
~(0xD800 <= u && u < 0xE000)}
() -<prf> UTF8_CHAR_VALID (3, u, c0, c1, c2, ~1)
extern prfun
lemma_valid_utf8_character_4byte :
{u, c0, c1, c2, c3 : int |
is_extended_utf8_4byte_first_byte c0;
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3;
u == extended_utf8_char_4byte_decoding (c0, c1, c2, c3);
0xFFFF < u; u <= 0x10FFFF}
() -<prf> UTF8_CHAR_VALID (4, u, c0, c1, c2, c3)
extern prfun
utf8_character_1byte_valid_bytes :
// This does not really do anything, but is included
// for completeness.
{u, c0 : int | is_extended_utf8_1byte_first_byte c0}
UTF8_CHAR_VALID (1, u, c0, ~1, ~1, ~1) -<prf> void
extern prfun
utf8_character_2byte_valid_bytes :
{u, c0, c1 : int | is_extended_utf8_2byte_first_byte c0}
UTF8_CHAR_VALID (2, u, c0, c1, ~1, ~1) -<prf>
[0xC2 <= c0; c0 <= 0xDF;
is_valid_utf8_continuation_byte c1]
void
extern prfun
utf8_character_3byte_valid_bytes :
{u, c0, c1, c2 : int | is_extended_utf8_3byte_first_byte c0}
UTF8_CHAR_VALID (3, u, c0, c1, c2, ~1) -<prf>
[(0xE1 <= c0 && c0 <= 0xEC)
|| c0 == 0xEE
|| c0 == 0xEF
|| (c0 == 0xE0 && 0xA0 <= c1)
|| (c0 == 0xED && c1 < 0xA0);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2]
void
extern prfun
utf8_character_4byte_valid_bytes :
{u, c0, c1, c2, c3 : int | is_extended_utf8_4byte_first_byte c0}
UTF8_CHAR_VALID (4, u, c0, c1, c2, c3) -<prf>
[(0xF1 <= c0 && c0 <= 0xF3)
|| (c0 == 0xF0 && 0x90 <= c1)
|| (c0 == 0xF4 && c1 < 0x90);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3]
void
extern prfun
utf8_character_1byte_invalid_bytes :
// This does not really do anything, but is included
// for completeness.
{c0 : int | is_extended_utf8_1byte_first_byte c0}
UTF8_CHAR_INVALID (c0, ~1, ~1, ~1) -<prf> void
extern prfun
utf8_character_2byte_invalid_bytes :
{c0, c1 : int | is_extended_utf8_2byte_first_byte c0}
UTF8_CHAR_INVALID (c0, c1, ~1, ~1) -<prf>
[c0 == 0xC0 || c0 == 0xc1 || is_invalid_utf8_continuation_byte c1]
void
extern prfun
utf8_character_3byte_invalid_bytes :
{c0, c1, c2 : int | is_extended_utf8_3byte_first_byte c0}
UTF8_CHAR_INVALID (c0, c1, c2, ~1) -<prf>
[(c0 == 0xE0 && c1 < 0xA0) ||
(c0 == 0xED && 0xA0 <= c1) ||
is_invalid_utf8_continuation_byte c1 ||
is_invalid_utf8_continuation_byte c2]
void
extern prfun
utf8_character_4byte_invalid_bytes :
{c0, c1, c2, c3 : int | is_extended_utf8_4byte_first_byte c0}
UTF8_CHAR_INVALID (c0, c1, c2, c3) -<prf>
[0xF4 < c0 ||
(c0 == 0xF0 && c1 < 0x90) ||
(c0 == 0xF4 && 0x90 <= c1) ||
is_invalid_utf8_continuation_byte c1 ||
is_invalid_utf8_continuation_byte c2 ||
is_invalid_utf8_continuation_byte c3]
void
extern fun {}
is_valid_utf8_character_1byte :
{c0 : int | is_extended_utf8_1byte_first_byte c0}
int c0 -<>
[b : bool | b == true] [u : int]
(UTF8_CHAR_VALIDITY (1, u, c0, ~1, ~1, ~1, b) | bool b)
extern fun {}
is_valid_utf8_character_2byte :
{c0, c1 : int | is_extended_utf8_2byte_first_byte c0}
(int c0, int c1) -<>
[b : bool] [u : int]
(UTF8_CHAR_VALIDITY (2, u, c0, c1, ~1, ~1, b) | bool b)
extern fun {}
is_valid_utf8_character_3byte :
{c0, c1, c2 : int | is_extended_utf8_3byte_first_byte c0}
(int c0, int c1, int c2) -<>
[b : bool] [u : int]
(UTF8_CHAR_VALIDITY (3, u, c0, c1, c2, ~1, b) | bool b)
extern fun {}
is_valid_utf8_character_4byte :
{c0, c1, c2, c3 : int | is_extended_utf8_4byte_first_byte c0}
(int c0, int c1, int c2, int c3) -<>
[b : bool] [u : int]
(UTF8_CHAR_VALIDITY (4, u, c0, c1, c2, c3, b) | bool b)
extern fun {}
decode_utf8_1byte :
{c0 : int | is_extended_utf8_1byte_first_byte c0}
int c0 -<> [u : int | 0 <= u; u <= 0x7F] int u
extern fun {}
decode_utf8_2byte :
{c0, c1 : int | 0xC2 <= c0; c0 <= 0xDF;
is_valid_utf8_continuation_byte c1}
(int c0, int c1) -<> [u : int | 0x7F < u; u <= 0x7FF] int u
extern fun {}
decode_utf8_3byte :
{c0, c1, c2 : int | (0xE1 <= c0 && c0 <= 0xEC)
|| c0 == 0xEE
|| c0 == 0xEF
|| (c0 == 0xE0 && 0xA0 <= c1)
|| (c0 == 0xED && c1 < 0xA0);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2}
(int c0, int c1, int c2) -<>
[u : int | 0x7FF < u; u <= 0xFFFF; u < 0xD800 || 0xE000 <= u] int u
extern fun {}
decode_utf8_4byte :
{c0, c1, c2, c3 : int | (0xF1 <= c0 && c0 <= 0xF3)
|| (c0 == 0xF0 && 0x90 <= c1)
|| (c0 == 0xF4 && c1 < 0x90);
is_valid_utf8_continuation_byte c1;
is_valid_utf8_continuation_byte c2;
is_valid_utf8_continuation_byte c3}
(int c0, int c1, int c2, int c3) -<>
[u : int | 0xFFFF < u; u <= 0x10FFFF] int u
extern fun {}
encode_utf8_character :
{u : int | is_valid_unicode_code_point u}
int u -<>
[n : int]
[c0, c1, c2, c3 : int | extended_utf8_char_length_relation (c0, n)]
@(UTF8_CHAR_VALID (n, u, c0, c1, c2, c3) |
int n, int c0, int c1, int c2, int c3)
(*------------------------------------------------------------------*)
#define utf8_decode_next_error_char ~1
(* Returns @(utf8_decode_next_error_char, ..) on error. *)
extern fun
utf8_array_decode_next {utf8len : int | 0 < utf8len}
{n_utf8arr : int | utf8len <= n_utf8arr}
{i : int | i < utf8len}
(utf8len : size_t utf8len,
utf8arr : &(@[char][n_utf8arr]),
i : size_t i) :<>
[c : int | is_valid_unicode_code_point c ||
c == utf8_decode_next_error_char]
[i_next : int | i_next == i + 1 || i_next == i + 2 ||
i_next == i + 3 || i_next == i + 4;
i_next <= utf8len]
@(int c, size_t i_next)
extern fun
utf8_string_decode_next {utf8len : int | 0 < utf8len}
{n_utf8str : int | utf8len <= n_utf8str}
{i : int | i < utf8len}
(utf8len : size_t utf8len,
utf8str : string n_utf8str,
i : size_t i) :<>
[c : int | is_valid_unicode_code_point c ||
c == utf8_decode_next_error_char]
[i_next : int | i_next == i + 1 || i_next == i + 2 ||
i_next == i + 3 || i_next == i + 4;
i_next <= utf8len]
@(int c, size_t i_next)
overload utf8_decode_next with utf8_array_decode_next
overload utf8_decode_next with utf8_string_decode_next
(*###################### IMPLEMENTATION ############################*)
// Integer division by 64 is equivalent to shifting right
// by 6 bits.
extern prfun _shift_right_twelve :
{x, y, z : nat | y == (x \ndiv 64);
z == (y \ndiv 64)}
(int x, int y, int z) -<prf> [z == (x \ndiv (64 * 64))] void
primplement _shift_right_twelve (x, y, z) =
()
extern prfun _shift_right_eighteen :
{x, y, z, u : nat | y == (x \ndiv 64);
z == (y \ndiv 64);
u == (z \ndiv 64)}
(int x, int y, int z, int u) -<prf> [u == (x \ndiv (64 * 64 * 64))] void
primplement _shift_right_eighteen (x, y, z, u) = ()
extern prfun _shift_right_twenty_four :
{x, y, z, u, v : nat | y == (x \ndiv 64);
z == (y \ndiv 64);
u == (z \ndiv 64);
v == (u \ndiv 64)}
(int x, int y, int z, int u, int v) -<prf>
[v == (x \ndiv (64 * 64 * 64 * 64))] void
primplement _shift_right_twenty_four (x, y, z, u, v) = ()
(*------------------------------------------------------------------*)
implement {}
is_valid_unicode_code_point u =
((0x0 <= u) * (u < 0xD800)) + ((0xE000 <= u) * (u <= 0x10FFFF))
(*------------------------------------------------------------------*)
primplement
extended_utf8_char_length_relation_to_length () = ()
primplement
extended_utf8_char_length_to_length_relation () = ()
primplement
utf8_char_length_relation_to_length () = ()
primplement
utf8_char_length_to_length_relation () = ()
(*------------------------------------------------------------------*)
implement {}
is_valid_utf8_continuation_byte c =
(0x80 <= c) * (c <= 0xBF)
(*------------------------------------------------------------------*)
primplement
decode_extended_utf8_istot {n} {c0, c1, c2, c3, c4, c5} () =
sif n == 1 then
let
prfn
make_pf {u : int | u == extended_utf8_char_1byte_decoding (c0)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_1byte ()
stadef u = extended_utf8_char_1byte_decoding (c0)
in
make_pf {u} ()
end
else sif n == 2 then
let
prfn
make_pf {u : int | u == extended_utf8_char_2byte_decoding (c0, c1)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_2byte ()
stadef u = extended_utf8_char_2byte_decoding (c0, c1)
in
make_pf {u} ()
end
else sif n == 3 then
let
prfn
make_pf {u : int | u == extended_utf8_char_3byte_decoding (c0, c1, c2)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_3byte ()
stadef u = extended_utf8_char_3byte_decoding (c0, c1, c2)
in
make_pf {u} ()
end
else sif n == 4 then
let
prfn
make_pf {u : int |
u == extended_utf8_char_4byte_decoding (c0, c1, c2, c3)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_4byte ()
stadef u = extended_utf8_char_4byte_decoding (c0, c1, c2, c3)
in
make_pf {u} ()
end
else sif n == 5 then
let
prfn
make_pf {u : int |
u == extended_utf8_char_5byte_decoding (c0, c1, c2, c3, c4)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_5byte ()
stadef u = extended_utf8_char_5byte_decoding (c0, c1, c2, c3, c4)
in
make_pf {u} ()
end
else
let
prfn
make_pf {u : int |
u == extended_utf8_char_6byte_decoding (c0, c1, c2, c3, c4, c5)}
() :<prf>
EXTENDED_UTF8_CHAR (n, u, c0, c1, c2, c3, c4, c5) =
EXTENDED_UTF8_CHAR_6byte ()
stadef u = extended_utf8_char_6byte_decoding (c0, c1, c2, c3, c4, c5)
in
make_pf {u} ()
end
primplement
decode_extended_utf8_isfun {na} (pf_a, pf_b) =
sif na == 1 then
let
prval EXTENDED_UTF8_CHAR_1byte () = pf_a
prval EXTENDED_UTF8_CHAR_1byte () = pf_b
in
end
else sif na == 2 then
let
prval EXTENDED_UTF8_CHAR_2byte () = pf_a
prval EXTENDED_UTF8_CHAR_2byte () = pf_b
in
end
else sif na == 3 then
let
prval EXTENDED_UTF8_CHAR_3byte () = pf_a
prval EXTENDED_UTF8_CHAR_3byte () = pf_b
in
end
else sif na == 4 then
let
prval EXTENDED_UTF8_CHAR_4byte () = pf_a
prval EXTENDED_UTF8_CHAR_4byte () = pf_b
in
end
else sif na == 5 then
let
prval EXTENDED_UTF8_CHAR_5byte () = pf_a
prval EXTENDED_UTF8_CHAR_5byte () = pf_b
in
end
else
let
prval EXTENDED_UTF8_CHAR_6byte () = pf_a
prval EXTENDED_UTF8_CHAR_6byte () = pf_b
in
end
primplement
lemma_extended_utf8_char_length pf_char =
case+ pf_char of
| EXTENDED_UTF8_CHAR_1byte () => ()
| EXTENDED_UTF8_CHAR_2byte () => ()
| EXTENDED_UTF8_CHAR_3byte () => ()
| EXTENDED_UTF8_CHAR_4byte () => ()
| EXTENDED_UTF8_CHAR_5byte () => ()
| EXTENDED_UTF8_CHAR_6byte () => ()
implement {}
decode_extended_utf8_1byte c0 =
(EXTENDED_UTF8_CHAR_1byte () | c0)
implement {}
decode_extended_utf8_2byte (c0, c1) =
let
val u0 = c0 - 0xC0
val u1 = c1 - 0x80
in
(EXTENDED_UTF8_CHAR_2byte () | 64 * u0 + u1)
end
implement {}
decode_extended_utf8_3byte (c0, c1, c2) =
let
val u0 = c0 - 0xE0
val u1 = c1 - 0x80
val u2 = c2 - 0x80
in
(EXTENDED_UTF8_CHAR_3byte () | 64 * (64 * u0 + u1) + u2)
end
implement {}
decode_extended_utf8_4byte (c0, c1, c2, c3) =
let
val u0 = c0 - 0xF0
val u1 = c1 - 0x80
val u2 = c2 - 0x80
val u3 = c3 - 0x80
in
(EXTENDED_UTF8_CHAR_4byte () | 64 * (64 * (64 * u0 + u1) + u2) + u3)
end
implement {}
decode_extended_utf8_5byte (c0, c1, c2, c3, c4) =
let
val u0 = c0 - 0xF8
val u1 = c1 - 0x80
val u2 = c2 - 0x80
val u3 = c3 - 0x80
val u4 = c4 - 0x80
in
(EXTENDED_UTF8_CHAR_5byte () |
64 * (64 * (64 * (64 * u0 + u1) + u2) + u3) + u4)
end
implement {}
decode_extended_utf8_6byte (c0, c1, c2, c3, c4, c5) =
let
val u0 = c0 - 0xFC
val u1 = c1 - 0x80
val u2 = c2 - 0x80
val u3 = c3 - 0x80
val u4 = c4 - 0x80
val u5 = c5 - 0x80
in
(EXTENDED_UTF8_CHAR_6byte () |
64 * (64 * (64 * (64 * (64 * u0 + u1) + u2) + u3) + u4) + u5)
end
(*------------------------------------------------------------------*)
primplement
extended_utf8_shortest_is_char pf_shortest =
case+ pf_shortest of
| EXTENDED_UTF8_SHORTEST_1byte pf_char => pf_char
| EXTENDED_UTF8_SHORTEST_2byte pf_char => pf_char
| EXTENDED_UTF8_SHORTEST_3byte pf_char => pf_char
| EXTENDED_UTF8_SHORTEST_4byte pf_char => pf_char
| EXTENDED_UTF8_SHORTEST_5byte pf_char => pf_char
| EXTENDED_UTF8_SHORTEST_6byte pf_char => pf_char
primplement
lemma_extended_utf8_shortest_length pf_shortest =
case+ pf_shortest of
| EXTENDED_UTF8_SHORTEST_1byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_1byte () = pf_char }
| EXTENDED_UTF8_SHORTEST_2byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_2byte () = pf_char }
| EXTENDED_UTF8_SHORTEST_3byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_3byte () = pf_char }
| EXTENDED_UTF8_SHORTEST_4byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_4byte () = pf_char }
| EXTENDED_UTF8_SHORTEST_5byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_5byte () = pf_char }
| EXTENDED_UTF8_SHORTEST_6byte pf_char =>
{ prval EXTENDED_UTF8_CHAR_6byte () = pf_char }
implement {}
encode_extended_utf8_character u =
if u <= 0x7F then
let
val c0 = u
in
@(EXTENDED_UTF8_SHORTEST_1byte (EXTENDED_UTF8_CHAR_1byte ()) |
1, c0, ~1, ~1, ~1, ~1, ~1)
end
else if u <= 0x7FF then
let
val c1 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c0 = 0xC0 + u1
in
@(EXTENDED_UTF8_SHORTEST_2byte (EXTENDED_UTF8_CHAR_2byte ()) |
2, c0, c1, ~1, ~1, ~1, ~1)
end
else if u <= 0xFFFF then
let
val c2 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c1 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c0 = 0xE0 + u2
in
@(EXTENDED_UTF8_SHORTEST_3byte (EXTENDED_UTF8_CHAR_3byte ()) |
3, c0, c1, c2, ~1, ~1, ~1)
end
else if u <= 0x1FFFFF then
let
val c3 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c2 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c1 = 0x80 + (u2 \nmod 64)
val u3 = u2 \ndiv 64
val c0 = 0xF0 + u3
prval () = _shift_right_twelve (u, u1, u2)
in
@(EXTENDED_UTF8_SHORTEST_4byte (EXTENDED_UTF8_CHAR_4byte ()) |
4, c0, c1, c2, c3, ~1, ~1)
end
else if u <= 0x3FFFFFF then
let
val c4 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c3 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c2 = 0x80 + (u2 \nmod 64)
val u3 = u2 \ndiv 64
val c1 = 0x80 + (u3 \nmod 64)
val u4 = u3 \ndiv 64
val c0 = 0xF8 + u4
prval () = _shift_right_twelve (u, u1, u2)
prval () = _shift_right_eighteen (u, u1, u2, u3)
in
@(EXTENDED_UTF8_SHORTEST_5byte (EXTENDED_UTF8_CHAR_5byte ()) |
5, c0, c1, c2, c3, c4, ~1)
end
else
let
val c5 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c4 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c3 = 0x80 + (u2 \nmod 64)
val u3 = u2 \ndiv 64
val c2 = 0x80 + (u3 \nmod 64)
val u4 = u3 \ndiv 64
val c1 = 0x80 + (u4 \nmod 64)
val u5 = u4 \ndiv 64
val c0 = 0xFC + u5
prval () = _shift_right_twelve (u, u1, u2)
prval () = _shift_right_eighteen (u, u1, u2, u3)
prval () = _shift_right_twenty_four (u, u1, u2, u3, u4)
in
@(EXTENDED_UTF8_SHORTEST_6byte (EXTENDED_UTF8_CHAR_6byte ()) |
6, c0, c1, c2, c3, c4, c5)
end
(*------------------------------------------------------------------*)
primplement
utf8_char_valid_implies_shortest pf_valid =
case+ pf_valid of
| UTF8_CHAR_valid (pf_shortest, _) => pf_shortest
primplement
lemma_valid_utf8_character_1byte {u, c0} () =
let
prfn
make_pf {u : int | u == extended_utf8_char_1byte_decoding (c0)}
() :<prf> EXTENDED_UTF8_CHAR (1, u, c0, ~1, ~1, ~1, ~1, ~1) =
EXTENDED_UTF8_CHAR_1byte ()
prval pf_char = make_pf {u} ()
prval pf_shortest = EXTENDED_UTF8_SHORTEST_1byte pf_char
prval pf_bytes = UTF8_CHAR_VALID_BYTES_1byte ()
prval pf_valid = UTF8_CHAR_valid (pf_shortest, pf_bytes)
in
pf_valid
end
primplement
lemma_valid_utf8_character_2byte {u, c0, c1} () =
let
prfn
make_pf {u : int | u == extended_utf8_char_2byte_decoding (c0, c1)}
() :<prf> EXTENDED_UTF8_CHAR (2, u, c0, c1, ~1, ~1, ~1, ~1) =
EXTENDED_UTF8_CHAR_2byte ()
prval pf_char = make_pf {u} ()
prval pf_shortest = EXTENDED_UTF8_SHORTEST_2byte pf_char
prval pf_bytes = UTF8_CHAR_VALID_BYTES_2byte ()
prval pf_valid = UTF8_CHAR_valid (pf_shortest, pf_bytes)
in
pf_valid
end
primplement
lemma_valid_utf8_character_3byte {u, c0, c1, c2} () =
let
prfn
make_pf {u : int | u == extended_utf8_char_3byte_decoding (c0, c1, c2)}
() :<prf> EXTENDED_UTF8_CHAR (3, u, c0, c1, c2, ~1, ~1, ~1) =
EXTENDED_UTF8_CHAR_3byte ()
prval pf_char = make_pf {u} ()
prfn lemma_c1 () :<prf> [c1 == 0x80 + ((u \ndiv 64) \nmod 64)] void =
{
// Convert to Horner form.
stadef u1 = 64 * (64 * (c0 - 0xE0) + (c1 - 0x80)) + (c2 - 0x80)
prval EQINT () = eqint_make {u, u1} ()
}
prval () = lemma_c1 ()
prval pf_shortest = EXTENDED_UTF8_SHORTEST_3byte pf_char
prval pf_bytes = UTF8_CHAR_VALID_BYTES_3byte ()
prval pf_valid = UTF8_CHAR_valid (pf_shortest, pf_bytes)
in
pf_valid
end
primplement
lemma_valid_utf8_character_4byte {u, c0, c1, c2, c3} () =
let
prfn
make_pf {u : int | u == extended_utf8_char_4byte_decoding (c0, c1, c2, c3)}
() :<prf> EXTENDED_UTF8_CHAR (4, u, c0, c1, c2, c3, ~1, ~1) =
EXTENDED_UTF8_CHAR_4byte ()
prval pf_char = make_pf {u} ()
prfn lemma_c1 () :<prf> [c1 == 0x80 + ((u \ndiv (64 * 64)) \nmod 64)] void =
{
prval EQINT () =
eqint_make {(64 * 64 * (c0 - 0xE0)) \ndiv (64 * 64), c0 - 0xE0} ()
prval pfd = divmod_istot {u \ndiv (64 * 64), 64} ()
prval pfm = divmod_elim pfd
prval () = mul_elim pfm
}
prval () = lemma_c1 ()
prfn lemma_c2 () :<prf> [c2 == 0x80 + ((u \ndiv 64) \nmod 64)] void =
{
// Convert to Horner form.
stadef u1 = 64 * (64 * (64 * (c0 - 0xF0) + (c1 - 0x80)) + (c2 - 0x80))
+ (c3 - 0x80)
prval EQINT () = eqint_make {u, u1} ()
}
prval () = lemma_c2 ()
prval pf_shortest = EXTENDED_UTF8_SHORTEST_4byte pf_char
prval pf_bytes = UTF8_CHAR_VALID_BYTES_4byte ()
prval pf_valid = UTF8_CHAR_valid (pf_shortest, pf_bytes)
in
pf_valid
end
primplement
utf8_character_1byte_valid_bytes pf_valid = ()
primplement
utf8_character_2byte_valid_bytes pf_valid =
{
prval UTF8_CHAR_valid (_, pf_bytes) = pf_valid
prval UTF8_CHAR_VALID_BYTES_2byte () = pf_bytes
}
primplement
utf8_character_3byte_valid_bytes pf_valid =
{
prval UTF8_CHAR_valid (_, pf_bytes) = pf_valid
prval UTF8_CHAR_VALID_BYTES_3byte () = pf_bytes
}
primplement
utf8_character_4byte_valid_bytes pf_valid =
{
prval UTF8_CHAR_valid (_, pf_bytes) = pf_valid
prval UTF8_CHAR_VALID_BYTES_4byte () = pf_bytes
}
primplement
utf8_character_1byte_invalid_bytes pf_invalid =
{
prval UTF8_CHAR_invalid (_, pf_bytes) = pf_invalid
prval UTF8_CHAR_INVALID_BYTES_1byte () = pf_bytes
}
primplement
utf8_character_2byte_invalid_bytes pf_invalid =
{
prval UTF8_CHAR_invalid (_, pf_bytes) = pf_invalid
prval UTF8_CHAR_INVALID_BYTES_2byte () = pf_bytes
}
primplement
utf8_character_3byte_invalid_bytes pf_invalid =
{
prval UTF8_CHAR_invalid (_, pf_bytes) = pf_invalid
prval UTF8_CHAR_INVALID_BYTES_3byte () = pf_bytes
}
primplement
utf8_character_4byte_invalid_bytes pf_invalid =
{
prval UTF8_CHAR_invalid (_, pf_bytes) = pf_invalid
prval UTF8_CHAR_INVALID_BYTES_4byte () = pf_bytes
}
implement {}
is_valid_utf8_character_1byte {c0} c0 =
let
stadef u = extended_utf8_char_1byte_decoding c0
in
(lemma_valid_utf8_character_1byte {u, c0} () | true)
end
implement {}
is_valid_utf8_character_2byte {c0, c1} (c0, c1) =
let
stadef u = extended_utf8_char_2byte_decoding (c0, c1)
in
if not (is_valid_utf8_continuation_byte c1) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c1 (),
UTF8_CHAR_INVALID_BYTES_2byte ()) |
false)
else if c0 < 0xC2 then
// The sequence is overlong.
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_invalid_2byte (),
UTF8_CHAR_INVALID_BYTES_2byte ()) |
false)
else
(lemma_valid_utf8_character_2byte {u, c0, c1} () | true)
end
implement {}
is_valid_utf8_character_3byte {c0, c1, c2} (c0, c1, c2) =
let
stadef u = extended_utf8_char_3byte_decoding (c0, c1, c2)
in
if not (is_valid_utf8_continuation_byte c1) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c1 (),
UTF8_CHAR_INVALID_BYTES_3byte ()) |
false)
else if not (is_valid_utf8_continuation_byte c2) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c2 (),
UTF8_CHAR_INVALID_BYTES_3byte ()) |
false)
else if (0xE1 <= c0) * (c0 <= 0xEC) then
(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | true)
else if c0 = 0xEE then
(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | true)
else if c0 = 0xEF then
(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | true)
else if (c0 = 0xE0) * (0xA0 <= c1) then
(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | true)
else if (c0 = 0xED) * (c1 < 0xA0) then
(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | true)
else
// Either the sequence is overlong or it decodes to
// an invalid code point.
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_invalid_3byte (),
UTF8_CHAR_INVALID_BYTES_3byte ()) |
false)
end
implement {}
is_valid_utf8_character_4byte {c0, c1, c2, c3} (c0, c1, c2, c3) =
let
stadef u = extended_utf8_char_4byte_decoding (c0, c1, c2, c3)
in
if not (is_valid_utf8_continuation_byte c1) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c1 (),
UTF8_CHAR_INVALID_BYTES_4byte ()) |
false)
else if not (is_valid_utf8_continuation_byte c2) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c2 (),
UTF8_CHAR_INVALID_BYTES_4byte ()) |
false)
else if not (is_valid_utf8_continuation_byte c3) then
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_bad_c3 (),
UTF8_CHAR_INVALID_BYTES_4byte ()) |
false)
else if (0xF1 <= c0) * (c0 <= 0xF3) then
(lemma_valid_utf8_character_4byte {u, c0, c1, c2, c3} () | true)
else if (c0 = 0xF0) * (0x90 <= c1) then
(lemma_valid_utf8_character_4byte {u, c0, c1, c2, c3} () | true)
else if (c0 = 0xF4) * (c1 < 0x90) then
(lemma_valid_utf8_character_4byte {u, c0, c1, c2, c3} () | true)
else
// Either the sequence is overlong or it decodes to
// an invalid code point.
(UTF8_CHAR_invalid (UTF8_CHAR_INVALID_invalid_4byte (),
UTF8_CHAR_INVALID_BYTES_4byte ()) |
false)
end
implement {}
decode_utf8_1byte c0 = c0
implement {}
decode_utf8_2byte (c0, c1) =
let
val u0 = c0 - 0xC0
val u1 = c1 - 0x80
in
64 * u0 + u1
end
implement {}
decode_utf8_3byte (c0, c1, c2) =
let
val u0 = c0 - 0xE0
val u1 = c1 - 0x80
val u2 = c2 - 0x80
in
64 * (64 * u0 + u1) + u2
end
implement {}
decode_utf8_4byte (c0, c1, c2, c3) =
let
val u0 = c0 - 0xF0
val u1 = c1 - 0x80
val u2 = c2 - 0x80
val u3 = c3 - 0x80
in
64 * (64 * (64 * u0 + u1) + u2) + u3
end
implement {}
encode_utf8_character {u} u =
if u <= 0x7F then
let
val c0 = u
stadef c0 = u
in
@(lemma_valid_utf8_character_1byte {u, c0} () | 1, c0, ~1, ~1, ~1)
end
else if u <= 0x7FF then
let
val c1 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c0 = 0xC0 + u1
stadef c1 = 0x80 + (u \nmod 64)
stadef u1 = u \ndiv 64
stadef c0 = 0xC0 + u1
in
@(lemma_valid_utf8_character_2byte {u, c0, c1} () | 2, c0, c1, ~1, ~1)
end
else if u <= 0xFFFF then
let
val c2 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c1 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c0 = 0xE0 + u2
stadef c2 = 0x80 + (u \nmod 64)
stadef u1 = u \ndiv 64
stadef c1 = 0x80 + (u1 \nmod 64)
stadef u2 = u1 \ndiv 64
stadef c0 = 0xE0 + u2
in
@(lemma_valid_utf8_character_3byte {u, c0, c1, c2} () | 3, c0, c1, c2, ~1)
end
else
let
val c3 = 0x80 + (u \nmod 64)
val u1 = u \ndiv 64
val c2 = 0x80 + (u1 \nmod 64)
val u2 = u1 \ndiv 64
val c1 = 0x80 + (u2 \nmod 64)
val u3 = u2 \ndiv 64
val c0 = 0xF0 + u3
stadef c3 = 0x80 + (u \nmod 64)
stadef u1 = u \ndiv 64
stadef c2 = 0x80 + (u1 \nmod 64)
stadef u2 = u1 \ndiv 64
stadef c1 = 0x80 + (u2 \nmod 64)
stadef u3 = u2 \ndiv 64
stadef c0 = 0xF0 + u3
prval () = _shift_right_twelve (u, u1, u2)
in
@(lemma_valid_utf8_character_4byte {u, c0, c1, c2, c3} () |
4, c0, c1, c2, c3)
end
(*------------------------------------------------------------------*)
implement
utf8_array_decode_next (utf8len, utf8arr, i) =
let
macdef getchr (j) = g1ofg0 (char2u2i (utf8arr[,(j)]))
macdef error_return = @(utf8_decode_next_error_char, i + i2sz 1)
prval _ = lemma_g1uint_param (i)
val c0 = getchr (i)
in
if 0x00 <= c0 &&& c0 <= 0xFF then
let
val seqlen = utf8_character_length c0
in
case+ seqlen of
| 1 => @(c0, i + i2sz 1)
| 2 =>
if utf8len < i + i2sz 2 then
error_return
else
let
val c1 = getchr (i + i2sz 1)
val (pf | valid) =
is_valid_utf8_character_2byte (c0, c1)
in
if valid then
let
prval _ = utf8_character_2byte_valid_bytes pf
val code_point = decode_utf8_2byte (c0, c1)
in
@(code_point, i + i2sz 2)
end
else
error_return
end
| 3 =>
if utf8len < i + i2sz 3 then
error_return
else
let
val c1 = getchr (i + i2sz 1)
val c2 = getchr (i + i2sz 2)
val (pf | valid) =
is_valid_utf8_character_3byte (c0, c1, c2)
in
if valid then
let
prval _ = utf8_character_3byte_valid_bytes pf
val code_point = decode_utf8_3byte (c0, c1, c2)
in
@(code_point, i + i2sz 3)
end
else
error_return
end
| 4 =>
if utf8len < i + i2sz 4 then
error_return
else
let
val c1 = getchr (i + i2sz 1)
val c2 = getchr (i + i2sz 2)
val c3 = getchr (i + i2sz 3)
val (pf | valid) =
is_valid_utf8_character_4byte (c0, c1, c2, c3)
in
if valid then
let
prval _ = utf8_character_4byte_valid_bytes pf
val code_point = decode_utf8_4byte (c0, c1, c2, c3)
in
@(code_point, i + i2sz 4)
end
else
error_return
end
| _ => error_return
end
else
(* This branch should never be run on a system
with 8-bit char. *)
error_return
end
implement
utf8_string_decode_next {..} {n_utf8str} (utf8len, utf8str, i) =
let
val [p : addr] p = string2ptr utf8str
val (pf, consume_pf | p) =
$UNSAFE.ptr1_vtake{@[char][n_utf8str]} p
val result = utf8_array_decode_next (utf8len, !p, i)
prval _ = consume_pf pf
in
result
end
(*###################### DEMONSTRATION #############################*)
fn
encode_LATIN_CAPITAL_LETTER_A () : void =
{
val u = 0x0041
(* Return both a proof of valid encoding and the encoding. *)
val (pf_valid | n, c0, c1, c2, c3) = encode_utf8_character (u)
(* Verify the encoding. *)
val _ = assertloc (n = 1)
val _ = assertloc (c0 = 0x41)
}
fn
decode_LATIN_CAPITAL_LETTER_A () : void =
{
val str = "\x41\0"
val n = length str
val (c, i) = utf8_decode_next (n, str, i2sz 0)
(* Verify that the decoding is correct. *)
val _ = assertloc (c = 0x0041)
(* Verify that the next index is 1. *)
val _ = assertloc (i = i2sz 1)
}
fn
encode_LATIN_SMALL_LETTER_O_WITH_DIAERESIS () : void =
{
val u = 0x00F6
(* Return both a proof of valid encoding and the encoding. *)
val (pf_valid | n, c0, c1, c2, c3) = encode_utf8_character (u)
(* Verify the encoding. *)
val _ = assertloc (n = 2)
val _ = assertloc (c0 = 0xC3)
val _ = assertloc (c1 = 0xB6)
}
fn
decode_LATIN_SMALL_LETTER_O_WITH_DIAERESIS () : void =
{
val str = "\xC3\xB6\0"
val n = length str
val (c, i) = utf8_decode_next (n, str, i2sz 0)
(* Verify that the decoding is correct. *)
val _ = assertloc (c = 0x00F6)
(* Verify that the next index is 2. *)
val _ = assertloc (i = i2sz 2)
}
fn
encode_CYRILLIC_CAPITAL_LETTER_ZHE () : void =
{
val u = 0x0416
(* Return both a proof of valid encoding and the encoding. *)
val (pf_valid | n, c0, c1, c2, c3) = encode_utf8_character (u)
(* Verify the encoding. *)
val _ = assertloc (n = 2)
val _ = assertloc (c0 = 0xD0)
val _ = assertloc (c1 = 0x96)
}
fn
decode_CYRILLIC_CAPITAL_LETTER_ZHE () : void =
{
val str = "\xD0\x96\0"
val n = length str
val (c, i) = utf8_decode_next (n, str, i2sz 0)
(* Verify that the decoding is correct. *)
val _ = assertloc (c = 0x0416)
(* Verify that the next index is 2. *)
val _ = assertloc (i = i2sz 2)
}
fn
encode_EURO_SIGN () : void =
{
val u = 0x20AC
(* Return both a proof of valid encoding and the encoding. *)
val (pf_valid | n, c0, c1, c2, c3) = encode_utf8_character (u)
(* Verify the encoding. *)
val _ = assertloc (n = 3)
val _ = assertloc (c0 = 0xE2)
val _ = assertloc (c1 = 0x82)
val _ = assertloc (c2 = 0xAC)
}
fn
decode_EURO_SIGN () : void =
{
val str = "\xE2\x82\xAC\0"
val n = length str
val (c, i) = utf8_decode_next (n, str, i2sz 0)
(* Verify that the decoding is correct. *)
val _ = assertloc (c = 0x20AC)
(* Verify that the next index is 3. *)
val _ = assertloc (i = i2sz 3)
}
fn
encode_MUSICAL_SYMBOL_G_CLEF () : void =
{
val u = 0x1D11E
(* Return both a proof of valid encoding and the encoding. *)
val (pf_valid | n, c0, c1, c2, c3) = encode_utf8_character (u)
(* Verify the encoding. *)
val _ = assertloc (n = 4)
val _ = assertloc (c0 = 0xF0)
val _ = assertloc (c1 = 0x9D)
val _ = assertloc (c2 = 0x84)
val _ = assertloc (c3 = 0x9E)
}
fn
decode_MUSICAL_SYMBOL_G_CLEF () : void =
{
val str = "\xF0\x9D\x84\x9E\0"
val n = length str
val (c, i) = utf8_decode_next (n, str, i2sz 0)
(* Verify that the decoding is correct. *)
val _ = assertloc (c = 0x1D11E)
(* Verify that the next index is 4. *)
val _ = assertloc (i = i2sz 4)
}
implement
main0 () =
begin
encode_LATIN_CAPITAL_LETTER_A ();
decode_LATIN_CAPITAL_LETTER_A ();
encode_LATIN_SMALL_LETTER_O_WITH_DIAERESIS ();
decode_LATIN_SMALL_LETTER_O_WITH_DIAERESIS ();
encode_CYRILLIC_CAPITAL_LETTER_ZHE ();
decode_CYRILLIC_CAPITAL_LETTER_ZHE ();
encode_EURO_SIGN ();
decode_EURO_SIGN ();
encode_MUSICAL_SYMBOL_G_CLEF ();
decode_MUSICAL_SYMBOL_G_CLEF ();
println! ("SUCCESS")
end |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #D | D | import core.stdc.string;
extern(C) bool query(char *data, size_t *length) pure nothrow {
immutable text = "Here am I";
if (*length < text.length) {
*length = 0; // Also clears length.
return false;
} else {
memcpy(data, text.ptr, text.length);
*length = text.length;
return true;
}
} |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #Delphi | Delphi |
function Query(Buffer: PChar; var Size: Int64): LongBool;
const
Text = 'Hello World!';
begin
If not Assigned(Buffer) Then
begin
Size := 0;
Result := False;
Exit;
end;
If Size < Length(Text) Then
begin
Size := 0;
Result := False;
Exit;
end;
Size := Length(Text);
Move(Text[1], Buffer^, Size);
Result := True;
end;
|
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Go | Go | package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://[email protected]",
"https://bob:[email protected]/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64",
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
} |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Bracmat | Bracmat | ( ( encode
= encoded exceptions octet string
. !arg:(?exceptions.?string)
& :?encoded
& @( !string
: ?
( %@?octet ?
& !encoded
( !octet
: ( ~<0:~>9
| ~<A:~>Z
| ~<a:~>z
)
| @(!exceptions:? !octet ?)
& !octet
| "%" d2x$(asc$!octet)
)
: ?encoded
& ~
)
)
| str$!encoded
)
& out$"without exceptions:
"
& out$(encode$(."http://foo bar/"))
& out$(encode$(."mailto:Ivan"))
& out$(encode$(."Aim <[email protected]>"))
& out$(encode$(."mailto:Irma"))
& out$(encode$(."User <[email protected]>"))
& out$(encode$(."http://foo.bar.com/~user-name/_subdir/*~.html"))
& out$"
with RFC 3986 rules:
"
& out$(encode$("-._~"."http://foo bar/"))
& out$(encode$("-._~"."mailto:Ivan"))
& out$(encode$("-._~"."Aim <[email protected]>"))
& out$(encode$("-._~"."mailto:Irma"))
& out$(encode$("-._~"."User <[email protected]>"))
& out$(encode$("-._~"."http://foo.bar.com/~user-name/_subdir/*~.html"))
);
|
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #C | C | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
/* caller responsible for memory */
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http://foo bar/";
char enc[(strlen(url) * 3) + 1];
int i;
for (i = 0; i < 256; i++) {
rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'
? i : 0;
html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'
? i : (i == ' ') ? '+' : 0;
}
encode(url, enc, rfc3986);
puts(enc);
return 0;
} |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #C.2B.2B | C++ | int a; |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | set MyStr = "A string"
set MyInt = 4
set MyFloat = 1.3 |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Cowgol | Cowgol | include "cowgol.coh";
sub print_list(ptr: [uint16], n: uint8) is
while n > 0 loop
print_i16([ptr]);
print_char(' ');
n := n - 1;
ptr := @next ptr;
end loop;
print_nl();
end sub;
const LIMIT := 1000;
var eck: uint16[LIMIT];
MemZero(&eck as [uint8], @bytesof eck);
var i: @indexof eck;
var j: @indexof eck;
i := 0;
while i < LIMIT-1 loop
j := i-1;
while j != -1 loop
if eck[i] == eck[j] then
eck[i+1] := i-j;
break;
end if;
j := j - 1;
end loop;
i := i + 1;
end loop;
print_list(&eck[0], 10);
print_list(&eck[LIMIT-10], 10); |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #D | D | import std.stdio;
void vanEck(int firstIndex, int lastIndex) {
int[int] vanEckMap;
int last = 0;
if (firstIndex == 1) {
writefln("VanEck[%d] = %d", 1, 0);
}
for (int n = 2; n <= lastIndex; n++) {
int vanEck = last in vanEckMap ? n - vanEckMap[last] : 0;
vanEckMap[last] = n;
last = vanEck;
if (n >= firstIndex) {
writefln("VanEck[%d] = %d", n, vanEck);
}
}
}
void main() {
writeln("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
writeln;
writeln("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
} |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Java | Java | import java.util.Arrays;
import java.util.HashSet;
public class VampireNumbers{
private static int numDigits(long num){
return Long.toString(Math.abs(num)).length();
}
private static boolean fangCheck(long orig, long fang1, long fang2){
if(Long.toString(fang1).endsWith("0") && Long.toString(fang2).endsWith("0")) return false;
int origLen = numDigits(orig);
if(numDigits(fang1) != origLen / 2 || numDigits(fang2) != origLen / 2) return false;
byte[] origBytes = Long.toString(orig).getBytes();
byte[] fangBytes = (Long.toString(fang1) + Long.toString(fang2)).getBytes();
Arrays.sort(origBytes);
Arrays.sort(fangBytes);
return Arrays.equals(origBytes, fangBytes);
}
public static void main(String[] args){
HashSet<Long> vamps = new HashSet<Long>();
for(long i = 10; vamps.size() <= 25; i++ ){
if((numDigits(i) % 2) != 0) {i = i * 10 - 1; continue;}
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
vamps.add(i);
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
Long[] nums = {16758243290880L, 24959017348650L, 14593825548650L};
for(Long i : nums){
for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){
if(i % fang1 == 0){
long fang2 = i / fang1;
if(fangCheck(i, fang1, fang2) && fang1 <= fang2){
System.out.println(i + ": [" + fang1 + ", " + fang2 +"]");
}
}
}
}
}
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Java | Java | public static void printAll(Object... things){
// "things" is an Object[]
for(Object i:things){
System.out.println(i);
}
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #JavaScript | JavaScript | function printAll() {
for (var i=0; i<arguments.length; i++)
print(arguments[i])
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!"); |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Toka | Toka | char-size .
cell-size . |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT,{}
string="somerandomstring"
size=SIZE(string)
length=LENGTH(string)
PRINT "string: ",string
PRINT "has size: ",size
PRINT "and length: ",length
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #TXR | TXR | 1> (prof 1)
(1 0 0 0) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #UNIX_Shell | UNIX Shell | # In the shell all variables are stored as strings, so we use the same technique
# as for finding the length of a string:
greeting='Hello, world!'
greetinglength=`printf '%s' "$greeting" | wc -c`
echo "The greeting is $greetinglength characters in length" |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Ursala | Ursala | #import std
#cast %nL
examples = <weight 'hello',mpfr..prec 1.0E+0> |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #PowerShell | PowerShell | $V1 = New-Object System.Windows.Vector ( 2.5, 3.4 )
$V2 = New-Object System.Windows.Vector ( -6, 2 )
$V1
$V2
$V1 + $V2
$V1 - $V2
$V1 * 3
$V1 / 8 |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Processing | Processing | PVector v1 = new PVector(5, 7);
PVector v2 = new PVector(2, 3);
println(v1.x, v1.y, v1.mag(), v1.heading(),'\n');
// static methods
println(PVector.add(v1, v2));
println(PVector.sub(v1, v2));
println(PVector.mult(v1, 11));
println(PVector.div(v1, 2), '\n');
// object methods
println(v1.sub(v1));
println(v1.add(v2));
println(v1.mult(10));
println(v1.div(10)); |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #Python | Python | '''Vigenere encryption and decryption'''
from itertools import starmap, cycle
def encrypt(message, key):
'''Vigenere encryption of message using key.'''
# Converted to uppercase.
# Non-alpha characters stripped out.
message = filter(str.isalpha, message.upper())
def enc(c, k):
'''Single letter encryption.'''
return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))
return ''.join(starmap(enc, zip(message, cycle(key))))
def decrypt(message, key):
'''Vigenere decryption of message using key.'''
def dec(c, k):
'''Single letter decryption.'''
return chr(((ord(c) - ord(k) - 2 * ord('A')) % 26) + ord('A'))
return ''.join(starmap(dec, zip(message, cycle(key))))
def main():
'''Demonstration'''
text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (
'the claws that catch!'
)
key = 'VIGENERECIPHER'
encr = encrypt(text, key)
decr = decrypt(encr, key)
print(text)
print(encr)
print(decr)
if __name__ == '__main__':
main()
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #zkl | zkl | d:=File.globular("..","s*.zkl") |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Zsh | Zsh | setopt GLOB_DOTS
print -l -- **/*.txt |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #D | D | import std.stdio, std.conv, std.numeric;
struct V3 {
union {
immutable struct { double x, y, z; }
immutable double[3] v;
}
double dot(in V3 rhs) const pure nothrow /*@safe*/ @nogc {
return dotProduct(v, rhs.v);
}
V3 cross(in V3 rhs) const pure nothrow @safe @nogc {
return V3(y * rhs.z - z * rhs.y,
z * rhs.x - x * rhs.z,
x * rhs.y - y * rhs.x);
}
string toString() const { return v.text; }
}
double scalarTriple(in V3 a, in V3 b, in V3 c) /*@safe*/ pure nothrow {
return a.dot(b.cross(c));
// function vector_products.V3.cross (const(V3) rhs) immutable
// is not callable using argument types (const(V3)) const
}
V3 vectorTriple(in V3 a, in V3 b, in V3 c) @safe pure nothrow @nogc {
return a.cross(b.cross(c));
}
void main() {
immutable V3 a = {3, 4, 5},
b = {4, 3, 5},
c = {-5, -12, -13};
writeln("a = ", a);
writeln("b = ", b);
writeln("c = ", c);
writeln("a . b = ", a.dot(b));
writeln("a x b = ", a.cross(b));
writeln("a . (b x c) = ", scalarTriple(a, b, c));
writeln("a x (b x c) = ", vectorTriple(a, b, c));
} |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Go | Go | package main
import "regexp"
var r = regexp.MustCompile(`^[A-Z]{2}[A-Z0-9]{9}\d$`)
var inc = [2][10]int{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 2, 4, 6, 8, 1, 3, 5, 7, 9},
}
func ValidISIN(n string) bool {
if !r.MatchString(n) {
return false
}
var sum, p int
for i := 10; i >= 0; i-- {
p = 1 - p
if d := n[i]; d < 'A' {
sum += inc[p][d-'0']
} else {
d -= 'A'
sum += inc[p][d%10]
p = 1 - p
sum += inc[p][d/10+1]
}
}
sum += int(n[11] - '0')
return sum%10 == 0
} |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #ERRE | ERRE | PROGRAM VAN_DER_CORPUT
!
! for rosettacode.org
!
PROCEDURE VDC(N%,B%->RES)
LOCAL V,S%
S%=1
WHILE N%>0 DO
S%*=B%
V+=(N% MOD B%)/S%
N%=N% DIV B%
END WHILE
RES=V
END PROCEDURE
BEGIN
FOR BASE%=2 TO 5 DO
PRINT("Base";STR$(BASE%);":")
FOR NUMBER%=0 TO 9 DO
VDC(NUMBER%,BASE%->RES)
WRITE("#.##### ";RES;)
END FOR
PRINT
END FOR
END PROGRAM |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Euphoria | Euphoria | function vdc(integer n, atom base)
atom vdc, denom, rem
vdc = 0
denom = 1
while n do
denom *= base
rem = remainder(n,base)
n = floor(n/base)
vdc += rem / denom
end while
return vdc
end function
for i = 2 to 5 do
printf(1,"Base %d\n",i)
for j = 0 to 9 do
printf(1,"%g ",vdc(j,i))
end for
puts(1,"\n\n")
end for |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #AWK | AWK |
# syntax:
awk '
BEGIN {
str = "http%3A%2F%2Ffoo%20bar%2F" # "http://foo bar/"
printf("%s\n",str)
len=length(str)
for (i=1;i<=len;i++) {
if ( substr(str,i,1) == "%") {
L = substr(str,1,i-1) # chars to left of "%"
M = substr(str,i+1,2) # 2 chars to right of "%"
R = substr(str,i+3) # chars to right of "%xx"
str = sprintf("%s%c%s",L,hex2dec(M),R)
}
}
printf("%s\n",str)
exit(0)
}
function hex2dec(s, num) {
num = index("0123456789ABCDEF",toupper(substr(s,length(s)))) - 1
sub(/.$/,"",s)
return num + (length(s) ? 16*hex2dec(s) : 0)
} '
|
http://rosettacode.org/wiki/Update_a_configuration_file | Update a configuration file | We have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.
# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# How many bananas we have
NUMBEROFBANANAS 48
The task is to manipulate the configuration file as follows:
Disable the needspeeling option (using a semicolon prefix)
Enable the seedsremoved option by removing the semicolon and any leading whitespace
Change the numberofbananas parameter to 1024
Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000
Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case.
Options should always be disabled by prefixing them with a semicolon.
Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file.
If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry.
For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.)
The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons).
Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single
space, and any non-ASCII extended characters, tabs characters, or control codes
(other than end of line markers), should also be removed.
Related tasks
Read a configuration file
| #AutoHotkey | AutoHotkey | ; Author: AlephX, Aug 17 2011
data = %A_scriptdir%\rosettaconfig.txt
outdata = %A_scriptdir%\rosettaconfig.tmp
FileDelete, %outdata%
NUMBEROFBANANAS := 1024
numberofstrawberries := 560
NEEDSPEELING = "0"
FAVOURITEFRUIT := "bananas"
SEEDSREMOVED = "1"
BOOL0 = "0"
BOOL1 = "1"
NUMBER1 := 1
number0 := 0
STRINGA := "string here"
parameters = bool0|bool1|NUMBER1|number0|stringa|NEEDSPEELING|seedsremoved|numberofbananas|numberofstrawberries
Loop, Read, %data%, %outdata%
{
if (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "")
{
Line := A_LoopReadLine
}
else
{
if instr(A_LoopReadLine, ";") == 1
{
parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "")
parametervalue = %parameter%
value := %parametervalue%
if value == 0
Line := A_loopReadLine
else
Line := Parameter
}
else
{
parameter := RegExReplace(A_LoopReadLine, "^[ \s]+|[ \s]+$", "")
if instr(parameter, A_Space)
parameter := substr(parameter, 1, instr(parameter, A_Space)-1)
if instr(parameters, parameter) > 0
{
parametervalue = %parameter%
value := %parametervalue%
if (value = chr(34) . "0" . chr(34))
Line := "; " . Parameter
else
{
if (value = chr(34) . "1" . chr(34))
Line := Parameter
else
Line = %parametervalue% %value%
}
}
else
Line := A_LoopReadLine
}
}
StringReplace, parameters, parameters, %parametervalue%,,
StringReplace, parameters, parameters,||,|
FileAppend, %Line%`n
}
Loop, parse, parameters,|
{
if (A_Loopfield <> "")
{
StringUpper, parameter, A_LoopField
parametervalue = %parameter%
value := %parametervalue%
if (value = chr(34) . "0" . chr(34))
Line := "; " . parameter
else
{
if (value = chr(34) . "1" . chr(34))
Line := parameter
else
Line = %parametervalue% %value%
}
FileAppend, %Line%`n, %outdata%
}
}
FileCopy, %A_scriptdir%\rosettaconfig.tmp, %A_scriptdir%\rosettaconfig.txt, 1 |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Arturo | Arturo | str: input "Enter a string: "
num: to :integer input "Enter an integer: "
print ["Got:" str "," num] |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #AutoHotkey | AutoHotkey | DllCall("AllocConsole")
FileAppend, please type something`n, CONOUT$
FileReadLine, line, CONIN$, 1
msgbox % line
FileAppend, please type '75000'`n, CONOUT$
FileReadLine, line, CONIN$, 1
msgbox % line |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #AppleScript | AppleScript | set input to text returned of (display dialog "Enter text:" default answer "") |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #AutoHotkey | AutoHotkey | InputBox, String, Input, Enter a string:
InputBox, Int, Input, Enter an int:
Msgbox, You entered "%String%" and "%Int%" |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #AutoHotkey | AutoHotkey | Encode_UTF(hex){
Bytes := hex>=0x10000 ? 4 : hex>=0x0800 ? 3 : hex>=0x0080 ? 2 : hex>=0x0001 ? 1 : 0
Prefix := [0, 0xC0, 0xE0, 0xF0]
loop % Bytes {
if (A_Index < Bytes)
UTFCode := Format("{:X}", (hex&0x3F) + 0x80) . UTFCode ; 3F=00111111, 80=10000000
else
UTFCode := Format("{:X}", hex + Prefix[Bytes]) . UTFCode ; C0=11000000, E0=11100000, F0=11110000
hex := hex>>6
}
return "0x" UTFCode
}
;----------------------------------------------------------------------------------------
Decode_UTF(hex){
Bytes := hex>=0x10000 ? 4 : hex>=0x0800 ? 3 : hex>=0x0080 ? 2 : hex>=0x0001 ? 1 : 0
bin := ConvertBase(16, 2, hex)
loop, % Bytes {
B := SubStr(bin, -7)
if Bytes > 1
B := LTrim(B, 1) , B := StrReplace(B, 0,,, 1)
bin := SubStr(bin, 1, StrLen(bin)-8)
Uni := B . Uni
}
return "0x" ConvertBase(2, 16, Uni)
}
;----------------------------------------------------------------------------------------
; www.autohotkey.com/boards/viewtopic.php?f=6&t=3607#p18985
ConvertBase(InputBase, OutputBase, number){
static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
static v := A_IsUnicode ? "_i64tow" : "_i64toa"
VarSetCapacity(s, 65, 0)
value := DllCall("msvcrt.dll\" u, "Str", number, "UInt", 0, "UInt", InputBase, "CDECL Int64")
DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
return s
} |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #Fortran | Fortran |
!-----------------------------------------------------------------------
!Function
!-----------------------------------------------------------------------
function fortran_query(data, length) result(answer) bind(c, name='Query')
use, intrinsic :: iso_c_binding, only: c_char, c_int, c_size_t, c_null_char
implicit none
character(len=1,kind=c_char), dimension(length), intent(inout) :: data
integer(c_size_t), intent(inout) :: length
integer(c_int) :: answer
answer = 0
if(length<10) return
data = transfer("Here I am"//c_null_char, data)
length = 10_c_size_t
answer = 1
end function fortran_query
|
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #Go | Go | #include <stdio.h>
#include "_cgo_export.h"
void Run()
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
... |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Groovy | Groovy | import java.net.URI
[
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
].each { String url ->
// magic happens here
URI u = url.toURI()
// Results displayed here
println """
|Parsing $url
| scheme = ${u.scheme}
| domain = ${u.host}
| port = ${(u.port + 1) ? u.port : 'default' }
| path = ${u.path ?: u.schemeSpecificPart}
| query = ${u.query}
| fragment = ${u.fragment}""".stripMargin()
} |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Haskell | Haskell | module Main (main) where
import Data.Foldable (for_)
import Network.URI
( URI
, URIAuth
, parseURI
, uriAuthority
, uriFragment
, uriPath
, uriPort
, uriQuery
, uriRegName
, uriScheme
, uriUserInfo
)
uriStrings :: [String]
uriStrings =
[ "https://bob:[email protected]/place"
, "foo://example.com:8042/over/there?name=ferret#nose"
, "urn:example:animal:ferret:nose"
, "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"
, "ftp://ftp.is.co.za/rfc/rfc1808.txt"
, "http://www.ietf.org/rfc/rfc2396.txt#header1"
, "ldap://[2001:db8::7]/c=GB?objectClass?one"
, "mailto:[email protected]"
, "news:comp.infosystems.www.servers.unix"
, "tel:+1-816-555-1212"
, "telnet://192.0.2.16:80/"
, "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
]
trimmedUriScheme :: URI -> String
trimmedUriScheme = init . uriScheme
trimmedUriUserInfo :: URIAuth -> Maybe String
trimmedUriUserInfo uriAuth =
case uriUserInfo uriAuth of
[] -> Nothing
userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing
trimmedUriPath :: URI -> String
trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p
trimmedUriQuery :: URI -> Maybe String
trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing
trimmedUriFragment :: URI -> Maybe String
trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing
main :: IO ()
main = do
for_ uriStrings $ \uriString -> do
case parseURI uriString of
Nothing -> putStrLn $ "Could not parse" ++ uriString
Just uri -> do
putStrLn uriString
putStrLn $ " scheme = " ++ trimmedUriScheme uri
case uriAuthority uri of
Nothing -> return ()
Just uriAuth -> do
case trimmedUriUserInfo uriAuth of
Nothing -> return ()
Just userInfo -> putStrLn $ " user-info = " ++ userInfo
putStrLn $ " domain = " ++ uriRegName uriAuth
putStrLn $ " port = " ++ uriPort uriAuth
putStrLn $ " path = " ++ trimmedUriPath uri
case trimmedUriQuery uri of
Nothing -> return ()
Just query -> putStrLn $ " query = " ++ query
case trimmedUriFragment uri of
Nothing -> return ()
Just fragment -> putStrLn $ " fragment = " ++ fragment
putStrLn "" |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #C.23 | C# | using System;
namespace URLEncode
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Encode("http://foo bar/"));
}
private static string Encode(string uri)
{
return Uri.EscapeDataString(uri);
}
}
} |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #C.2B.2B | C++ | #include <QByteArray>
#include <iostream>
int main( ) {
QByteArray text ( "http://foo bar/" ) ;
QByteArray encoded( text.toPercentEncoding( ) ) ;
std::cout << encoded.data( ) << '\n' ;
return 0 ;
} |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #ChucK | ChucK | int a; |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Clojure | Clojure | (declare foo) |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Delphi | Delphi | /* Fill array with Van Eck sequence */
proc nonrec make_eck([*] word eck) void:
int i, j, max;
max := dim(eck,1)-1;
for i from 0 upto max do eck[i] := 0 od;
for i from 0 upto max-1 do
j := i - 1;
while j >= 0 and eck[i] ~= eck[j] do
j := j - 1
od;
if j >= 0 then
eck[i+1] := i - j
fi
od
corp
/* Print eck[0..9] and eck[990..999] */
proc nonrec main() void:
word i;
[1000] word eck;
make_eck(eck);
for i from 0 upto 9 do write(eck[i]:4) od;
writeln();
for i from 990 upto 999 do write(eck[i]:4) od;
writeln()
corp |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Draco | Draco | /* Fill array with Van Eck sequence */
proc nonrec make_eck([*] word eck) void:
int i, j, max;
max := dim(eck,1)-1;
for i from 0 upto max do eck[i] := 0 od;
for i from 0 upto max-1 do
j := i - 1;
while j >= 0 and eck[i] ~= eck[j] do
j := j - 1
od;
if j >= 0 then
eck[i+1] := i - j
fi
od
corp
/* Print eck[0..9] and eck[990..999] */
proc nonrec main() void:
word i;
[1000] word eck;
make_eck(eck);
for i from 0 upto 9 do write(eck[i]:4) od;
writeln();
for i from 990 upto 999 do write(eck[i]:4) od;
writeln()
corp |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #jq | jq | def count(s): reduce s as $x (0; .+1);
# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# Output: a possibly empty array of pairs
def factor_pairs:
. as $n
| ($n / (10 | power($n|tostring|length / 2) - 1)) as $first
| [range($first|floor; 1 + ($n | sqrt)) | select(($n % .) == 0) | [., $n / .] ] ;
# Output: a stream
def vampire_factors:
def es: tostring|explode;
. as $n
| tostring as $s
| ($s|length) as $nlen
| if ($nlen % 2) == 1 then []
else ($nlen / 2 ) as $half
| [factor_pairs[]
| select(. as [$a, $b]
| ($a|tostring|length) == $half and ($b|tostring|length) == $half
and count($a, $b | select(.%10 == 0)) != 2
and ((($a|es) + ($b|es)) | sort) == ($n|es|sort) ) ]
end ;
def task1($n):
limit($n; range(1; infinite)
| . as $i
| vampire_factors
| select(length>0)
| "\($i):\t\(.)" );
def task2:
16758243290880, 24959017348650, 14593825548650
| vampire_factors as $vf
| if $vf|length == 0
then "\(.) is not a vampire number!"
else "\(.):\t\($vf)"
end;
task1(25),
"",
task2 |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Julia | Julia |
function divisors{T<:Integer}(n::T)
!isprime(n) || return [one(T), n]
d = [one(T)]
for (k, v) in factor(n)
e = T[k^i for i in 1:v]
append!(d, vec([i*j for i in d, j in e]))
end
sort(d)
end
function vampirefangs{T<:Integer}(n::T)
fangs = T[]
isvampire = false
vdcnt = ndigits(n)
fdcnt = vdcnt>>1
iseven(vdcnt) || return (isvampire, fangs)
!isprime(n) || return (isvampire, fangs)
vdigs = sort(digits(n))
d = divisors(n)
len = length(d)
len = iseven(len) ? len>>1 : len>>1 + 1
for f in d[1:len]
ndigits(f) == fdcnt || continue
g = div(n, f)
f%10!=0 || g%10!=0 || continue
sort([digits(f), digits(g)]) == vdigs || continue
isvampire = true
append!(fangs, [f, g])
end
if isvampire
fangs = reshape(fangs, (2,length(fangs)>>1))'
end
return (isvampire, fangs)
end
|
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #jq | jq | def demo: .[]; |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Julia | Julia |
julia> print_each(X...) = for x in X; println(x); end
julia> print_each(1, "hello", 23.4)
1
hello
23.4
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Vala | Vala | void main(){
/* you can replace the int below with any of the vala supported datatypes
see the vala documentation for valid datatypes.
*/
print(@"$(sizeof(int))\n");
} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Vlang | Vlang | sizeof(i64) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Wren | Wren | print frnfn_size("uint8") //1
print frnfn_size("int8") //1
print frnfn_size("uint16") //2
print frnfn_size("int16") //2
print frnfn_size("uint32") //4
print frnfn_size("int32") //4
print frnfn_size("uint64") //8
print frnfn_size("int64") //8
print frnfn_size("float") //4
print frnfn_size("double") //8
print frnfn_size("char") //1
print frnfn_size("int") //4
print frnfn_size("short") //2 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Yabasic | Yabasic | print frnfn_size("uint8") //1
print frnfn_size("int8") //1
print frnfn_size("uint16") //2
print frnfn_size("int16") //2
print frnfn_size("uint32") //4
print frnfn_size("int32") //4
print frnfn_size("uint64") //8
print frnfn_size("int64") //8
print frnfn_size("float") //4
print frnfn_size("double") //8
print frnfn_size("char") //1
print frnfn_size("int") //4
print frnfn_size("short") //2 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #XPL0 | XPL0 | include c:\cxpl\codes;
int Size;
int A, B;
real X, Y;
[Size:= addr B - addr A;
IntOut(0, Size); CrLf(0);
Size:= addr Y - addr X;
IntOut(0, Size); CrLf(0);
] |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Python | Python | class Vector:
def __init__(self,m,value):
self.m = m
self.value = value
self.angle = math.degrees(math.atan(self.m))
self.x = self.value * math.sin(math.radians(self.angle))
self.y = self.value * math.cos(math.radians(self.angle))
def __add__(self,vector):
"""
>>> Vector(1,10) + Vector(1,2)
Vector:
- Angular coefficient: 1.0
- Angle: 45.0 degrees
- Value: 12.0
- X component: 8.49
- Y component: 8.49
"""
final_x = self.x + vector.x
final_y = self.y + vector.y
final_value = pytagoras(final_x,final_y)
final_m = final_y / final_x
return Vector(final_m,final_value)
def __neg__(self):
return Vector(self.m,-self.value)
def __sub__(self,vector):
return self + (- vector)
def __mul__(self,scalar):
"""
>>> Vector(4,5) * 2
Vector:
- Angular coefficient: 4
- Angle: 75.96 degrees
- Value: 10
- X component: 9.7
- Y component: 2.43
"""
return Vector(self.m,self.value*scalar)
def __div__(self,scalar):
return self * (1 / scalar)
def __repr__(self):
"""
Returns a nicely formatted list of the properties of the Vector.
>>> Vector(1,10)
Vector:
- Angular coefficient: 1
- Angle: 45.0 degrees
- Value: 10
- X component: 7.07
- Y component: 7.07
"""
return """Vector:
- Angular coefficient: {}
- Angle: {} degrees
- Value: {}
- X component: {}
- Y component: {}""".format(self.m.__round__(2),
self.angle.__round__(2),
self.value.__round__(2),
self.x.__round__(2),
self.y.__round__(2)) |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #Quackery | Quackery | [ [] swap witheach
[ upper
dup char A char Z 1+ within
iff join else drop ] ] is onlycaps ( $ --> $ )
[ onlycaps
[] swap witheach
[ char A - join ] ] is cipherdisk ( $ --> [ )
[ [] swap witheach
[ 26 swap - join ] ] is deciphering ( [ --> [ )
[ behead tuck join swap ] is nextkey ( [ --> [ n )
[ dip nextkey + dup
char Z > if [ 26 - ] ] is encryptchar ( [ c --> [ c )
[ $ "" swap rot
onlycaps witheach
[ encryptchar
swap dip join ]
drop ] is vigenere ( $ [ --> $ )
[ cipherdisk vigenere ] is encrypt ( $ $ --> $ )
[ cipherdisk deciphering vigenere ] is decrypt ( $ $ --> $ )
$ "If you reveal your secrets to the wind, you should "
$ "not blame the wind for revealing them to the trees." join
say "Encrypted: " $ "Kahlil Gibran" encrypt dup echo$ cr
say "Decrypted: " $ "Kahlil Gibran" decrypt echo$ |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #R | R | mod1 = function(v, n)
# mod1(1:20, 6) => 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2
((v - 1) %% n) + 1
str2ints = function(s)
as.integer(Filter(Negate(is.na),
factor(levels = LETTERS, strsplit(toupper(s), "")[[1]])))
vigen = function(input, key, decrypt = F)
{input = str2ints(input)
key = rep(str2ints(key), len = length(input)) - 1
paste(collapse = "", LETTERS[
mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}
message(vigen("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher"))
# WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
# BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Delphi | Delphi |
(lib 'math)
(define (scalar-triple-product a b c)
(dot-product a (cross-product b c)))
(define (vector-triple-product a b c)
(cross-product a (cross-product b c)))
(define a #(3 4 5))
(define b #(4 3 5))
(define c #(-5 -12 -13))
(cross-product a b)
→ #( 5 5 -7)
(dot-product a b)
→ 49
(scalar-triple-product a b c)
→ 6
(vector-triple-product a b c)
→ #( -267 204 -3)
|
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Groovy | Groovy | CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
int checksum(String prefix) {
def digits = prefix.toUpperCase().collect { CHARS.indexOf(it).toString() }.sum()
def groups = digits.collect { CHARS.indexOf(it) }.inject([[], []]) { acc, i -> [acc[1], acc[0] + i] }
def ds = groups[1].collect { (2 * it).toString() }.sum().collect { CHARS.indexOf(it) } + groups[0]
(10 - ds.sum() % 10) % 10
}
assert checksum('AU0000VXGZA') == 3
assert checksum('GB000263494') == 6
assert checksum('US037833100') == 5
assert checksum('US037833107') == 0 |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #F.23 | F# | open System
let vdc n b =
let rec loop n denom acc =
if n > 0l then
let m, remainder = Math.DivRem(n, b)
loop m (denom * b) (acc + (float remainder) / (float (denom * b)))
else acc
loop n 1 0.0
[<EntryPoint>]
let main argv =
printfn "%A" [ for n in 0 .. 9 -> (vdc n 2) ]
printfn "%A" [ for n in 0 .. 9 -> (vdc n 5) ]
0 |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Factor | Factor | USING: formatting fry io kernel math math.functions math.parser
math.ranges sequences ;
IN: rosetta-code.van-der-corput
: vdc ( n base -- x )
[ >base string>digits <reversed> ]
[ nip '[ 1 + neg _ swap ^ * ] ] 2bi map-index sum ;
: vdc-demo ( -- )
2 5 [a,b] [
dup "Base %d: " printf 10 <iota>
[ swap vdc "%-5u " printf ] with each nl
] each ;
MAIN: vdc-demo |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.