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/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt import "/math" for Nums   var rgen = Random.new()   // Box-Muller method from Wikipedia var normal = Fn.new { |mu, sigma| var u1 = rgen.float() var u2 = rgen.float() var mag = sigma * (-2 * u1.log).sqrt var z0 = mag * (2 * Num.pi * u2).cos + mu va...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
len[n_] := RealDigits[n][[2]]; padding = len[Max@ Quotient[inputdata, 10]]; For[i = Min@ Quotient[inputdata, 10],i <= Max@ Quotient[inputdata, 10], i++, (Print[i, If[(padding - len[i]) > 0, (padding - len[i])*" " <> " |", " |"] , StringJoin[(" " <> #) & /@ Map[ToString, #]]])&@ Select[{Quotient[#, 10], Mod[#, 10]} ...
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#jq
jq
def until(cond; update): def _until: if cond then . else (update | _until) end; try _until catch if .== "break" then empty else . end ;   def gcd(a; b): # subfunction expects [a,b] as input # i.e. a ~ .[0] and b ~ .[1] def rgcd: if .[1] == 0 then .[0] else [.[1], .[0] % .[1]] | rgcd end...
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Scala
Scala
def callStack = try { error("exception") } catch { case ex => ex.getStackTrace drop 2 }   def printStackTrace = callStack drop 1 /* don't print ourselves! */ foreach println
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Slate
Slate
slate[1]> d@(Debugger traits) printCurrentStack &limit: limit &stream: out &showLocation: showLocation [ d clone `>> [baseFramePointer: (d interpreter framePointerOf: #printCurrentStack). buildFrames. printBacktrace &limit: limit &stream: out &showLocation: showLocation ] ]. Defining fu...
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Python
Python
def step_up1(): """Straightforward implementation: keep track of how many level we need to ascend, and stop when this count is zero.""" deficit = 1 while deficit > 0: if step(): deficit -= 1 else: deficit += 1
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Quackery
Quackery
[ step if done recurse again ] is step-up
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#R
R
step <- function() { success <- runif(1) > p ## Requires that the "robot" is a variable named "level" level <<- level - 1 + (2 * success) success }
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Action.21
Action!
DEFINE MAXSIZE="200" BYTE ARRAY stack(MAXSIZE) BYTE stacksize=[0]   BYTE FUNC IsEmpty() IF stacksize=0 THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE v) IF stacksize=maxsize THEN PrintE("Error: stack is full!") Break() FI stack(stacksize)=v stacksize==+1 RETURN   BYTE FUNC Pop() IF IsEmpty() T...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Java
Java
import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import...
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#AWK
AWK
  # syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK BEGIN { while (n < 30) { sqpow = ++square ^ 2 if (is_cube(sqpow) == 0) { n++ printf("%4d\n",sqpow) } else { printf("%4d is square and cube\n",sqpow) } } exit(0) } function is_cube(x, i) { for (i=1; i<=x; i...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Fortran
Fortran
program basic_stats implicit none   integer, parameter :: i64 = selected_int_kind(18) integer, parameter :: r64 = selected_real_kind(15) integer(i64), parameter :: samples = 1000000000_i64   real(r64) :: r real(r64) :: mean, stddev real(r64) :: sumn = 0, sumnsq = 0 integer(i64) :: n = 0 integer(i64) ...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Lua
Lua
function squareFree (n) for root = 2, math.sqrt(n) do if n % (root * root) == 0 then return false end end return true end   function run (lo, hi, showValues) io.write("From " .. lo .. " to " .. hi) io.write(showValues and ":\n" or " = ") local count = 0 for i = lo, hi do if squareFree(i) then ...
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#zkl
zkl
var s="foo"; s.append("bar"); //-->new string "foobar", var s unchanged s+="bar"; //-->new string "foobar", var s modifed to new value   s=Data(Void,"foo"); // byte blob/character blob/text editor buffer s.append("bar"); // or s+="bar" s.text; //-->"foobar"
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#zkl
zkl
fcn norm2{ // Box-Muller const PI2=(0.0).pi*2;; rnd:=(0.0).random.fp(1); // random number in [0,1), using partial application r,a:=(-2.0*rnd().log()).sqrt(), PI2*rnd(); return(r*a.cos(), r*a.sin()); // z0,z1 } const N=100000, BINS=12, SIG=3, SCALE=500; var sum=0.0,sumSq=0.0, h=BINS.pump(List(),0); // (0...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#MATLAB_.2F_Octave
MATLAB / Octave
function stem_and_leaf_plot(x,stem_unit,leaf_unit) if nargin < 2, stem_unit = 10; end; if nargin < 3, leaf_unit = 1; else x = leaf_unit*round(x/leaf_unit); end;   stem = floor(x/stem_unit); leaf = mod(x,stem_unit);   for k = min(stem):max(stem) printf('\n%d |',k) printf(' %d' ,sort(l...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#11l
11l
F split(input, delim) V res = ‘’ L(ch) input I !res.empty & ch != res.last res ‘’= delim res ‘’= ch R res   print(split(‘gHHH5YY++///\’, ‘, ’))
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Julia
Julia
using Printf   function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int} rst = Int[1, 1] i = 2 while !f(rst) append!(rst, Int[rst[i] + rst[i-1], rst[i]]) i += 1 end return rst end   println("First 15 elements of Stern-Brocot series:\n", sternbrocot(x -> length(x) ≥ 15)[1:1...
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Smalltalk
Smalltalk
Object subclass: Container [ Container class >> outer: a and: b and: c [ self middle: (a+b) and: (b+c) ] Container class >> middle: x and: y [ self inner: (x*y) ] Container class >> inner: k [ Smalltalk backtrace ] ].   Container outer: 2 and: 3 and: 5.   'Anyway, we continue with it' d...
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Tcl
Tcl
proc printStackTrace {} { puts "Stack trace:" for {set i 1} {$i < [info level]} {incr i} { puts [string repeat " " $i][info level $i] } }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Racket
Racket
#lang racket (define p 0.5001) (define (step) (> p (random)))   (define (step-up n) (cond ((zero? n) 'done) ((step) (step-up (sub1 n))) (else (step-up (add1 n)))))   (step-up 1)
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Raku
Raku
sub step_up { step_up until step; }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#REBOL
REBOL
rebol [ Title: "Stair Climber" URL: http://rosettacode.org/wiki/Stair_Climbing ]   random/seed now   step: does [random/only reduce [yes no]]   ; Iterative solution with symbol stack. No numbers, draws a nifty ; diagram of number of steps to go. This is intended more to ; demonstrate a correct solution:   step_...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ActionScript
ActionScript
var stack:Array = new Array(); stack.push(1); stack.push(2); trace(stack.pop()); // outputs "2" trace(stack.pop()); // outputs "1"
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Julia
Julia
  using MySQL using Nettle # for md5   function connect_db(uri, user, pw, dbname) mydb = mysql_connect(uri, user, pw, dbname)   const command = """CREATE TABLE IF NOT EXISTS users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) UNIQUE KEY NOT NU...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Kotlin
Kotlin
// Version 1.2.41   import java.sql.Connection import java.sql.DriverManager import java.sql.ResultSet import java.security.MessageDigest import java.security.SecureRandom import java.math.BigInteger   class UserManager { private lateinit var dbConnection: Connection   private fun md5(message: String): String {...
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#BASIC
BASIC
10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1 20 IF N>30 THEN END 30 S=Q*Q 40 IF S>C THEN R=R+1: C=R*R*R: GOTO 40 50 IF S<C THEN N=N+1: PRINT S; 60 Q=Q+1 70 GOTO 20
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#BCPL
BCPL
get "libhdr"   let square(x) = x * x let cube(x) = x * x * x   let start() be $( let c, s, seen = 1, 1, 0 while seen < 30 do $( while cube(c) < square(s) do c := c + 1 if square(s) ~= cube(c) then $( writed(square(s), 5) seen := seen + 1 if seen rem 5 = 0 then wrch('*N...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize   Sub basicStats(sampleSize As Integer) If sampleSize < 1 Then Return Dim r(1 To sampleSize) As Double Dim h(0 To 9) As Integer '' all zero by default Dim sum As Double = 0.0 Dim hSum As Integer = 0   ' Generate 'sampleSize' random numbers in the interval [0, 1) ' calculate ...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Maple
Maple
  with(NumberTheory): with(ArrayTools):   squareFree := proc(n::integer) if mul(PrimeFactors(n)) = n then return true; else return false; end if; return true; end proc:   sfintegers := Array([]):   for count from 1 to 145 do if squareFree(count) then Append(sfintegers, count); end if; end do:   print(sfintegers):  ...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Maxima
Maxima
load(descrptive)$   data: [12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, ...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;; Split the string under DE on changing characters, ;;; and store the result at HL. split: ldax d ; Load character from string spcopy: mov m,a ; Store in output cpi '$' ; CP/M string terminator rz ; Stop when the end is reached mov b,a ; Store previous character in B inx d ; Increment input...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#8086_Assembly
8086 Assembly
cpu 8086 org 100h section .text jmp demo ;;; Split the string at DS:SI on changing characters, ;;; and store the result at ES:DI. split: lodsb ; Load character .copy: stosb ; Store in output cmp al,'$' ; Done yet? je .out ; If so, stop. mov ah,al ; Store previous character lodsb ; Get next character cmp a...
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Kotlin
Kotlin
// version 1.1.0   val sbs = mutableListOf(1, 1)   fun sternBrocot(n: Int, fromStart: Boolean = true) { if (n < 4 || (n % 2 != 0)) throw IllegalArgumentException("n must be >= 4 and even") var consider = if (fromStart) 1 else n / 2 - 1 while (true) { val sum = sbs[consider] + sbs[consider - 1] ...
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#VBA
VBA
var func2 = Fn.new { Fiber.abort("Forced error.") }   var func1 = Fn.new { func2.call() }   func1.call()
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Wren
Wren
var func2 = Fn.new { Fiber.abort("Forced error.") }   var func1 = Fn.new { func2.call() }   func1.call()
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#zkl
zkl
fcn f{println("F");vm.stackTrace().println()} fcn g{println("G")} f();g();
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#REXX
REXX
step_up: do while \step(); call step_up end return
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Ring
Ring
  stepup()   func stepup n = 0 while n < 1 if stp() n=n+1 else n= n-1 ok see n + nl end   func stp return 0  
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Ruby
Ruby
def step_up start_position = $position step until ($position == start_position + 1) end   # assumptions about the step function: # - it maintains the current position of the robot "as a side effect" # - the robot is equally likely to step back as to step up def step if rand < 0.5 $position -= 1 p "fall (#...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Ada
Ada
generic type Element_Type is private; package Generic_Stack is type Stack is private; procedure Push (Item : Element_Type; Onto : in out Stack); procedure Pop (Item : out Element_Type; From : in out Stack); function Create return Stack; Stack_Empty_Error : exception; private type Node; type...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["DatabaseLink`"]; connectDb[dbUser_, dbPass_, dbUrl_] := OpenSQLConnection[JDBC["mysql", dbUrl], "Username" -> dbUser, "Password" -> dbPass]; createUser::nameTaken = "The username '`1`' is already taken."; createUser[dbUser_, dbPass_, dbUrl_, user_, pass_] := Module[{db = connectDb[dbUser, dbPass, dbUrl...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Nim
Nim
import db_mysql, nimcrypto, md5, strutils   proc connectDb(user, password: string): DbConn = ## Connect to the database "user_db" and create ## the table "users" if it doesn’t exist yet.   result = open("localhost", user, password, "user_db") result.exec(sql"""CREATE TABLE IF NOT EXISTS users ( ...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Objeck
Objeck
use ODBC; use Encryption;   class SqlTest { @conn : Connection;   function : Main(args : String[]) ~ Nil { SqlTest->New()->Run(); }   New() { @conn := Connection->New("test", "root", "helloworld"); }   method : Run() ~ Nil { CreateUser("objeck", "beer"); AuthenticateUser("objeck", "beer");...
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#BQN
BQN
∘‿5⥊ ((⊢⋆3˙)((¬∊)/⊢)⊢⋆2˙) ↕34
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#C
C
#include <stdio.h> #include <math.h>   int main() { int n = 1, count = 0, sq, cr; for ( ; count < 30; ++n) { sq = n * n; cr = (int)cbrt((double)sq); if (cr * cr * cr != sq) { count++; printf("%d\n", sq); } else { printf("%d is square an...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Go
Go
package main   import ( "fmt" "math" "math/rand" "strings" )   func main() { sample(100) sample(1000) sample(10000) }   func sample(n int) { // generate data d := make([]float64, n) for i := range d { d[i] = rand.Float64() } // show mean, standard deviation va...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
squareFree[n_Integer] := DeleteCases[Last /@ FactorInteger[n], 1] === {}; findSquareFree[n__] := Select[Range[n], squareFree]; findSquareFree[45] findSquareFree[10^9, 10^9 + 145] Length[findSquareFree[10^6]]
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Nanoquery
Nanoquery
def is_square_free(n) if n < 2^2 return true end   for root in range(2, int(sqrt(n))) if (n % (root ^ 2)) = 0 return false end end return true end   def square_free(low, high, show_values) print forma...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Nim
Nim
import tables import math import strutils import algorithm   type StemLeafPlot = ref object leafDigits: int multiplier: int plot: TableRef[int, seq[int]]   proc `$`(s: seq[int]): string = result = "" for item in s: result &= $item & " "   proc `$`(self: StemLeafPlot): string = result = "" var ...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program splitcar64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Action.21
Action!
PROC Split(CHAR ARRAY s) BYTE i CHAR curr,last   i=1 last=s(1) Put('") WHILE i<=s(0) DO curr=s(i) IF curr#last THEN Print(", ") FI Put(curr) last=curr i==+1 OD Put('") RETURN   PROC Test(CHAR ARRAY s) PrintF("Input: ""%S""%E",s) Print("Split: ") Split(s) PutE() PutE()...
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Lua
Lua
-- Task 1 function sternBrocot (n) local sbList, pos, c = {1, 1}, 2 repeat c = sbList[pos] table.insert(sbList, c + sbList[pos - 1]) table.insert(sbList, c) pos = pos + 1 until #sbList >= n return sbList end   -- Return index in table 't' of first value matching 'v' funct...
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Run_BASIC
Run BASIC
  result = stepUp()   Function stepUp() While Not(stepp()) result = stepUp() Wend End Function   Function stepp() stepp = int((Rnd(1) * 2)) print "Robot stepped "+word$("up down",stepp+1) End Function  
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Rust
Rust
fn step_up() { while !step() { step_up(); } }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#SAS
SAS
  %macro step(); %sysfunc(round(%sysfunc(ranuni(0)))) %mend step;  
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked # END CO   MODE OBJNEXTLINK = STRUCT( REF OBJNEXTLINK next, OBJVALUE value # ... etc. required # );   PROC obj nextlink new = REF OBJNEXTLINK: HEAP OBJNEXTLINK;   PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Perl
Perl
use DBI;   # returns a database handle configured to throw an exception on query errors sub connect_db { my ($dbname, $host, $user, $pass) = @_; my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass) or die $DBI::errstr; $db->{RaiseError} = 1; $db }   # if the user was successfully cre...
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#C.23
C#
using System; using System.Collections.Generic; using static System.Console; using static System.Linq.Enumerable;   public static class SquareButNotCube { public static void Main() { var squares = from i in Integers() select i * i; var cubes = from i in Integers() select i * i * i;   foreach...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Haskell
Haskell
import Data.Foldable (foldl') --' import System.Random (randomRs, newStdGen) import Control.Monad (zipWithM_) import System.Environment (getArgs)   intervals :: [(Double, Double)] intervals = map conv [0 .. 9] where xs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] conv s = let [h, l] = take ...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Nim
Nim
import math, strutils     proc sieve(limit: Natural): seq[int] = result = @[2] var c = newSeq[bool](limit + 1) # Composite = true. # No need to process even numbers > 2. var p = 3 while true: let p2 = p * p if p2 > limit: break for i in countup(p2, limit, 2 * p): c[i] = true while true...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#OCaml
OCaml
let unique li = let rec aux acc = function | [] -> (List.rev acc) | x::xs -> if List.mem x acc then aux acc xs else aux (x::acc) xs in aux [] li
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Ada
Ada
  with Ada.Text_IO; procedure Split is procedure Print_Tokens (s : String) is i, j : Integer := s'First; begin loop while j<=s'Last and then s(j)=s(i) loop j := j + 1; end loop; if i/=s'first then Ada.Text_IO.Put (", "); end if; Ada.Text_IO.Put (s(i..j-1)); i := j; exit when j...
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES FRST15 = $20HFIRST 15 NUMBERS ARE*$ VECTOR VALUES FRSTAT = $6HFIRST ,I3,S1,11HAPPEARS AT ,I4*$ VECTOR VALUES NUMBER = $I4*$   DIMENSION STERN(1200) STERN(1) = 1 STERN(2) = 1   R GENERATE FI...
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Scala
Scala
def stepUp { while (! step) stepUp }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Scheme
Scheme
(define (step-up n-steps) (cond ((zero? n-steps) 'done) ((step) (step-up (- n-steps 1))) (else (step-up (+ n-steps 1)))))
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ALGOL_W
ALGOL W
begin  % define a Stack type that will hold StringStackElements  %  % and the StringStackElement type  %  % we would need separate types for other element types  % record StringStack ( reference(StringStackElement) top ); record StringStackElement ( string(8) ...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Phix
Phix
-- demo\rosetta\SQL-based_authentication.exw without js -- (file i/o) include pSQLite.e include md5.exw sqlite3_stmt pAddUser = NULL procedure add_user(sqlite3 db, string name, pw) if pAddUser=NULL then pAddUser = sqlite3_prepare(db,"INSERT INTO users (username,pass_salt,pass_md5) VALUES(:name, :salt, :m...
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#C.2B.2B
C++
#include <iostream> #include <cmath>   int main() { int n = 1; int count = 0; int sq; int cr;   for (; count < 30; ++n) { sq = n * n; cr = cbrt(sq); if (cr * cr * cr != sq) { count++; std::cout << sq << '\n'; } else { std::cout << s...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Hy
Hy
(import [numpy.random [random]] [numpy [mean std]] [matplotlib.pyplot :as plt])   (for [n [100 1000 10000]] (setv v (random n)) (print "Mean:" (mean v) "SD:" (std v)))   (plt.hist (random 1000)) (plt.show)
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Icon_and_Unicon
Icon and Unicon
procedure main(A)   W := 50 # avg width for histogram bar B := 10 # histogram bins if *A = 0 then put(A,100) # 100 if none specified   while N := get(A) do { # once per argument write("\nN=",N)   N := 0 < integer(N) | next # skip if invalid   ...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#OCaml
OCaml
  let squarefree (number: int) : bool = let max = Float.of_int number |> sqrt |> Float.to_int |> (fun x -> x + 2) in let rec inner i number2 = if i == max then true else if number2 mod (i*i) == 0 then false else inner (i+1) number2 in inner 2 number ;;   let...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Perl
Perl
my @data = sort {$a <=> $b} qw( 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 ...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#ALGOL_68
ALGOL 68
BEGIN # returns s with ", " added between each change of character # PROC split on characters = ( STRING s )STRING: IF s = "" THEN # empty string # "" ELSE # allow for 3 times as many characters as in the string # # this would handle a string of ...
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
sb = {1, 1}; Do[ sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]} , {i, 2, 1000} ] Take[sb, 15] Flatten[FirstPosition[sb, #] & /@ Range[10]] First@FirstPosition[sb, 100] AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[1]]
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Seed7
Seed7
const proc: step_up is func begin while not doStep do step_up; end while; end func;
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Sidef
Sidef
func step_up() { while (!step()) { step_up(); } }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Smalltalk
Smalltalk
Smalltalk at: #stepUp put: 0. stepUp := [ [ step value ] whileFalse: [ stepUp value ] ].
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Applesoft_BASIC
Applesoft BASIC
100 DIM STACK$(1000) 110 DATA "(2*A)","PI","","TO BE OR","NOT TO BE" 120 FOR I = 1 TO 5 130 READ ELEMENT$ 140 GOSUB 500_PUSH 150 NEXT 200 GOSUB 400 POP AND PRINT 210 GOSUB 300_EMPTY AND PRINT 220 FOR I = 1 TO 4 230 GOSUB 400 POP AND PRINT 240 NEXT 250 GOSUB 300_EMPTY AND PRINT 260 END 300 GOS...
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#PHP
PHP
  function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) { // Returns a MySQL link identifier (handle) on success // Returns false or dies() on error depending on the setting of parameter $die // Parameter $die configures error handling, setting it any non-false value...
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#11l
11l
os:(‘espeak 'Hello world!'’)
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#Clojure
Clojure
(def squares (map #(* % %) (drop 1 (range)))) (def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range))))   (def squares-not-cubes (filter #(not (= % (first (drop-while (fn [n] (< n %)) square-cubes)))) squares))   (println "Squares but not cubes:") (println (take 30 squares-not-cubes)) (println "Both squares and...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#J
J
require 'stats' (mean,stddev) 1000 ?@$ 0 0.484669 0.287482 (mean,stddev) 10000 ?@$ 0 0.503642 0.290777 (mean,stddev) 100000 ?@$ 0 0.499677 0.288726
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Java
Java
import static java.lang.Math.pow; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import static java.util.stream.IntStream.range;   public class Test { static double[] meanStdDev(double[] numbers) { if (numbers.length == 0) return new double[]{0.0, 0.0};...
http://rosettacode.org/wiki/Square-free_integers
Square-free integers
Task Write a function to test if a number is   square-free. A   square-free   is an integer which is divisible by no perfect square other than   1   (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between...
#Pascal
Pascal
program SquareFree; {$IFDEF FPC} {$MODE DELPHI} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} const //needs 1e10 Byte = 10 Gb maybe someone got 128 Gb :-) nearly linear time BigLimit = 10*1000*1000*1000; TRILLION = 1000*1000*1000*1000; primeLmt = trunc(sqrt(TRILLION+150));   var primes : array of byte; sieve :...
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Phix
Phix
with javascript_semantics procedure leaf_plot(sequence s) s = sort(deep_copy(s)) sequence stem = repeat({},floor(s[$]/10)+1) for i=1 to length(s) do integer j = floor(s[i]/10)+1 stem[j] = deep_copy(stem[j]) & remainder(s[i],10) end for for i=1 to length(stem) do printf(1, "%3...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#ANSI_BASIC
ANSI BASIC
REM >split DECLARE EXTERNAL FUNCTION FN_split$   PRINT FN_split$( "gHHH5YY++///\" ) END   EXTERNAL FUNCTION FN_split$( s$ ) LET c$ = s$(1:1) LET split$ = "" FOR i = 1 TO LEN(s$) LET d$ = s$(i:i) IF d$ <> c$ THEN LET split$ = split$ & ", " LET c$ = d$ END IF LET split$ = split$ & d$ NEXT i LET FN_split$ ...
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#APL
APL
split ← 2↓∘∊(⊂', '),¨(⊢≠¯1⌽⊢)⊂⊢
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Modula-2
Modula-2
MODULE SternBrocot; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   CONST Amount = 1200;   VAR stern: ARRAY [1..Amount] OF CARDINAL; i: CARDINAL;   PROCEDURE GCD(a,b: CARDINAL): CARDINAL; VAR c: CARDINAL; BEGIN WHILE b # 0 DO c := a MOD b; a := b; b := c; END; RETURN a; ...
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Standard_ML
Standard ML
  (* * val step : unit -> bool * This is a stub for a function which returns true if successfully climb a step or false otherwise. *) fun step() = true   (* * val step_up : unit -> bool *) fun step_up() = step() orelse (step_up() andalso step_up())  
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Swift
Swift
func step_up() { while !step() { step_up() } }
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ARM_Assembly
ARM Assembly
STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is put into the program counter. ;This acts as a pop and return command all-in-one. (Most programs use bx lr to return.)
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Python
Python
import mysql.connector import hashlib   import sys import random   DB_HOST = "localhost" DB_USER = "devel" DB_PASS = "devel" DB_NAME = "test"   def connect_db(): ''' Try to connect DB and return DB instance, if not, return False ''' try: return mysql.connector.connect(host=DB_HOST, use...
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#AmigaBASIC
AmigaBASIC
text$=TRANSLATE$("This is an example of speech synthesis.") SAY text$
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#AppleScript
AppleScript
  say "This is an example of speech synthesis"  
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#AutoHotkey
AutoHotkey
talk := ComObjCreate("sapi.spvoice") talk.Speak("This is an example of speech synthesis.")
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#AutoIt
AutoIt
$voice = ObjCreate("SAPI.SpVoice") $voice.Speak("This is an example of speech synthesis.")
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#CLU
CLU
square_not_cube = iter () yields (int) cube_root: int := 1 square_root: int := 1   while true do while cube_root ** 3 < square_root ** 2 do cube_root := cube_root + 1 end if square_root ** 2 ~= cube_root ** 3 then yield(square_root ** 2) end s...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#jq
jq
# Usage: prng N width function prng { cat /dev/urandom | tr -cd '0-9' | fold -w "$2" | head -n "$1" }
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Jsish
Jsish
#!/usr/bin/env jsish "use strict";   function statisticsBasic(args:array|string=void, conf:object=void) { var options = { // Rosetta Code, Statistics/Basic rootdir :'', // Root directory. samples : 0 // Set sample size from options }; var self = { }; parseOpts(self, ...