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/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#AppleScript
AppleScript
  set {table, macList} to {{return}, {"88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D", "FC:FB:FB:01:FA:21", "4c:72:b9:56:fe:bc", "00-14-22-01-23-45"}}   repeat with burger in macList set end of table to do shell script "curl http://api.macvendors.com/" & burger & " && sleep 5 && echo '\n'" & return end repeat   return table as string  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Arturo
Arturo
loop ["FC-A1-3E" "FC:FB:FB:01:FA:21" "BC:5F:F4"] 'mac [ print [mac "=>" read ~"http://api.macvendors.com/|mac|"] pause 1500 ]
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Octave
Octave
#! /usr/bin/octave -qf global width = 200; global height = 200; maxiter = 100;   z0 = 0; global cmax = 1 + i; global cmin = -2 - i;   function cs = pscale(c) global cmax; global cmin; global width; global height; persistent px = (real(cmax-cmin))/width; persistent py = (imag(cmax-cmin))/height; cs = real(cmin) + px*real(c) + i*(imag(cmin) + py*imag(c)); endfunction   ms = zeros(width, height); for x = 0:width-1 for y = 0:height-1 z0 = 0; c = pscale(x+y*i); for ic = 1:maxiter z1 = z0^2 + c; if ( abs(z1) > 2 ) break; endif z0 = z1; endfor ms(x+1, y+1) = ic/maxiter; endfor endfor   saveimage("mandel.ppm", round(ms .* 255).', "ppm");
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Rascal
Rascal
public rel[real, real, real] matrixMultiplication(rel[real x, real y, real v] matrix1, rel[real x, real y, real v] matrix2){ if (max(matrix1.x) == max(matrix2.y)){ p = {<x1,y1,x2,y2, v1*v2> | <x1,y1,v1> <- matrix1, <x2,y2,v2> <- matrix2};   result = {}; for (y <- matrix1.y){ for (x <- matrix2.x){ v = (0.0 | it + v | <x1, y1, x2, y2, v> <- p, x==x2 && y==y1, x1==y2 && y2==x1); result += <x,y,v>; } } return result; } else throw "Matrix sizes do not match.";   //a matrix, given by a relation of the x-coordinate, y-coordinate and value. public rel[real x, real y, real v] matrixA = { <0.0,0.0,12.0>, <0.0,1.0, 6.0>, <0.0,2.0,-4.0>, <1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, <2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> };
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Rascal
Rascal
public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){ return {<y, x, v> | <x, y, v> <- matrix}; }   //a matrix public rel[real x, real y, real v] matrixA = { <0.0,0.0,12.0>, <0.0,1.0, 6.0>, <0.0,2.0,-4.0>, <1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, <2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> };
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#AutoHotkey
AutoHotkey
macLookup(MAC){ WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1") WebRequest.Open("GET", "http://api.macvendors.com/" MAC) WebRequest.Send() return WebRequest.ResponseText }
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#BaCon
BaCon
OPTION TLS TRUE   website$ = "api.macvendors.com" mac$ = "b0:52:16:d0:3c:fb"   OPEN website$ & ":443" FOR NETWORK AS mynet SEND "GET /" & mac$ & " HTTP/1.1\r\nHost: " & website$ & "\r\n\r\n" TO mynet RECEIVE info$ FROM mynet CLOSE NETWORK mynet   PRINT TOKEN$(info$, 2, "\r\n\r\n")
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Ol
Ol
  (define x-size 59) (define y-size 21) (define min-im -1) (define max-im 1) (define min-re -2) (define max-re 1)   (define step-x (/ (- max-re min-re) x-size)) (define step-y (/ (- max-im min-im) y-size))   (for-each (lambda (y) (let ((im (+ min-im (* step-y y)))) (for-each (lambda (x) (let*((re (+ min-re (* step-x x))) (zr (inexact re)) (zi (inexact im))) (let loop ((n 0) (zi zi) (zr zr)) (let ((a (* zr zr)) (b (* zi zi))) (cond ((> (+ a b) 4) (display (string (- 62 n)))) ((= n 30) (display (string (- 62 n)))) (else (loop (+ n 1) (+ (* 2 zr zi) im) (- (+ a re) b)))))))) (iota x-size)) (print))) (iota y-size))  
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#REXX
REXX
/*REXX program multiplies two matrices together, displays the matrices and the results. */ x.=; x.1= 1 2 /*╔═══════════════════════════════════╗*/ x.2= 3 4 /*║ As none of the matrix values have ║*/ x.3= 5 6 /*║ a sign, quotes aren't needed. ║*/ x.4= 7 8 /*╚═══════════════════════════════════╝*/ do r=1 while x.r\=='' /*build the "A" matrix from X. numbers.*/ do c=1 while x.r\==''; parse var x.r a.r.c x.r; end /*c*/ end /*r*/ Arows= r - 1 /*adjust the number of rows (DO loop).*/ Acols= c - 1 /* " " " " cols " " .*/ y.=; y.1= 1 2 3 y.2= 4 5 6 do r=1 while y.r\=='' /*build the "B" matrix from Y. numbers.*/ do c=1 while y.r\==''; parse var y.r b.r.c y.r; end /*c*/ end /*r*/ Brows= r - 1 /*adjust the number of rows (DO loop).*/ Bcols= c - 1 /* " " " " cols " " */ w= 0 /*W is max width of an matrix element.*/ c.= 0; do i=1 for Arows /*multiply matrix A and B ───► C */ do j=1 for Bcols do k=1 for Acols; c.i.j= c.i.j + a.i.k*b.k.j; w= max(w, length(c.i.j) ) end /*k*/ /* ↑ */ end /*j*/ /* └────────◄───────────┐ */ end /*i*/ /*max width of the matrix elements─►─┘ */   call showMat 'A', Arows, Acols /*display matrix A ───► the terminal.*/ call showMat 'B', Brows, Bcols /* " " B ───► " " */ call showMat 'C', Arows, Bcols /* " " C ───► " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ showMat: parse arg mat,rows,cols; say; say center(mat 'matrix', cols*(w+1) + 9, "─") do r=1 for rows; _= ' ' do c=1 for cols; _= _ right( value(mat'.'r"."c), w); end; say _ end /*r*/; return
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#REXX
REXX
/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/ @.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08 @.2 = 111 2222 33333 444444 5555555 66666666 777777777 w=0 do row=1 while @.row\=='' do col=1 until @.row==''; parse var @.row A.row.col @.row w=max(w, length(A.row.col) ) /*max width for elements*/ end /*col*/ /*(used to align ouput).*/ end /*row*/ /* [↑] build matrix A from the @ lists*/ row= row-1 /*adjust for DO loop index increment.*/ do j=1 for row /*process each row of the matrix.*/ do k=1 for col /* " " column " " " */ B.k.j= A.j.k /*transpose the A matrix (into B). */ end /*k*/ end /*j*/ call showMat 'A', row, col /*display the A matrix to terminal.*/ call showMat 'B', col, row /* " " B " " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ showMat: arg mat,rows,cols; say; say center( mat 'matrix', (w+1)*cols +4, "─") do r=1 for rows; _= /*newLine*/ do c=1 for cols; _=_ right( value( mat'.'r"."c), w) /*append.*/ end /*c*/ say _ /*1 line.*/ end /*r*/; return
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#C
C
  #include <curl/curl.h> #include <string.h> #include <stdlib.h> #include <stdio.h>   /* Length of http://api.macvendors.com/ */ #define FIXED_LENGTH 16   struct MemoryStruct { char *memory; size_t size; };   static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp;   mem->memory = realloc(mem->memory, mem->size + realsize + 1);   memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0;   return realsize; }   void checkResponse(char* str){ char ref[] = "Vendor not found"; int len = strlen(str),flag = 1,i;   if(len<16) fputs(str,stdout); else{ for(i=0;i<len && i<16;i++) flag = flag && (ref[i]==str[i]);   flag==1?fputs("N/A",stdout):fputs(str,stdout); } }   int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <MAC address>",argV[0]); else{ CURL *curl; int len = strlen(argV[1]); char* str = (char*)malloc((FIXED_LENGTH + len)*sizeof(char)); struct MemoryStruct chunk; CURLcode res;   chunk.memory = malloc(1); chunk.size = 0;   if ((curl = curl_easy_init()) != NULL) { sprintf(str,"http://api.macvendors.com/%s",argV[1]);   curl_easy_setopt(curl, CURLOPT_URL, str); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);   free(str);   res = curl_easy_perform(curl);   if (res == CURLE_OK) { checkResponse(chunk.memory); return EXIT_SUCCESS; }   curl_easy_cleanup(curl); } }   return EXIT_FAILURE; }  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE VARIABLE print_str AS CHAR NO-UNDO INIT ''. DEFINE VARIABLE X1 AS DECIMAL NO-UNDO INIT 50. DEFINE VARIABLE Y1 AS DECIMAL NO-UNDO INIT 21. DEFINE VARIABLE X AS DECIMAL NO-UNDO. DEFINE VARIABLE Y AS DECIMAL NO-UNDO. DEFINE VARIABLE N AS DECIMAL NO-UNDO. DEFINE VARIABLE I3 AS DECIMAL NO-UNDO. DEFINE VARIABLE R3 AS DECIMAL NO-UNDO. DEFINE VARIABLE Z1 AS DECIMAL NO-UNDO. DEFINE VARIABLE Z2 AS DECIMAL NO-UNDO. DEFINE VARIABLE A AS DECIMAL NO-UNDO. DEFINE VARIABLE B AS DECIMAL NO-UNDO. DEFINE VARIABLE I1 AS DECIMAL NO-UNDO INIT -1.0. DEFINE VARIABLE I2 AS DECIMAL NO-UNDO INIT 1.0. DEFINE VARIABLE R1 AS DECIMAL NO-UNDO INIT -2.0. DEFINE VARIABLE R2 AS DECIMAL NO-UNDO INIT 1.0. DEFINE VARIABLE S1 AS DECIMAL NO-UNDO. DEFINE VARIABLE S2 AS DECIMAL NO-UNDO.     S1 = (R2 - R1) / X1. S2 = (I2 - I1) / Y1. DO Y = 0 TO Y1 - 1: I3 = I1 + S2 * Y. DO X = 0 TO X1 - 1: R3 = R1 + S1 * X. Z1 = R3. Z2 = I3. DO N = 0 TO 29: A = Z1 * Z1. B = Z2 * Z2. IF A + B > 4.0 THEN LEAVE. Z2 = 2 * Z1 * Z2 + I3. Z1 = A - B + R3. END. print_str = print_str + CHR(62 - N). END. print_str = print_str + '~n'. END.   OUTPUT TO "C:\Temp\out.txt". MESSAGE print_str. OUTPUT CLOSE.  
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ring
Ring
  load "stdlib.ring" n = 3 C = newlist(n,n) A = [[1,2,3], [4,5,6], [7,8,9]] B = [[1,0,0], [0,1,0], [0,0,1]] for i = 1 to n for j = 1 to n for k = 1 to n C[i][k] += A[i][j] * B[j][k] next next next for i = 1 to n for j = 1 to n see C[i][j] + " " next see nl next  
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Ring
Ring
  load "stdlib.ring" transpose = newlist(5,4) matrix = [[78,19,30,12,36], [49,10,65,42,50], [30,93,24,78,10], [39,68,27,64,29]] for i = 1 to 5 for j = 1 to 4 transpose[i][j] = matrix[j][i] see "" + transpose[i][j] + " " next see nl next  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#C.23
C#
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks;   class Program { static async Task<string> LookupMac(string MacAddress) { var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress)); using (var wc = new HttpClient()) return await wc.GetStringAsync(uri); } static void Main(string[] args) { foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" }) Console.WriteLine(mac + "\t" + LookupMac(mac).Result); Console.ReadLine(); } }
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#C.2B.2B
C++
// This code is based on the example 'Simple HTTP Client' included with // the Boost documentation.   #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ip/tcp.hpp> #include <iostream> #include <string>   bool get_mac_vendor(const std::string& mac, std::string& vendor) { namespace beast = boost::beast; namespace http = beast::http; namespace net = boost::asio; using tcp = net::ip::tcp;   net::io_context ioc; tcp::resolver resolver(ioc); const char* host = "api.macvendors.com";   beast::tcp_stream stream(ioc); stream.connect(resolver.resolve(host, "http"));   http::request<http::string_body> req{http::verb::get, "/" + mac, 10}; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); http::write(stream, req);   beast::flat_buffer buffer; http::response<http::string_body> res; http::read(stream, buffer, res);   bool success = res.result() == http::status::ok; if (success) vendor = res.body();   beast::error_code ec; stream.socket().shutdown(tcp::socket::shutdown_both, ec); if (ec && ec != beast::errc::not_connected) throw beast::system_error{ec};   return success; }   int main(int argc, char** argv) { if (argc != 2 || strlen(argv[1]) == 0) { std::cerr << "usage: " << argv[0] << " MAC-address\n"; return EXIT_FAILURE; } try { std::string vendor; if (get_mac_vendor(argv[1], vendor)) { std::cout << vendor << '\n'; return EXIT_SUCCESS; } else { std::cout << "N/A\n"; } } catch(std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; } return EXIT_FAILURE; }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#PARI.2FGP
PARI/GP
mandelbrot() = { forstep(y=-1, 1, 0.05, forstep(x=-2, 0.5, 0.0315, print1(((c)->my(z=c);for(i=1,20,z=z*z+c;if(abs(z)>2,return(" ")));"#")(x+y*I))); print()); }
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ruby
Ruby
require 'matrix'   Matrix[[1, 2], [3, 4]] * Matrix[[-3, -8, 3], [-2, 1, 4]]
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#RLaB
RLaB
>> m = rand(3,5) 0.41844289 0.476591435 0.75054022 0.226388925 0.963880314 0.91267171 0.941762397 0.464227895 0.693482786 0.203839405 0.261512966 0.157981873 0.26582235 0.11557427 0.0442493069 >> m' 0.41844289 0.91267171 0.261512966 0.476591435 0.941762397 0.157981873 0.75054022 0.464227895 0.26582235 0.226388925 0.693482786 0.11557427 0.963880314 0.203839405 0.0442493069
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Ruby
Ruby
m=[[1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], [5, 25,125, 625]] puts m.transpose
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Common_Lisp
Common Lisp
(quicklisp:quickload :Drakma)  ; or load it in another way   (defun mac-vendor (mac) (check-type mac string "A MAC address as a string") (multiple-value-bind (vendor status) (drakma:http-request (format nil "http://api.macvendors.com/~a" mac)) (if (= 200 status) (format t "~%Vendor is ~a" vendor) (error "~%Not a MAC address: ~a" mac))))  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Delphi
Delphi
  program MAC_Vendor_Lookup;   {$APPTYPE CONSOLE}   uses System.SysUtils, IdHttp;   function macLookUp(mac: string): string; begin Result := ''; with TIdHTTP.Create(nil) do begin try Result := Get('http://api.macvendors.com/' + mac);   except on E: Exception do Writeln(e.Message); end; Free; end; end;   begin Writeln(macLookUp('FC-A1-3E')); sleep(1000); Writeln(macLookUp('FC:FB:FB:01:FA:21')); sleep(1000); Writeln(macLookUp('BC:5F:F4')); readln; end.
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Pascal
Pascal
program mandelbrot;   {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   const ixmax = 800; iymax = 800; cxmin = -2.5; cxmax = 1.5; cymin = -2.0; cymax = 2.0; maxcolorcomponentvalue = 255; maxiteration = 200; escaperadius = 2;   type colortype = record red : byte; green : byte; blue : byte; end;   var ix, iy : integer; cx, cy : real; pixelwidth : real = (cxmax - cxmin) / ixmax; pixelheight : real = (cymax - cymin) / iymax; filename : string = 'new1.ppm'; comment : string = '# '; outfile : textfile; color : colortype; zx, zy : real; zx2, zy2 : real; iteration : integer; er2 : real = (escaperadius * escaperadius);   begin {$I-} assign(outfile, filename); rewrite(outfile); if ioresult <> 0 then begin {$IFDEF FPC} writeln(stderr, 'Unable to open output file: ', filename); {$ELSE} writeln('ERROR: Unable to open output file: ', filename); {$ENDIF} exit; end;   writeln(outfile, 'P6'); writeln(outfile, ' ', comment); writeln(outfile, ' ', ixmax); writeln(outfile, ' ', iymax); writeln(outfile, ' ', maxcolorcomponentvalue);   for iy := 1 to iymax do begin cy := cymin + (iy - 1)*pixelheight; if abs(cy) < pixelheight / 2 then cy := 0.0; for ix := 1 to ixmax do begin cx := cxmin + (ix - 1)*pixelwidth; zx := 0.0; zy := 0.0; zx2 := zx*zx; zy2 := zy*zy; iteration := 0; while (iteration < maxiteration) and (zx2 + zy2 < er2) do begin zy := 2*zx*zy + cy; zx := zx2 - zy2 + cx; zx2 := zx*zx; zy2 := zy*zy; iteration := iteration + 1; end; if iteration = maxiteration then begin color.red := 0; color.green := 0; color.blue := 0; end else begin color.red := 255; color.green := 255; color.blue := 255; end; write(outfile, chr(color.red), chr(color.green), chr(color.blue)); end; end;   close(outfile); end.
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Rust
Rust
  struct Matrix { dat: [[f32; 3]; 3] }   impl Matrix { pub fn mult_m(a: Matrix, b: Matrix) -> Matrix { let mut out = Matrix { dat: [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.] ] };   for i in 0..3{ for j in 0..3 { for k in 0..3 { out.dat[i][j] += a.dat[i][k] * b.dat[k][j]; } } }   out }   pub fn print(self) { for i in 0..3 { for j in 0..3 { print!("{} ", self.dat[i][j]); } print!("\n"); } } }   fn main() { let a = Matrix { dat: [[1., 2., 3.], [4., 5., 6.], [7., 8., 9.] ] };   let b = Matrix { dat: [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] };       let c = Matrix::mult_m(a, b);     c.print(); }    
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Run_BASIC
Run BASIC
mtrx$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10"   print "Transpose of matrix" call DisplayMatrix mtrx$ print " =" MatrixT$ =MatrixTranspose$(mtrx$) call DisplayMatrix MatrixT$   end   function MatrixTranspose$(in$) w = val(word$(in$, 1, ",")) ' swap w and h parameters h = val(word$(in$, 2, ",")) t$ = str$(h); ","; str$(w); "," for i =1 to w for j =1 to h t$ = t$ +word$(in$, 2 +i +(j -1) *w, ",") +"," next j next i MatrixTranspose$ =left$(t$, len(t$) -1) end function   sub DisplayMatrix in$ ' Display looking like a matrix! html "<table border=2>" w = val(word$(in$, 1, ",")) h = val(word$(in$, 2, ",")) for i =0 to h -1 html "<tr align=right>" for j =1 to w term$ = word$(in$, j +2 +i *w, ",") html "<td>";val(term$);"</td>" next j html "</tr>" next i html "</table>" end sub
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Factor
Factor
USING: accessors calendar continuations http.client io kernel sequences threads ;   : mac-vendor ( str -- str ) "http://api.macvendors.com/" prepend [ http-get nip ] [ nip response>> message>> ] recover ;   "FC-A1-3E" "FC:FB:FB:01:FA:21" "10-11-22-33-44-55-66" [ mac-vendor print 1 seconds sleep ] tri@
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#FreeBASIC
FreeBASIC
Function pipeout(Byval s As String = "") Byref As String Var f = Freefile Dim As String tmp Open Pipe s For Input As #f s = "" Do Until Eof(f) Line Input #f, tmp s &= tmp Loop Close #f Return s End Function   Function lookupvendor(webpage As String, mac As String) As String Return pipeout("powershell " + "(Invoke-WebRequest " + webpage + mac + ")") End Function   Dim As String macs(1 To 4) = {"FC-A1-3E","FC:FB:FB:01:FA:21","88:53:2E:67:07:BE","D4:F4:6F:C9:EF:8D"}   For i As Integer = 1 To Ubound(macs) Var d = lookupvendor("api.macvendors.com/", macs(i)) Var e = Instr(d, "RawContent") Print Mid(d, 66, e-66) Next i Sleep  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Perl
Perl
use Math::Complex;   sub mandelbrot { my ($z, $c) = @_[0,0]; for (1 .. 20) { $z = $z * $z + $c; return $_ if abs $z > 2; } }   for (my $y = 1; $y >= -1; $y -= 0.05) { for (my $x = -2; $x <= 0.5; $x += 0.0315) {print mandelbrot($x + $y * i) ? ' ' : '#'} print "\n" }
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#S-lang
S-lang
% Matrix multiplication is a built-in with the S-Lang octothorpe operator. variable A = [1,2,3,4,5,6]; reshape(A, [2,3]); % reshape 1d array to 2 rows, 3 columns printf("A is %S\n", A); print(A);   variable B = [1:6]; % index range, 1 to 6 same as above in A reshape(B, [3,2]); % reshape to 3 rows, 2 columns printf("\nB is %S\n", B); print(B);   printf("\nA # B is %S\n", A#B); print(A#B);   % Multiply binary operator is different, dimensions need to be equal reshape(B, [2,3]); printf("\nA * B is %S (with reshaped B to match A)\n", A*B); print(A*B);
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Rust
Rust
  struct Matrix { dat: [[i32; 3]; 3] }       impl Matrix { pub fn transpose_m(a: Matrix) -> Matrix { let mut out = Matrix { dat: [[0, 0, 0], [0, 0, 0], [0, 0, 0] ] };   for i in 0..3{ for j in 0..3{   out.dat[i][j] = a.dat[j][i]; } }   out }   pub fn print(self) { for i in 0..3 { for j in 0..3 { print!("{} ", self.dat[i][j]); } print!("\n"); } } }   fn main() { let a = Matrix { dat: [[1, 2, 3], [4, 5, 6], [7, 8, 9] ] };   let c = Matrix::transpose_m(a); c.print(); }  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Free_Pascal
Free Pascal
program MACVendorLookup;   uses fphttpclient;   var res: String; begin if paramCount > 0 then begin   With TFPHttpClient.Create(Nil) do try allowRedirect := true; try res := Get('http://api.macvendors.com/' + ParamStr(1)); writeLn(res); except writeLn('N/A'); end; finally Free; end; end; end.
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#6502_Assembly
6502 Assembly
LDA #$07 CLC ADC #$0C RTS
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Phix
Phix
-- -- Mandlebrot set in ascii art demo. -- constant b=" .:,;!/>)|&IH%*#" atom r, i, c, C, z, Z, t, k for y=30 to 0 by -1 do C = y*0.1-1.5 puts(1,'\n') for x=0 to 74 do c = x*0.04-2 z = 0 Z = 0 r = c i = C k = 0 while k<112 do t = z*z-Z*Z+r Z = 2*z*Z+i z = t if z*z+Z*Z>10 then exit end if k += 1 end while puts(1,b[remainder(k,16)+1]) end for end for
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Scala
Scala
def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = { import n._ for (row <- a) yield for(col <- b.transpose) yield row zip col map Function.tupled(_*_) reduceLeft (_+_) }
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Scala
Scala
scala> Array.tabulate(4)(i => Array.tabulate(4)(j => i*4 + j)) res12: Array[Array[Int]] = Array(Array(0, 1, 2, 3), Array(4, 5, 6, 7), Array(8, 9, 10, 11), Array(12, 13, 14, 15))   scala> res12.transpose res13: Array[Array[Int]] = Array(Array(0, 4, 8, 12), Array(1, 5, 9, 13), Array(2, 6, 10, 14), Array(3, 7, 11, 15))   scala> res12 map (_ map ("%2d" format _) mkString " ") mkString "\n" res16: String = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15   scala> res13 map (_ map ("%2d" format _) mkString " ") mkString "\n" res17: String = 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Go
Go
package main   import ( "net/http" "fmt" "io/ioutil" )   func macLookUp(mac string) (res string){ resp, _ := http.Get("http://api.macvendors.com/" + mac) body, _ := ioutil.ReadAll(resp.Body) res = string(body) return }   func main() { fmt.Println(macLookUp("FC-A1-3E")) fmt.Println(macLookUp("FC:FB:FB:01:FA:21")) fmt.Println(macLookUp("BC:5F:F4")) }  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Haskell
Haskell
#!/usr/bin/env stack {- stack script --resolver lts-9.0 --package bytestring --package http-client --package http-types -}   {-# LANGUAGE MultiWayIf #-}   import Control.Exception (try) import Control.Monad (forM_) import qualified Data.ByteString.Lazy.Char8 as L8 (ByteString, unpack) import Network.HTTP.Client (Manager, parseRequest, httpLbs, responseStatus, responseBody, newManager, defaultManagerSettings, Response, HttpException) import Network.HTTP.Types.Status (statusIsSuccessful, notFound404) import System.Environment (getArgs) import Text.Printf (printf)   fetchURL :: Manager -> String -> IO (Either HttpException (Response L8.ByteString)) fetchURL mgr url = try $ do req <- parseRequest url httpLbs req mgr   lookupMac :: Manager -> String -> IO String lookupMac mgr mac = do eth <- fetchURL mgr $ "http://api.macvendors.com/" ++ mac return $ case eth of Left _ -> "null" Right resp -> let body = responseBody resp status = responseStatus resp in if | status == notFound404 -> "N/A" | not (statusIsSuccessful status) -> "null" | otherwise -> L8.unpack body   main :: IO () main = do args <- getArgs mgr <- newManager defaultManagerSettings forM_ args $ \mac -> do putStr $ printf "%-17s" mac ++ " = " vendor <- lookupMac mgr mac putStrLn vendor
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#68000_Assembly
68000 Assembly
MOVE.B #7,D0 ADD.B #12,D0 RTS
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Action.21
Action!
DEFINE ADC="$6D" DEFINE CLC="$18" DEFINE JSR="$20" DEFINE LDA="$AD" DEFINE RTS="$60" DEFINE STA="$8D"   PROC Main() BYTE ARRAY buf(20) BYTE a=[19],b=[37],s CARD addr   addr=buf Poke(addr,CLC) addr==+1 Poke(addr,LDA) addr==+1 PokeC(addr,@a) addr==+2 Poke(addr,ADC) addr==+1 PokeC(addr,@b) addr==+2 Poke(addr,STA) addr==+1 PokeC(addr,@s) addr==+2 Poke(addr,RTS) addr==+1   [JSR buf] ;run the machine code stored on buf   PrintF("%B+%B=%B%E",a,b,s) RETURN
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#PHP
PHP
$min_x=-2; $max_x=1; $min_y=-1; $max_y=1;   $dim_x=400; $dim_y=300;   $im = @imagecreate($dim_x, $dim_y) or die("Cannot Initialize new GD image stream"); header("Content-Type: image/png"); $black_color = imagecolorallocate($im, 0, 0, 0); $white_color = imagecolorallocate($im, 255, 255, 255);   for($y=0;$y<=$dim_y;$y++) { for($x=0;$x<=$dim_x;$x++) { $c1=$min_x+($max_x-$min_x)/$dim_x*$x; $c2=$min_y+($max_y-$min_y)/$dim_y*$y;   $z1=0; $z2=0;   for($i=0;$i<100;$i++) { $new1=$z1*$z1-$z2*$z2+$c1; $new2=2*$z1*$z2+$c2; $z1=$new1; $z2=$new2; if($z1*$z1+$z2*$z2>=4) { break; } } if($i<100) { imagesetpixel ($im, $x, $y, $white_color); } } }   imagepng($im); imagedestroy($im);  
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Scheme
Scheme
(define (matrix-multiply matrix1 matrix2) (map (lambda (row) (apply map (lambda column (apply + (map * row column))) matrix2)) matrix1))
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Scheme
Scheme
(define (transpose m) (apply map list m))
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: matrix is array array float;   const func matrix: transpose (in matrix: aMatrix) is func result var matrix: transposedMatrix is matrix.value; local var integer: i is 0; var integer: j is 0; begin transposedMatrix := length(aMatrix[1]) times length(aMatrix) times 0.0; for i range 1 to length(aMatrix) do for j range 1 to length(aMatrix[1]) do transposedMatrix[j][i] := aMatrix[i][j]; end for; end for; end func;   const proc: write (in matrix: aMatrix) is func local var integer: line is 0; var integer: column is 0; begin for line range 1 to length(aMatrix) do for column range 1 to length(aMatrix[line]) do write(" " <& aMatrix[line][column] digits 2); end for; writeln; end for; end func;   const matrix: testMatrix is [] ( [] (0.0, 0.1, 0.2, 0.3), [] (0.4, 0.5, 0.6, 0.7), [] (0.8, 0.9, 1.0, 1.1));   const proc: main is func begin writeln("Before Transposition:"); write(testMatrix); writeln; writeln("After Transposition:"); write(transpose(testMatrix)); end func;
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#J
J
require 'web/gethttp' lookupMACvendor=: [: gethttp 'http://api.macvendors.com/'&,
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Java
Java
package com.jamesdonnell.MACVendor;   import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;   /** MAC Vendor Lookup class. * www.JamesDonnell.com * @author James A. Donnell Jr. */ public class Lookup { /** Base URL for API. The API from www.macvendors.com was chosen. */ private static final String baseURL = "http://api.macvendors.com/";   /** Performs lookup on MAC address(es) supplied in arguments. * @param args MAC address(es) to lookup. */ public static void main(String[] args) { for (String arguments : args) System.out.println(arguments + ": " + get(arguments)); }   /** Performs lookup on supplied MAC address. * @param macAddress MAC address to lookup. * @return Manufacturer of MAC address. */ private static String get(String macAddress) { try { StringBuilder result = new StringBuilder(); URL url = new URL(baseURL + macAddress); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } catch (FileNotFoundException e) { // MAC not found return "N/A"; } catch (IOException e) { // Error during lookup, either network or API. return null; } } }
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
V s = [‘It is certain’, ‘It is decidedly so’, ‘Without a doubt’, ‘Yes, definitely’, ‘You may rely on it’, ‘As I see it, yes’, ‘Most likely’, ‘Outlook good’, ‘Signs point to yes’, ‘Yes’, ‘Reply hazy, try again’, ‘Ask again later’, ‘Better not tell you now’, ‘Cannot predict now’, ‘Concentrate and ask again’, ‘Don't bet on it’, ‘My reply is no’, ‘My sources say no’, ‘Outlook not so good’, ‘Very doubtful’]   Set[String] qs   L V question = input(‘Ask your question:’) I question.empty L.break   V answer = random:choice(s)   I question C qs print(‘Your question has already been answered’) E qs.add(question) print(answer)
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Applesoft_BASIC
Applesoft BASIC
POKE768,169:POKE770,24:POKE771,105:POKE773,133:POKE775,96:POKE774,235:POKE769,7:POKE772,12:CALL768:?PEEK(235)
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#AutoHotkey
AutoHotkey
MCode(Var, "8B44240403442408C3") MsgBox, % DllCall(&Var, "Char",7, "Char",12) Var := "" return   ; http://www.autohotkey.com/board/topic/19483-machine-code-functions-bit-wizardry/ MCode(ByRef code, hex) { ; allocate memory and write Machine Code there VarSetCapacity(code, StrLen(hex) // 2) Loop % StrLen(hex) // 2 NumPut("0x" . SubStr(hex, 2 * A_Index - 1, 2), code, A_Index - 1, "Char") }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Picat
Picat
go =>   Width = 90, Height = 50, Limit = 50, foreach(Y in 1..Height) P="", foreach (X in 1..Width) Z=complex(0,0), C=complex(2.5*X/Width-2.0,2.0*Y/Height-1.0), J = 0, while (J < Limit, c_abs(Z)<2.0) Z := c_add(c_mul(Z,Z),C), J := J + 1 end, if J == Limit then P := P ++ "#" else P := P ++ "." end end, printf("%s\n", P) end, nl.   % Operations on complex numbers complex(R,I) = [R,I]. c_add(X,Y) = complex(X[1]+Y[1],X[2]+Y[2]). c_mul(X,Y) = complex(X[1]*Y[1]-X[2]*Y[2],X[1]*Y[2]+X[2]*Y[1]). c_abs(X) = sqrt(X[1]*X[1]+X[2]*X[2]).
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Seed7
Seed7
const type: matrix is array array float;   const func matrix: (in matrix: left) * (in matrix: right) is func result var matrix: result is matrix.value; local var integer: i is 0; var integer: j is 0; var integer: k is 0; var float: accumulator is 0.0; begin if length(left[1]) <> length(right) then raise RANGE_ERROR; else result := length(left) times length(right[1]) times 0.0; for i range 1 to length(left) do for j range 1 to length(right) do accumulator := 0.0; for k range 1 to length(left) do accumulator +:= left[i][k] * right[k][j]; end for; result[i][j] := accumulator; end for; end for; end if; end func;
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Sidef
Sidef
func transpose(matrix) { matrix[0].range.map{|i| matrix.map{_[i]}}; };   var m = [ [1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], [5, 25, 125, 625], ];   transpose(m).each { |row| "%5d" * row.len -> printlnf(row...); }
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#JavaScript
JavaScript
  var mac = "88:53:2E:67:07:BE"; function findmac(){ window.open("http://api.macvendors.com/" + mac); }   findmac();  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Julia
Julia
# v0.6.0   using Requests   function getvendor(addr::String) try get("http://api.macvendors.com/$addr") |> readstring catch e nothing end end   for addr in ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] println("$addr -> ", getvendor(addr)) end
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Kotlin
Kotlin
// version 1.1.2   import java.net.URL   fun lookupVendor(mac: String) = URL("http://api.macvendors.com/" + mac).readText()   fun main(args: Array<String>) { val macs = arrayOf("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D") for (mac in macs) println(lookupVendor(mac)) }
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#8080_Assembly
8080 Assembly
bdos: equ 5 ; CP/M calls puts: equ 9 gets: equ 10 org 100h lxi d,message ; Print message mvi c,puts call bdos question: lxi d,prompt ; Ask for question mvi c,puts call bdos lxi d,bufdef ; Read answer mvi c,gets call bdos lxi d,newline ; Print newline mvi c,puts call bdos lxi h,buf ; XOR the question w/ the RNG state mvi b,20 xorouter: lxi d,xabcdat + 1 mvi c,3 xorinner: ldax d xra m stax d inx d inx h dcr c jnz xorinner dcr b jnz xorouter getrnd: call xabcrand ; Generate random number <20 ani 1fh cpi 20 jnc getrnd inr a mov b,a ; That is the number of the message lxi h,responses ; Skip that many strings mvi a,'$' skipstring: cmp m inx h jnz skipstring dcr b jnz skipstring xchg ; Print the chosen string mvi c,puts call bdos jmp question ; Get another question ;; RNG to make it a little less predictable xabcrand: lxi h,xabcdat inr m  ; X++ mov a,m  ; X, inx h  ; xra m  ; ^ C, inx h  ; xra m  ; ^ A, mov m,a  ; -> A inx h add m  ; + B, mov m,a  ; -> B rar  ; >>1 dcx h xra m  ; ^ A, dcx h add m  ; + C mov m,a  ; -> C ret ;; Strings message: db 'Magic 8 Ball$' newline: db 13,10,'$' prompt: db 13,10,13,10,'What is your question? ' ;; The possible responses responses: db '$It is certain$It is decidedly so$Without a doubt$' db 'Yes, definitely$You may rely on it$As I see it, yes$' db 'Most likely$Outlook good$Signs point to yes$Yes$' db 'Reply hazy, try again$Ask again later$' db 'Better not tell you now$Cannot predict now$' db 'Concentrate and ask again$Don',39,'t bet on it$' db 'My reply is no$My sources say no$Outlook not so good$' db 'Very doubtful$' ;; Variables bufdef: db 60,0 ; 60 = 20*3 buf: equ $ ; question will be XOR'ed with the RNG state xabcdat: equ buf + 60 ; Point RNG data into uninitialized memory, ; to make it more exciting.  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#8086_Assembly
8086 Assembly
  .model small .stack 1024   .data UserRam BYTE 256 DUP(0) xorshift32_state_lo equ UserRam xorshift32_state_hi equ UserRam+2   Ans0 byte "It is certain.",0 Ans1 byte "It is decidedly so.",0 Ans2 byte "Signs point to yes.",0 Ans3 byte "You can rely on it.",0 Ans4 byte "Most likely.",0 Ans5 byte "Cannot predict now.",0 Ans6 byte "Reply hazy, try again.",0 Ans7 byte "Outlook not so good.",0 Ans8 byte "My sources say no.",0 Ans9 byte "Very doubtful.",0 AnsA byte "Without a doubt.",0 AnsB byte "Outlook good.",0 AnsC byte "Ask again later.",0 AnsD byte "Better not tell you now.",0 AnsE byte "Don't count on it.",0 AnsF byte "Yes.",0   AnswerLookup word Ans0,Ans1,Ans2,Ans3,Ans4,Ans5,Ans6,Ans7 word Ans8,Ans9,AnsA,AnsB,AnsC,AnsD,AnsE,AnsF .code   start:   mov ax,@data mov ds,ax   mov ax,@code mov es,ax     CLD ;have LODSB,MOVSB,STOSB,etc. auto-increment   mov ax,03h int 10h ;sets video mode to MS-DOS text mode. Which the program is already in, so this just clears the screen.   mov ah,2Ch int 21h ;returns hour:minute in cx, second:100ths of second in dx mov word ptr [ds:xorshift32_state_lo],dx mov word ptr [ds:xorshift32_state_hi],cx   call doXorshift32 ;uses the above memory locations as input. Do it three times just to mix it up some more call doXorshift32 call doXorshift32   mov ax,word ptr[ds:xorshift32_state_lo] ;get the random output from the RNG and al,0Fh ;keep only the bottom nibble of al, there are only 16 possible messages. mov bx,offset AnswerLookup call XLATW ;translates AX using a table of words as a lookup table. mov si,ax ;use this looked-up value as the source index for our text. call PrintString ;print to the screen   mov ax,4C00h int 21h ;return to DOS   XLATW: ;input: ds:bx = the table you wish to look up ;AL= the raw index into this table as if it were byte data. ;So don't left shift prior to calling this. ;AH is destroyed. SHL AL,1 mov ah,al ;copy AL to AH XLAT ;returns low byte in al inc ah xchg al,ah ;XLAT only works with AL XLAT ;returns high byte in al (old ah) xchg al,ah ;now the word is loaded into ax, big-endian. ret
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#BBC_BASIC
BBC BASIC
REM Claim 9 bytes of memory SYS "GlobalAlloc",0,9 TO code%   REM Poke machine code into it P%=code% [OPT 0 mov EAX, [ESP+4] add EAX, [ESP+8] ret ]   REM Run code SYS code%,7,12 TO result% PRINT result%   REM Free memory SYS "GlobalFree",code% END
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#C
C
#include <stdio.h> #include <sys/mman.h> #include <string.h>   int test (int a, int b) { /* mov EAX, [ESP+4] add EAX, [ESP+8] ret */ char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; void *buf; int c; /* copy code to executable buffer */ buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON,-1,0);   memcpy (buf, code, sizeof(code)); /* run code */ c = ((int (*) (int, int))buf)(a, b); /* free buffer */ munmap (buf, sizeof(code)); return c; }   int main () { printf("%d\n", test(7,12)); return 0; }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#PicoLisp
PicoLisp
(scl 6)   (let Ppm (make (do 300 (link (need 400)))) (for (Y . Row) Ppm (for (X . @) Row (let (ZX 0 ZY 0 CX (*/ (- X 250) 1.0 150) CY (*/ (- Y 150) 1.0 150) C 570) (while (and (> 4.0 (+ (*/ ZX ZX 1.0) (*/ ZY ZY 1.0))) (gt0 C)) (let Tmp (- (*/ ZX ZX 1.0) (*/ ZY ZY 1.0) (- CX)) (setq ZY (+ (*/ 2 ZX ZY 1.0) CY) ZX Tmp ) ) (dec 'C) ) (set (nth Ppm Y X) (list 0 C C)) ) ) ) (out "img.ppm" (prinl "P6") (prinl 400 " " 300) (prinl 255) (for Y Ppm (for X Y (apply wr X))) ) )
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#SequenceL
SequenceL
matmul(A(2), B(2)) [i,j] := let k := 1...size(B); in sum( A[i,k] * B[k,j] );   //Example Use a := [[1, 2], [3, 4]];   b := [[-3, -8, 3], [-2, 1, 4]];   test := matmul(a, b);
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#SPAD
SPAD
(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _ [3, 9, 27, 81],[4, 16, 64, 256], _ [5, 25, 125, 625]]   +1 1 1 1 + | | |2 4 8 16 | | | (1) |3 9 27 81 | | | |4 16 64 256| | | +5 25 125 625+ Type: Matrix(Integer) (2) -> transposedMatrix := transpose(originalMatrix)   +1 2 3 4 5 + | | |1 4 9 16 25 | (2) | | |1 8 27 64 125| | | +1 16 81 256 625+ Type: Matrix(Integer)
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Lua
Lua
-- Requires LuaSocket extension by Lua -- Created by James A. Donnell Jr. -- www.JamesDonnell.com   local baseURL = "http://api.macvendors.com/"   local function lookup(macAddress) http = require "socket.http" result, statuscode, content = http.request(baseURL .. macAddress) return result end   local macAddress = "FC-A1-3E-2A-1C-33" print(lookup(macAddress))
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { httpGet$=lambda$ (url$, timeout=500)->{ declare htmldoc "WinHttp.WinHttpRequest.5.1" Method htmldoc "SetTimeouts", timeout, timeout, timeout, timeout Method htmldoc "open","GET", url$, false Method htmldoc "setRequestHeader","Content-Type", "application/x-www-form-urlencoded" Method htmldoc "send" With htmldoc, "responseText" as ready$ res$=trim$(ready$) if left$(res$,1)="{" then ="N/A" else =res$ end if declare htmldoc nothing } Urls=("88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67") url=each(URLs) While Url { Print Array$(URL), httpGet$("http://api.macvendors.com/"+Array$(URL)) Wait 20 } } Checkit  
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Action.21
Action!
PROC Main() DEFINE PTR="CARD" DEFINE COUNT="20" CHAR ARRAY s(256) PTR ARRAY a(COUNT) BYTE i   a(0)="It is certain." a(1)="It is decidedly so." a(2)="Without a doubt." a(3)="Yes - definitely." a(4)="You may rely on it." a(5)="As I see it, yes." a(6)="Most likely." a(7)="Outlook good." a(8)="Yes." a(9)="Signs point to yes." a(10)="Reply hazy, try again." a(11)="Ask again later." a(12)="Better not tell you now." a(13)="Cannot predict now." a(14)="Concentrate and ask again." a(15)="Don't count on it." a(16)="My reply is no." a(17)="My sources say no." a(18)="Outlook not so good." a(19)="Very doubtful."   DO PrintE("Enter your question or blank to exit:") InputS(s) IF s(0)=0 THEN EXIT FI i=Rand(COUNT) PrintE(a(i)) PutE() OD RETURN
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ada
Ada
    with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Numerics.Discrete_Random;     procedure Main is     --Creation of type with all the possible answers -- type Possible_Answers_Type is (It_Is_Certain, It_Is_Decidedly_So, Without_A_Doubt, Yes_Definitely, You_May_Rely_On_It, As_I_See_It, Yes_Most_Likely, Outlook_Good, Signs_Point_To_Yes, Yes_Reply_Hazy, Try_Again, Ask_Again_Later, Better_Not_Tell_You_Now, Cannot_Predict_Now, Concentrate_And_Ask_Again, Dont_Bet_On_It, My_Reply_Is_No, My_Sources_Say_No, Outlook_Not_So_Good, Very_Doubtful); ---------------------------------------------------------------------     -- Variable declaration Answer  : Possible_Answers_Type := Possible_Answers_Type'First; User_Question : String := " ";   -----------------------------------------------------------------------------     --Randomizer -- package Random_Answer is new Ada.Numerics.Discrete_Random (Possible_Answers_Type); use Random_Answer; G : Generator;   begin   Reset (G); -- Starts the generator in a unique state in each run   --User get provides question Put_Line ("Welcome."); New_Line;   Put_Line ("WARNING!!! Please remember that there's no need to shake your device for this program to work, and shaking your device could damage it"); New_Line;   Put_Line ("What's your question? "); Get (Item => User_Question); New_Line;     --Output Answer Answer := (Random (G)); --Assigns random answer to variable Answer   Put (Answer'Image); --Prints Answer   end Main;    
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#COBOL
COBOL
pushq %rbp movq %rsp, %rbp movl %edi, -0x4(%rbp) movl %esi, -0x8(%rbp) movl -0x4(%rbp), %esi addl -0x8(%rbp), %esi movl %esi, -0xc(%rbp) movl -0xc(%rbp), %eax popq %rbp retq  
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Commodore_BASIC
Commodore BASIC
Assembly Hexadecimal Decimal   CLC 18 24 LDA $2000 AD 00 20 173 0 32 ADC $2001 6D 01 20 109 1 32 STA $2002 8D 02 20 141 2 32 RTS 60 96
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#PostScript
PostScript
%!PS-Adobe-2.0 %%BoundingBox: 0 0 300 200 %%EndComments /origstate save def /ld {load def} bind def /m /moveto ld /g /setgray ld /dot { currentpoint 1 0 360 arc fill } bind def %%EndProlog % param /maxiter 200 def % complex manipulation /complex { 2 array astore } def /real { 0 get } def /imag { 1 get } def /cmul { /a exch def /b exch def a real b real mul a imag b imag mul sub a real b imag mul a imag b real mul add 2 array astore } def /cadd { aload pop 3 -1 roll aload pop 3 -1 roll add 3 1 roll add exch 2 array astore } def /cconj { aload pop neg 2 array astore } def /cabs2 { dup cconj cmul 0 get} def % mandel 200 100 translate -200 1 100 { /x exch def -100 1 100 { /y exch def /z0 0.0 0.0 complex def 0 1 maxiter { /iter exch def x 100 div y 100 div complex z0 z0 cmul cadd dup /z0 exch def cabs2 4 gt {exit} if } for iter maxiter div g x y m dot } for } for % showpage origstate restore %%EOF
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Sidef
Sidef
func matrix_multi(a, b) { var m = [[]] for r in ^a { for c in ^b[0] { for i in ^b { m[r][c] := 0 += (a[r][i] * b[i][c]) } } } return m }   var a = [ [1, 2], [3, 4], [5, 6], [7, 8] ]   var b = [ [1, 2, 3], [4, 5, 6] ]   for line in matrix_multi(a, b) { say line.map{|i|'%3d' % i }.join(', ') }
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Sparkling
Sparkling
function transpose(A) { return map(range(sizeof A), function(k, idx) { return map(A, function(k, row) { return row[idx]; }); }); }
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Stata
Stata
. mat a=1,2,3\4,5,6 . mat b=a' . mat list a   a[2,3] c1 c2 c3 r1 1 2 3 r2 4 5 6   . mat list b   b[3,2] r1 r2 c1 1 4 c2 2 5 c3 3 6
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
macLookup[mac_String] := Quiet[Check[Import["http://api.macvendors.com/" <> mac], "N/A"]]
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Nim
Nim
import httpclient   for mac in ["FC-A1-3E", "FC:FB:FB:01:FA:21", "BC:5F:F4"]: echo newHttpClient().getContent("http://api.macvendors.com/"&mac)
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_68
ALGOL 68
BEGIN []STRING answers = ("It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."); DO REF STRING question := LOC STRING; print("Your question: "); read((question, new line)); print((answers[ENTIER (random * UPB answers) + 1], new line)) OD END
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Common_Lisp
Common Lisp
;;Note that by using the 'CFFI' library, one can apply this procedure portably in any lisp implementation; ;; in this code however I chose to demonstrate only the implementation-dependent programs.   ;;CCL ;; Allocate a memory pointer and poke the opcode into it (defparameter ptr (ccl::malloc 9))   (loop for i in '(139 68 36 4 3 68 36 8 195) for j from 0 do (setf (ccl::%get-unsigned-byte ptr j) i))   ;; Execute with the required arguments and return the result as an unsigned-byte (ccl::ff-call ptr :UNSIGNED-BYTE 7 :UNSIGNED-BYTE 12 :UNSIGNED-BYTE)   ;; Output = 19   ;; Free the pointer (ccl::free ptr)   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;SBCL (defparameter mmap (list 139 68 36 4 3 68 36 8 195))   (defparameter pointer (sb-alien:make-alien sb-alien:unsigned-char (length mmap)))   (defparameter callp (loop for byte in mmap for i from 0 do (setf (sb-alien:deref pointer i) byte) finally (return (sb-alien:cast pointer (function integer integer integer)))))   (sb-alien:alien-funcall callp 7 12)   (loop for i from 0 below 18 collect (sb-alien:deref ptr i))   (sb-alien:free-alien pointer)   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;CLISP (defparameter mmap (list 139 68 36 4 3 68 36 8 195))   (defparameter POINTER (FFI:FOREIGN-ADDRESS (FFI:FOREIGN-ALLOCATE 'FFI:UINT8 :COUNT 9)))   (loop for i in mmap for j from 0 do (FUNCALL #'(SETF FFI:MEMORY-AS) i POINTER 'FFI:INT j))   (FUNCALL (FFI:FOREIGN-FUNCTION POINTER (LOAD-TIME-VALUE (FFI:PARSE-C-TYPE '(FFI:C-FUNCTION (:ARGUMENTS 'FFI:INT 'FFI:INT) (:RETURN-TYPE FFI:INT) (:LANGUAGE :STDC))))) 7 12)   (FFI:FOREIGN-FREE POINTER)  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#PowerShell
PowerShell
  $x = $y = $i = $j = $r = -16 $colors = [Enum]::GetValues([System.ConsoleColor])   while(($y++) -lt 15) { for($x=0; ($x++) -lt 84; Write-Host " " -BackgroundColor ($colors[$k -band 15]) -NoNewline) { $i = $k = $r = 0   do { $j = $r * $r - $i * $i -2 + $x / 25 $i = 2 * $r * $i + $y / 10 $r = $j } while (($j * $j + $i * $i) -lt 11 -band ($k++) -lt 111) }   Write-Host }  
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#SPAD
SPAD
(1) -> A:=matrix [[1,2],[3,4],[5,6],[7,8]]   +1 2+ | | |3 4| (1) | | |5 6| | | +7 8+ Type: Matrix(Integer) (2) -> B:=matrix [[1,2,3],[4,5,6]]   +1 2 3+ (2) | | +4 5 6+ Type: Matrix(Integer) (3) -> A*B   +9 12 15+ | | |19 26 33| (3) | | |29 40 51| | | +39 54 69+ Type: Matrix(Integer)
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Swift
Swift
@inlinable public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] { guard !matrix.isEmpty else { return [] }   var ret = Array(repeating: [T](), count: matrix[0].count)   for row in matrix { for j in 0..<row.count { ret[j].append(row[j]) } }   return ret }   @inlinable public func printMatrix<T>(_ matrix: [[T]]) { guard !matrix.isEmpty else { print()   return }   let rows = matrix.count let cols = matrix[0].count   for i in 0..<rows { for j in 0..<cols { print(matrix[i][j], terminator: " ") }   print() } }   let m1 = [ [1, 2, 3], [4, 5, 6] ]   print("Input:") printMatrix(m1)     let m2 = matrixTranspose(m1)   print("Output:") printMatrix(m2)
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Tailspin
Tailspin
  templates transpose def a: $; [1..$a(1)::length -> $a(1..last;$)] ! end transpose   templates printMatrix&{w:} templates formatN @: []; $ -> # '$@ -> $::length~..$w -> ' ';$@(last..1:-1)...;' ! when <1..> do ..|@: $ mod 10; $ ~/ 10 -> # end formatN $... -> '|$(1) -> formatN;$(2..last)... -> ', $ -> formatN;';| ' ! end printMatrix   def m: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; 'before: ' -> !OUT::write $m -> printMatrix&{w:2} -> !OUT::write   def mT: $m -> transpose; ' transposed: ' -> !OUT::write $mT -> printMatrix&{w:2} -> !OUT::write  
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#OCaml
OCaml
  (* build with ocamlfind ocamlopt -package netclient -linkpkg macaddr.ml -o macaddr *)   open Printf open Nethttp_client.Convenience open Unix   (* example vendors, including a nonsense one *)   let vendors = ["FF:FF:FF:67:07:BE"; "D4:F4:6F:C9:EF:8D"; "FC:FB:FB:01:FA:21"; "88:53:2E:67:07:BE"]   let get_vendor addr = sleep 3; (* built-in delay to handle rate-limiting at macvendors.com *)   let client = http_get_message ("http://api.macvendors.com/" ^ addr) in match client # response_status_code with | 200 -> client # response_body # value | 404 -> "N/A" | _ -> "NULL"   let rec parse_vendors vendors = match vendors with | [] -> [] | hd::tl -> get_vendor hd :: parse_vendors tl   let rec print_vendors vendor_list = match vendor_list with | [] -> "" | hd::tl -> printf "%s\n" hd; print_vendors tl   let main = let vendor_list = parse_vendors vendors in print_vendors vendor_list        
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Perl
Perl
#!/usr/bin/env perl -T use 5.018_002; use warnings; use LWP;   our $VERSION = 1.000_000;   my $ua = LWP::UserAgent->new;   my @macs = ( 'FC-A1-3EFC:FB:FB:01:FA:21', '00,0d,4b', 'Rhubarb', '00-14-22-01-23-45', '10:dd:b1', 'D4:F4:6F:C9:EF:8D', 'FC-A1-3E', '88:53:2E:67:07:BE', '23:45:67', 'FC:FB:FB:01:FA:21', 'BC:5F:F4', );   for my $mac (@macs) { my $vendor = get_mac_vendor($mac); if ($vendor) { say "$mac = $vendor"; } }   sub get_mac_vendor { my $s = shift;   my $req = HTTP::Request->new( GET => "http://api.macvendors.com/$s" ); my $res = $ua->request($req);   # A error related to the network connectivity or the API should # return a null result. if ( $res->is_error ) { return; }   # A MAC address that does not return a valid result should # return the String "N/A". if ( !$res->content or $res->content eq 'Vendor not found' ) { return 'N/A'; }   return $res->content; }   # IEEE 802: # Six groups of two hexadecimal digits separated by hyphens or colons, # like 01-23-45-67-89-ab or 01:23:45:67:89:ab # Three groups of four hexadecimal digits separated by dots (.), # like 0123.4567.89ab #sub validmac { # my $s = shift; # # my $hex = qr{ [A-Fa-f[:digit:]] }xms; # my $hex2ws = qr{ [-:] $hex{2} }xms; # # if ( $s =~ m{\A $hex{2} $hex2ws{5} \z}xms # or $s =~ m{\A $hex{4} [.] $hex{4} [.] $hex{4} \z}xms ) # { # return 'true'; # } # return; #}
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AppleScript
AppleScript
set the answers to {"It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"}   display dialog some item of the answers
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
answers: [ "It is certain" "It is decidedly so" "Without a doubt" "Yes, definitely" "You may rely on it" "As I see it, yes" "Most likely" "Outlook good" "Signs point to yes" "Yes" "Reply hazy, try again" "Ask again later" "Better not tell you now" "Cannot predict now" "Concentrate and ask again" "Don't bet on it" "My reply is no" "My sources say no" "Outlook not so good" "Very doubtful" ]   while ø [ input "Ask a question: " print sample answers ]
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Cowgol
Cowgol
include "cowgol.coh";   # Run machine code at cptr, given two 32-bit arguments, # return the value returned from EAX. sub RunCode(cptr: [uint8], arg1: uint32, arg2: uint32): (rslt: uint32) is # Inline assembly is supported, so this whole rigmarole # is not even necessary. # Though note that this (obviously) depends on the assembly back-end used. # Linux as uses AT&T syntax, so that's what I'm doing here. # Cowgol supports many processors but this will, obviously, only work # on x86.   @asm "pushl (",arg1,")"; # Push the two arguments on the stack @asm "pushl (",arg2,")"; @asm "call *(",cptr,")"; # Call the code at the pointer @asm "movl %eax, (",rslt,")"; # Store the result in rslt @asm "popl %eax"; # Clean up the stack @asm "popl %eax"; end sub;   # Store code in an array. This is enough to make it available. var code: uint8[] := {139, 68, 36, 4, 3, 68, 36, 8, 195};   # Use the function print_i32(RunCode(&code as [uint8], 7, 12)); # this prints 7+12 = 19 print_nl();   # As a demonstration, this shows it can be patched at runtime to multiply instead code[4] := 247; code[5] := 100; print_i32(RunCode(&code as [uint8], 7, 12)); # this prints 7*12 = 84 print_nl();
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#D
D
int test(in int a, in int b) pure nothrow @nogc { /* mov EAX, [ESP+4] add EAX, [ESP+8] ret */ immutable ubyte[9] code = [0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]; alias F = extern(C) int function(int, int) pure nothrow @nogc; immutable f = cast(F)code.ptr; return f(a, b); // Run code. }   void main() { import std.stdio;   test(7, 12).writeln; }
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Processing
Processing
double x, y, zr, zi, zr2, zi2, cr, ci, n; double zmx1, zmx2, zmy1, zmy2, f, di, dj; double fn1, fn2, fn3, re, gr, bl, xt, yt, i, j;   void setup() { size(500, 500); di = 0; dj = 0; f = 10; fn1 = random(20); fn2 = random(20); fn3 = random(20); zmx1 = int(width / 4); zmx2 = 2; zmy1 = int(height / 4); zmy2 = 2; }   void draw() { if (i <= width) i++; x = (i + di)/ zmx1 - zmx2; for ( j = 0; j <= height; j++) { y = zmy2 - (j + dj) / zmy1; zr = 0; zi = 0; zr2 = 0; zi2 = 0; cr = x; ci = y; n = 1; while (n < 200 && (zr2 + zi2) < 4) { zi2 = zi * zi; zr2 = zr * zr; zi = 2 * zi * zr + ci; zr = zr2 - zi2 + cr; n++; } re = (n * fn1) % 255; gr = (n * fn2) % 255; bl = (n * fn3) % 255; stroke((float)re, (float)gr, (float)bl); point((float)i, (float)j); } }   void mousePressed() { background(200); xt = mouseX; yt = mouseY; di = di + xt - float(width / 2); dj = dj + yt - float(height / 2); zmx1 = zmx1 * f; zmx2 = zmx2 * (1 / f); zmy1 = zmy1 * f; zmy2 = zmy2 * (1 / f); di = di * f; dj = dj * f; i = 0; j = 0; }
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#SQL
SQL
CREATE TABLE a (x INTEGER, y INTEGER, e REAL); CREATE TABLE b (x INTEGER, y INTEGER, e REAL);   -- test data -- A is a 2x2 matrix INSERT INTO a VALUES(0,0,1); INSERT INTO a VALUES(1,0,2); INSERT INTO a VALUES(0,1,3); INSERT INTO a VALUES(1,1,4);   -- B is a 2x3 matrix INSERT INTO b VALUES(0,0,-3); INSERT INTO b VALUES(1,0,-8); INSERT INTO b VALUES(2,0,3); INSERT INTO b VALUES(0,1,-2); INSERT INTO b VALUES(1,1, 1); INSERT INTO b VALUES(2,1,4);   -- C is 2x2 * 2x3 so will be a 2x3 matrix SELECT rhs.x, lhs.y, (SELECT SUM(a.e*b.e) FROM a, b WHERE a.y = lhs.y AND b.x = rhs.x AND a.x = b.y) INTO TABLE c FROM a AS lhs, b AS rhs WHERE lhs.x = 0 AND rhs.y = 0;
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Tcl
Tcl
package require Tcl 8.5 namespace path ::tcl::mathfunc   proc size {m} { set rows [llength $m] set cols [llength [lindex $m 0]] return [list $rows $cols] } proc transpose {m} { lassign [size $m] rows cols set new [lrepeat $cols [lrepeat $rows ""]] for {set i 0} {$i < $rows} {incr i} { for {set j 0} {$j < $cols} {incr j} { lset new $j $i [lindex $m $i $j] } } return $new } proc print_matrix {m {fmt "%.17g"}} { set max [widest $m $fmt] lassign [size $m] rows cols for {set i 0} {$i < $rows} {incr i} { for {set j 0} {$j < $cols} {incr j} { set s [format $fmt [lindex $m $i $j]] puts -nonewline [format "%*s " [lindex $max $j] $s] } puts "" } } proc widest {m {fmt "%.17g"}} { lassign [size $m] rows cols set max [lrepeat $cols 0] for {set i 0} {$i < $rows} {incr i} { for {set j 0} {$j < $cols} {incr j} { set s [format $fmt [lindex $m $i $j]] lset max $j [max [lindex $max $j] [string length $s]] } } return $max }   set m {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}} print_matrix $m "%d" print_matrix [transpose $m] "%d"
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Phix
Phix
without js -- libcurl string test = "00-11-22-33-44-55-66" -- CIMSYS Inc --string test = "10-11-22-33-44-55-66" -- N/A include builtins/libcurl.e curl_global_init() atom curl = curl_easy_init() string url = sprintf("http://api.macvendors.com/%s",{test}) curl_easy_setopt(curl, CURLOPT_URL, url) object res = curl_easy_perform_ex(curl) if string(res) then if res="Vendor not found" or res=`{"errors":{"detail":"Not Found"}}` then res = "N/A" end if ?res else ?{"error",res} end if curl_easy_cleanup(curl) curl_global_cleanup()
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#PicoLisp
PicoLisp
(load "@lib/http.l")   (de maclookup (M) (client "api.macvendors.com" 80 M (while (line)) (line T) ) ) (test "Intel Corporate" (maclookup "88:53:2E:67:07:BE") ) (test "Apple, Inc." (maclookup "D4:F4:6F:C9:EF:8D") )
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AutoHotkey
AutoHotkey
answers := [ (join "It is certain", "It is decidedly so", "Without a doubt","Yes, definitely", "You may rely on it", "As I see it, yes","Most likely", "Outlook good", "Signs point to yes", "Yes","Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now","Concentrate and ask again", "Don't bet on it","My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" )] Ask: InputBox, Question, Magic 8-Ball, Please ask your question or a blank line to quit.,,, 130 Random, rnd, 1, 20 if !question ExitApp MsgBox % answers[rnd] gosub, Ask return
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Draco
Draco
/* 8080 machine code in an array */ [6] byte add_mc = ( 0xC1, /* POP B - get return address */ 0xD1, /* POP D - get second argument */ 0xE1, /* POP H - get first argument */ 0x19, /* DAD D - add arguments */ 0xC5, /* PUSH B - push return address back */ 0xC9 /* RET - return */ );   proc nonrec main() void: /* Declare a function pointer */ type fn = proc(word a, b) word; fn add;   /* Pretend the array is actually a function */ add := pretend(add_mc, fn);   /* Call the function and print the result */ writeln(add(12, 7)) corp
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#FreeBASIC
FreeBASIC
'' This is an example for the x86 architecture. Function test (Byval a As Long, Byval b As Long) As Long Asm mov eax, [a] Add eax, [b] mov [Function], eax End Asm End Function   Print test(12, 7) Sleep
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Prolog
Prolog
:- use_module(library(pce)).   mandelbrot :- new(D, window('Mandelbrot Set')), send(D, size, size(700, 650)), new(Img, image(@nil, width := 700, height := 650, kind := pixmap)),   forall(between(0,699, I), ( forall(between(0,649, J), ( get_RGB(I, J, R, G, B), R1 is (R * 256) mod 65536, G1 is (G * 256) mod 65536, B1 is (B * 256) mod 65536, send(Img, pixel(I, J, colour(@default, R1, G1, B1))))))), new(Bmp, bitmap(Img)), send(D, display, Bmp, point(0,0)), send(D, open).   get_RGB(X, Y, R, G, B) :- CX is (X - 350) / 150, CY is (Y - 325) / 150, Iter = 570, compute_RGB(CX, CY, 0, 0, Iter, It), IterF is It \/ It << 15, R is IterF >> 16, Iter1 is IterF - R << 16, G is Iter1 >> 8, B is Iter1 - G << 8.   compute_RGB(CX, CY, ZX, ZY, Iter, IterF) :- ZX * ZX + ZY * ZY < 4, Iter > 0, !, Tmp is ZX * ZX - ZY * ZY + CX, ZY1 is 2 * ZX * ZY + CY, Iter1 is Iter - 1, compute_RGB(CX, CY, Tmp, ZY1, Iter1, IterF).   compute_RGB(_CX, _CY, _ZX, _ZY, Iter, Iter).
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Standard_ML
Standard ML
structure IMatrix = struct fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x fun x*y = let open Array2 in tabulate ColMajor (nRows x, nCols y, fn (i,j) => dot(row(x,i),column(y,j))) end end; (* for display *) fun toList a = let open Array2 in List.tabulate(nRows a, fn i => List.tabulate(nCols a, fn j => sub(a,i,j))) end; (* example *) let open IMatrix val m1 = Array2.fromList [[1,2],[3,4]] val m2 = Array2.fromList [[~3,~8,3],[~2,1,4]] in toList (m1*m2) end;
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#TI-83_BASIC.2C_TI-89_BASIC
TI-83 BASIC, TI-89 BASIC
[A]T->[B]
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#True_BASIC
True BASIC
OPTION BASE 0 DIM matriz(3, 4) DATA 78, 19, 30, 12, 36 DATA 49, 10, 65, 42, 50 DATA 30, 93, 24, 78, 10 DATA 39, 68, 27, 64, 29   FOR f = 0 TO 3 FOR c = 0 TO 4 READ matriz(f, c) NEXT c NEXT f   DIM mtranspuesta(0 TO 4, 0 TO 3)   FOR fila = LBOUND(matriz,1) TO UBOUND(matriz,1) FOR columna = LBOUND(matriz,2) TO UBOUND(matriz,2) LET mtranspuesta(columna, fila) = matriz(fila, columna) PRINT matriz(fila, columna); NEXT columna PRINT NEXT fila PRINT   FOR fila = LBOUND(mtranspuesta,1) TO UBOUND(mtranspuesta,1) FOR columna = LBOUND(mtranspuesta,2) TO UBOUND(mtranspuesta,2) PRINT mtranspuesta(fila, columna); NEXT columna PRINT NEXT fila END
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Python
Python
import requests   for addr in ['88:53:2E:67:07:BE', 'FC:FB:FB:01:FA:21', 'D4:F4:6F:C9:EF:8D', '23:45:67']: vendor = requests.get('http://api.macvendors.com/' + addr).text print(addr, vendor)
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. {"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}
#Racket
Racket
#lang racket   (require net/url)   (define (lookup-MAC-address addr) (port->string (get-pure-port (url "http" #f "api.macvendors.com" #f #t (list (path/param addr null)) null #f))))   (module+ test (for ((i (in-list '("88:53:2E:67:07:BE" "FC:FB:FB:01:FA:21" "D4:F4:6F:C9:EF:8D")))) (printf "~a\t~a~%" i (lookup-MAC-address i))))
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AWK
AWK
  # syntax: GAWK -f MAGIC_8-BALL.AWK BEGIN { # Ten answers are affirmative, five are non-committal, and five are negative. arr[++i] = "It is certain" arr[++i] = "It is decidedly so" arr[++i] = "Without a doubt" arr[++i] = "Yes, definitely" arr[++i] = "You may rely on it" arr[++i] = "As I see it, yes" arr[++i] = "Most likely" arr[++i] = "Outlook good" arr[++i] = "Signs point to yes" arr[++i] = "Yes" arr[++i] = "Reply hazy, try again" arr[++i] = "Ask again later" arr[++i] = "Better not tell you now" arr[++i] = "Cannot predict now" arr[++i] = "Concentrate and ask again" arr[++i] = "Don't bet on it" arr[++i] = "My reply is no" arr[++i] = "My sources say no" arr[++i] = "Outlook not so good" arr[++i] = "Very doubtful" srand() printf("Please enter your question or a blank line to quit.\n") while (1) { printf("\n? ") getline ans if (ans ~ /^ *$/) { break } printf("%s\n",arr[int(rand()*i)+1]) } exit(0) }