Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Common_Lisp to PHP with equivalent syntax and logic.
(defun csvfile-to-nested-list (filename delim-char) "Reads the csv to a nested list, where each sublist represents a line." (with-open-file (input filename) (loop :for line := (read-line input nil) :while line :collect (read-from-string (substitute #\SPACE delim-char (format nil "(~a)~%" line)))))) (defun sublist-sum-list (nested-list) "Return a list with the sum of each list of numbers in a nested list." (mapcar (lambda (l) (if (every #'numberp l) (reduce #'+ l) nil)) nested-list)) (defun append-each-sublist (nested-list1 nested-list2) "Horizontally append the sublists in two nested lists. Used to add columns." (mapcar #'append nested-list1 nested-list2)) (defun nested-list-to-csv (nested-list delim-string) "Converts the nested list back into a csv-formatted string." (format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}") nested-list)) (defun main () (let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt") (result-path #p"results.txt") (data-list (csvfile-to-nested-list csvfile-path #\,)) (list-of-sums (sublist-sum-list data-list)) (result-header "C1,C2,C3,C4,C5,SUM")) (setf data-list (rest (append-each-sublist data-list (mapcar #'list list-of-sums)))) (with-open-file (output result-path :direction :output :if-exists :supersede) (format output "~a~%~a" result-header (nested-list-to-csv data-list ","))))) (main)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Ensure the translated PHP code behaves exactly like the original Common_Lisp snippet.
(defun csvfile-to-nested-list (filename delim-char) "Reads the csv to a nested list, where each sublist represents a line." (with-open-file (input filename) (loop :for line := (read-line input nil) :while line :collect (read-from-string (substitute #\SPACE delim-char (format nil "(~a)~%" line)))))) (defun sublist-sum-list (nested-list) "Return a list with the sum of each list of numbers in a nested list." (mapcar (lambda (l) (if (every #'numberp l) (reduce #'+ l) nil)) nested-list)) (defun append-each-sublist (nested-list1 nested-list2) "Horizontally append the sublists in two nested lists. Used to add columns." (mapcar #'append nested-list1 nested-list2)) (defun nested-list-to-csv (nested-list delim-string) "Converts the nested list back into a csv-formatted string." (format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}") nested-list)) (defun main () (let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt") (result-path #p"results.txt") (data-list (csvfile-to-nested-list csvfile-path #\,)) (list-of-sums (sublist-sum-list data-list)) (result-header "C1,C2,C3,C4,C5,SUM")) (setf data-list (rest (append-each-sublist data-list (mapcar #'list list-of-sums)))) (with-open-file (output result-path :direction :output :if-exists :supersede) (format output "~a~%~a" result-header (nested-list-to-csv data-list ","))))) (main)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the D version.
void main() { import std.stdio, std.csv, std.file, std.typecons, std.array, std.algorithm, std.conv, std.range; auto rows = "csv_data_in.csv".File.byLine; auto fout = "csv_data_out.csv".File("w"); fout.writeln(rows.front); fout.writef("%(%(%d,%)\n%)", rows.dropOne .map!(r => r.csvReader!int.front.map!(x => x + 1))); }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert this D block to PHP, preserving its control flow and logic.
void main() { import std.stdio, std.csv, std.file, std.typecons, std.array, std.algorithm, std.conv, std.range; auto rows = "csv_data_in.csv".File.byLine; auto fout = "csv_data_out.csv".File("w"); fout.writeln(rows.front); fout.writef("%(%(%d,%)\n%)", rows.dropOne .map!(r => r.csvReader!int.front.map!(x => x + 1))); }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert this Delphi block to PHP, preserving its control flow and logic.
program CSV_data_manipulation; uses System.SysUtils, System.IoUtils, System.Types; type TStringDynArrayHelper = record helper for TStringDynArray function Sum: Integer; end; function TStringDynArrayHelper.Sum: Integer; var value: string; begin Result := 0; for value in self do Result := Result + StrToIntDef(value, 0); end; const FILENAME = './Data.csv'; var i: integer; Input, Row: TStringDynArray; begin Input := TFile.ReadAllLines(FILENAME); for i := 0 to High(Input) do begin if i = 0 then Input[i] := Input[i] + ',SUM' else begin Row := Input[i].Split([',']); Input[i] := Input[i] + ',' + row.Sum.ToString; end; end; TFile.WriteAllLines(FILENAME, Input); end.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Produce a functionally identical PHP code for the snippet given in Delphi.
program CSV_data_manipulation; uses System.SysUtils, System.IoUtils, System.Types; type TStringDynArrayHelper = record helper for TStringDynArray function Sum: Integer; end; function TStringDynArrayHelper.Sum: Integer; var value: string; begin Result := 0; for value in self do Result := Result + StrToIntDef(value, 0); end; const FILENAME = './Data.csv'; var i: integer; Input, Row: TStringDynArray; begin Input := TFile.ReadAllLines(FILENAME); for i := 0 to High(Input) do begin if i = 0 then Input[i] := Input[i] + ',SUM' else begin Row := Input[i].Split([',']); Input[i] := Input[i] + ',' + row.Sum.ToString; end; end; TFile.WriteAllLines(FILENAME, Input); end.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Translate the given Elixir code snippet into PHP without altering its behavior.
defmodule Csv do defstruct header: "", data: "", separator: "," def from_file(path) do [header | data] = path |> File.stream! |> Enum.to_list |> Enum.map(&String.trim/1) %Csv{ header: header, data: data } end def sums_of_rows(csv) do Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end) end def sum_of_row(row, separator) do row |> String.split(separator) |> Enum.map(&String.to_integer/1) |> Enum.sum |> to_string end def append_column(csv, column_header, column_data) do header = append_to_row(csv.header, column_header, csv.separator) data = [csv.data, column_data] |> List.zip |> Enum.map(fn ({ row, value }) -> append_to_row(row, value, csv.separator) end) %Csv{ header: header, data: data } end def append_to_row(row, value, separator) do row <> separator <> value end def to_file(csv, path) do body = Enum.join([csv.header | csv.data], "\n") File.write(path, body) end end csv = Csv.from_file("in.csv") csv |> Csv.append_column("SUM", Csv.sums_of_rows(csv)) |> Csv.to_file("out.csv")
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Please provide an equivalent version of this Elixir code in PHP.
defmodule Csv do defstruct header: "", data: "", separator: "," def from_file(path) do [header | data] = path |> File.stream! |> Enum.to_list |> Enum.map(&String.trim/1) %Csv{ header: header, data: data } end def sums_of_rows(csv) do Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end) end def sum_of_row(row, separator) do row |> String.split(separator) |> Enum.map(&String.to_integer/1) |> Enum.sum |> to_string end def append_column(csv, column_header, column_data) do header = append_to_row(csv.header, column_header, csv.separator) data = [csv.data, column_data] |> List.zip |> Enum.map(fn ({ row, value }) -> append_to_row(row, value, csv.separator) end) %Csv{ header: header, data: data } end def append_to_row(row, value, separator) do row <> separator <> value end def to_file(csv, path) do body = Enum.join([csv.header | csv.data], "\n") File.write(path, body) end end csv = Csv.from_file("in.csv") csv |> Csv.append_column("SUM", Csv.sums_of_rows(csv)) |> Csv.to_file("out.csv")
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Ensure the translated PHP code behaves exactly like the original Erlang snippet.
-module( csv_data ). -export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ). change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ). from_binary( Binary ) -> Lines = binary:split( Binary, <<"\n">>, [global] ), [binary:split(X, <<",">>, [global]) || X <- Lines]. from_file( Name ) -> {ok, Binary} = file:read_file( Name ), from_binary( Binary ). into_file( Name, CSV ) -> Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ), file:write_file( Name, Binaries ). task() -> CSV = from_file( "CSV_file.in" ), New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ), into_file( "CSV_file.out", New_CSV ). change_foldl( {Row_number, Column_number, New}, Acc ) -> {Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ), {Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ), Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters. join_binaries( Binaries, Binary ) -> [_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ), lists:reverse( Rest ). split( 1, List ) -> {[], List}; split( N, List ) -> lists:split( N - 1, List ).
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the following Erlang code into PHP without altering its purpose.
-module( csv_data ). -export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ). change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ). from_binary( Binary ) -> Lines = binary:split( Binary, <<"\n">>, [global] ), [binary:split(X, <<",">>, [global]) || X <- Lines]. from_file( Name ) -> {ok, Binary} = file:read_file( Name ), from_binary( Binary ). into_file( Name, CSV ) -> Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ), file:write_file( Name, Binaries ). task() -> CSV = from_file( "CSV_file.in" ), New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ), into_file( "CSV_file.out", New_CSV ). change_foldl( {Row_number, Column_number, New}, Acc ) -> {Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ), {Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ), Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters. join_binaries( Binaries, Binary ) -> [_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ), lists:reverse( Rest ). split( 1, List ) -> {[], List}; split( N, List ) -> lists:split( N - 1, List ).
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Transform the following F# implementation into PHP, maintaining the same output and logic.
open System.IO [<EntryPoint>] let main _ = let input = File.ReadAllLines "test_in.csv" let output = input |> Array.mapi (fun i line -> if i = 0 then line + ",SUM" else let sum = Array.sumBy int (line.Split(',')) sprintf "%s,%i" line sum) File.WriteAllLines ("test_out.csv", output) 0
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this F# code.
open System.IO [<EntryPoint>] let main _ = let input = File.ReadAllLines "test_in.csv" let output = input |> Array.mapi (fun i line -> if i = 0 then line + ",SUM" else let sum = Array.sumBy int (line.Split(',')) sprintf "%s,%i" line sum) File.WriteAllLines ("test_out.csv", output) 0
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert this Factor block to PHP, preserving its control flow and logic.
USING: csv io.encodings.utf8 kernel math.parser sequences ; IN: rosetta-code.csv-manipulation : append-sum ( seq -- seq' ) dup [ string>number ] map-sum number>string suffix ; : csv-sums ( seq -- seq' ) [ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ; "example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Translate the given Factor code snippet into PHP without altering its behavior.
USING: csv io.encodings.utf8 kernel math.parser sequences ; IN: rosetta-code.csv-manipulation : append-sum ( seq -- seq' ) dup [ string>number ] map-sum number>string suffix ; : csv-sums ( seq -- seq' ) [ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ; "example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same algorithm in PHP as shown in this Forth implementation.
CHAR , CONSTANT SEPARATOR 3 CONSTANT DECIMALS 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE : colsum 0E0 OVER SWAP BOUNDS ?DO I C@ SEPARATOR = IF I TUCK OVER - >FLOAT IF F+ THEN 1+ THEN LOOP DROP ; : f>string FSCALE F* F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #> ; : rowC!+ OVER HERE + C! 1+ ; : row$!+ ROT 2DUP + >R HERE + SWAP MOVE R> ; : csvsum 2DUP HERE UNUSED ROT READ-LINE THROW IF HERE SWAP SEPARATOR rowC!+ s ROT WRITE-LINE THROW BEGIN 2DUP HERE UNUSED ROT READ-LINE THROW WHILE HERE SWAP SEPARATOR rowC!+ HERE OVER colsum f>string row$!+ ROT WRITE-LINE THROW REPEAT THEN 2DROP 2DROP ;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the provided Forth code into PHP while preserving the original functionality.
CHAR , CONSTANT SEPARATOR 3 CONSTANT DECIMALS 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE : colsum 0E0 OVER SWAP BOUNDS ?DO I C@ SEPARATOR = IF I TUCK OVER - >FLOAT IF F+ THEN 1+ THEN LOOP DROP ; : f>string FSCALE F* F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #> ; : rowC!+ OVER HERE + C! 1+ ; : row$!+ ROT 2DUP + >R HERE + SWAP MOVE R> ; : csvsum 2DUP HERE UNUSED ROT READ-LINE THROW IF HERE SWAP SEPARATOR rowC!+ s ROT WRITE-LINE THROW BEGIN 2DUP HERE UNUSED ROT READ-LINE THROW WHILE HERE SWAP SEPARATOR rowC!+ HERE OVER colsum f>string row$!+ ROT WRITE-LINE THROW REPEAT THEN 2DROP 2DROP ;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the following Fortran code into PHP without altering its purpose.
program rowsum implicit none character(:), allocatable :: line, name, a(:) character(20) :: fmt double precision, allocatable :: v(:) integer :: n, nrow, ncol, i call get_command_argument(1, length=n) allocate(character(n) :: name) call get_command_argument(1, name) open(unit=10, file=name, action="read", form="formatted", access="stream") deallocate(name) call get_command_argument(2, length=n) allocate(character(n) :: name) call get_command_argument(2, name) open(unit=11, file=name, action="write", form="formatted", access="stream") deallocate(name) nrow = 0 ncol = 0 do while (readline(10, line)) nrow = nrow + 1 call split(line, a) if (nrow == 1) then ncol = size(a) write(11, "(A)", advance="no") line write(11, "(A)") ",Sum" allocate(v(ncol + 1)) write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, "," else if (size(a) /= ncol) then print "(A,' ',G0)", "Invalid number of values on row", nrow stop end if do i = 1, ncol read(a(i), *) v(i) end do v(ncol + 1) = sum(v(1:ncol)) write(11, fmt) v end if end do close(10) close(11) contains function readline(unit, line) use iso_fortran_env logical :: readline integer :: unit, ios, n character(:), allocatable :: line character(10) :: buffer line = "" readline = .false. do read(unit, "(A)", advance="no", size=n, iostat=ios) buffer if (ios == iostat_end) return readline = .true. line = line // buffer(1:n) if (ios == iostat_eor) return end do end function subroutine split(line, array, separator) character(*) line character(:), allocatable :: array(:) character, optional :: separator character :: sep integer :: n, m, p, i, k if (present(separator)) then sep = separator else sep = "," end if n = len(line) m = 0 p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then p = p + 1 m = max(m, i - k) k = i + 1 end if end do m = max(m, n - k + 1) if (allocated(array)) deallocate(array) allocate(character(m) :: array(p)) p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then array(p) = line(k:i-1) p = p + 1 k = i + 1 end if end do array(p) = line(k:n) end subroutine end program
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate a PHP translation of this Fortran snippet without changing its computational steps.
program rowsum implicit none character(:), allocatable :: line, name, a(:) character(20) :: fmt double precision, allocatable :: v(:) integer :: n, nrow, ncol, i call get_command_argument(1, length=n) allocate(character(n) :: name) call get_command_argument(1, name) open(unit=10, file=name, action="read", form="formatted", access="stream") deallocate(name) call get_command_argument(2, length=n) allocate(character(n) :: name) call get_command_argument(2, name) open(unit=11, file=name, action="write", form="formatted", access="stream") deallocate(name) nrow = 0 ncol = 0 do while (readline(10, line)) nrow = nrow + 1 call split(line, a) if (nrow == 1) then ncol = size(a) write(11, "(A)", advance="no") line write(11, "(A)") ",Sum" allocate(v(ncol + 1)) write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, "," else if (size(a) /= ncol) then print "(A,' ',G0)", "Invalid number of values on row", nrow stop end if do i = 1, ncol read(a(i), *) v(i) end do v(ncol + 1) = sum(v(1:ncol)) write(11, fmt) v end if end do close(10) close(11) contains function readline(unit, line) use iso_fortran_env logical :: readline integer :: unit, ios, n character(:), allocatable :: line character(10) :: buffer line = "" readline = .false. do read(unit, "(A)", advance="no", size=n, iostat=ios) buffer if (ios == iostat_end) return readline = .true. line = line // buffer(1:n) if (ios == iostat_eor) return end do end function subroutine split(line, array, separator) character(*) line character(:), allocatable :: array(:) character, optional :: separator character :: sep integer :: n, m, p, i, k if (present(separator)) then sep = separator else sep = "," end if n = len(line) m = 0 p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then p = p + 1 m = max(m, i - k) k = i + 1 end if end do m = max(m, n - k + 1) if (allocated(array)) deallocate(array) allocate(character(m) :: array(p)) p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then array(p) = line(k:i-1) p = p + 1 k = i + 1 end if end do array(p) = line(k:n) end subroutine end program
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite the snippet below in PHP so it works the same as the original Groovy code.
def csv = [] def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } } def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } } loadCsv new File('csv.txt') csv[0][0] = 'Column0' (1..4).each { i -> csv[i][i] = i * 100 } saveCsv new File('csv_out.txt')
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert this Groovy block to PHP, preserving its control flow and logic.
def csv = [] def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } } def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } } loadCsv new File('csv.txt') csv[0][0] = 'Column0' (1..4).each { i -> csv[i][i] = i * 100 } saveCsv new File('csv_out.txt')
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same code in PHP as shown below in Haskell.
import Data.Array (Array(..), (//), bounds, elems, listArray) import Data.List (intercalate) import Control.Monad (when) import Data.Maybe (isJust) delimiters :: String delimiters = ",;:" fields :: String -> [String] fields [] = [] fields xs = let (item, rest) = break (`elem` delimiters) xs (_, next) = break (`notElem` delimiters) rest in item : fields next unfields :: Maybe (Array (Int, Int) String) -> [String] unfields Nothing = [] unfields (Just a) = every fieldNumber $ elems a where ((_, _), (_, fieldNumber)) = bounds a every _ [] = [] every n xs = let (y, z) = splitAt n xs in intercalate "," y : every n z fieldArray :: [[String]] -> Maybe (Array (Int, Int) String) fieldArray [] = Nothing fieldArray xs = Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String)) fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO () fieldsToFile f = writeFile f . unlines . unfields someChanges :: Maybe (Array (Int, Int) String) -> Maybe (Array (Int, Int) String) someChanges = fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")]) main :: IO () main = do a <- fieldsFromFile "example.txt" when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the provided Haskell code into PHP while preserving the original functionality.
import Data.Array (Array(..), (//), bounds, elems, listArray) import Data.List (intercalate) import Control.Monad (when) import Data.Maybe (isJust) delimiters :: String delimiters = ",;:" fields :: String -> [String] fields [] = [] fields xs = let (item, rest) = break (`elem` delimiters) xs (_, next) = break (`notElem` delimiters) rest in item : fields next unfields :: Maybe (Array (Int, Int) String) -> [String] unfields Nothing = [] unfields (Just a) = every fieldNumber $ elems a where ((_, _), (_, fieldNumber)) = bounds a every _ [] = [] every n xs = let (y, z) = splitAt n xs in intercalate "," y : every n z fieldArray :: [[String]] -> Maybe (Array (Int, Int) String) fieldArray [] = Nothing fieldArray xs = Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String)) fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO () fieldsToFile f = writeFile f . unlines . unfields someChanges :: Maybe (Array (Int, Int) String) -> Maybe (Array (Int, Int) String) someChanges = fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")]) main :: IO () main = do a <- fieldsFromFile "example.txt" when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this J code.
data=: (','&splitstring);.2 freads 'rc_csv.csv' data=: (<'"spam"') (<2 3)} data 'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Maintain the same structure and functionality when rewriting this code in PHP.
data=: (','&splitstring);.2 freads 'rc_csv.csv' data=: (<'"spam"') (<2 3)} data 'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Please provide an equivalent version of this Julia code in PHP.
using DataFrames, CSV ifn = "csv_data_manipulation_in.dat" ofn = "csv_data_manipulation_out.dat" df = CSV.read(ifn, DataFrame) df.SUM = sum.(eachrow(df)) CSV.write(ofn, df)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert the following code from Julia to PHP, ensuring the logic remains intact.
using DataFrames, CSV ifn = "csv_data_manipulation_in.dat" ofn = "csv_data_manipulation_out.dat" df = CSV.read(ifn, DataFrame) df.SUM = sum.(eachrow(df)) CSV.write(ofn, df)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Ensure the translated PHP code behaves exactly like the original Lua snippet.
local csv={} for line in io.lines('file.csv') do table.insert(csv, {}) local i=1 for j=1,#line do if line:sub(j,j) == ',' then table.insert(csv[#csv], line:sub(i,j-1)) i=j+1 end end table.insert(csv[#csv], line:sub(i,j)) end table.insert(csv[1], 'SUM') for i=2,#csv do local sum=0 for j=1,#csv[i] do sum=sum + tonumber(csv[i][j]) end if sum>0 then table.insert(csv[i], sum) end end local newFileData = '' for i=1,#csv do newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' end local file=io.open('file.csv', 'w') file:write(newFileData)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert the following code from Lua to PHP, ensuring the logic remains intact.
local csv={} for line in io.lines('file.csv') do table.insert(csv, {}) local i=1 for j=1,#line do if line:sub(j,j) == ',' then table.insert(csv[#csv], line:sub(i,j-1)) i=j+1 end end table.insert(csv[#csv], line:sub(i,j)) end table.insert(csv[1], 'SUM') for i=2,#csv do local sum=0 for j=1,#csv[i] do sum=sum + tonumber(csv[i][j]) end if sum>0 then table.insert(csv[i], sum) end end local newFileData = '' for i=1,#csv do newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' end local file=io.open('file.csv', 'w') file:write(newFileData)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Keep all operations the same but rewrite the snippet in PHP.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Maintain the same structure and functionality when rewriting this code in PHP.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Produce a functionally identical PHP code for the snippet given in MATLAB.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Transform the following MATLAB implementation into PHP, maintaining the same output and logic.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert the following code from Nim to PHP, ensuring the logic remains intact.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the following Nim code into PHP without altering its purpose.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the programming language of this snippet from OCaml to PHP without modifying what it does.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the OCaml version.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this Pascal code.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; end.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Maintain the same structure and functionality when rewriting this code in PHP.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; end.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same code in PHP as shown below in Perl.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Perl version.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert the following code from PowerShell to PHP, ensuring the logic remains intact.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same algorithm in PHP as shown in this PowerShell implementation.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the provided R code into PHP while preserving the original functionality.
write.csv(df, file = "foo.csv",row.names = FALSE)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the following R code into PHP without altering its purpose.
write.csv(df, file = "foo.csv",row.names = FALSE)
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same algorithm in PHP as shown in this Racket implementation.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same algorithm in PHP as shown in this Racket implementation.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this COBOL code.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Maintain the same structure and functionality when rewriting this code in PHP.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Preserve the algorithm and functionality while converting the code from REXX to PHP.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Please provide an equivalent version of this REXX code in PHP.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate a PHP translation of this Ruby snippet without changing its computational steps.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Preserve the algorithm and functionality while converting the code from Ruby to PHP.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Translate the given Scala code snippet into PHP without altering its behavior.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Convert the following code from Scala to PHP, ensuring the logic remains intact.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Transform the following Tcl implementation into PHP, maintaining the same output and logic.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this Tcl code.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the provided C code into Rust while preserving the original functionality.
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Port the following code from C to Rust with equivalent syntax and logic.
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Maintain the same structure and functionality when rewriting this code in Rust.
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Preserve the algorithm and functionality while converting the code from C# to Rust.
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Please provide an equivalent version of this C# code in Rust.
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Rewrite this program in Rust while keeping its functionality equivalent to the Java version.
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Ensure the translated Rust code behaves exactly like the original Java snippet.
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Write a version of this Go function in Rust with identical behavior.
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Rewrite this program in Python while keeping its functionality equivalent to the Rust version.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Rewrite the snippet below in Python so it works the same as the original Rust code.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Change the following Rust code into VB without altering its purpose.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Port the provided Rust code into VB while preserving the original functionality.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Ensure the translated Rust code behaves exactly like the original C++ snippet.
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Rewrite the snippet below in Rust so it works the same as the original Go code.
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
Transform the following Ada implementation into C#, maintaining the same output and logic.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Change the following Ada code into C# without altering its purpose.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Change the following Ada code into Go without altering its purpose.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Change the following Ada code into Go without altering its purpose.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Generate a Java translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Convert this Ada snippet to Java and keep its semantics consistent.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Convert the following code from Ada to Python, ensuring the logic remains intact.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Generate an equivalent Python version of this Ada code.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Change the programming language of this snippet from Ada to VB without modifying what it does.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Change the following Ada code into VB without altering its purpose.
with Ada.Text_IO; with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables; procedure URL_Parser is procedure Parse (URL : in String) is use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables; procedure Put_Cond (Item : in String; Value : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond; Obj : Object; List : Table_Type; begin Put_Line ("Parsing " & URL); Obj := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj))); Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj)); if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse; begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:John.Doe@example.com"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://alice@example.com"); Parse ("https://bob:pass@example.com/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Generate an equivalent C# version of this Elixir code.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Rewrite the snippet below in C# so it works the same as the original Elixir code.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Change the programming language of this snippet from Elixir to Java without modifying what it does.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Preserve the algorithm and functionality while converting the code from Elixir to Java.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Maintain the same structure and functionality when rewriting this code in Python.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Preserve the algorithm and functionality while converting the code from Elixir to Python.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this Elixir snippet to VB and keep its semantics consistent.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Translate this program into VB but keep the logic exactly as in Elixir.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Please provide an equivalent version of this Elixir code in Go.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Write the same algorithm in Go as shown in this Elixir implementation.
test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] Enum.each(test_cases, fn str -> IO.puts "\n IO.inspect URI.parse(str) end)
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Please provide an equivalent version of this F# code in C#.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Transform the following F# implementation into C#, maintaining the same output and logic.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Write the same algorithm in Java as shown in this F# implementation.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Produce a functionally identical Java code for the snippet given in F#.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Write the same code in Python as shown below in F#.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Preserve the algorithm and functionality while converting the code from F# to Python.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Keep all operations the same but rewrite the snippet in VB.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert this F# block to VB, preserving its control flow and logic.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Generate a Go translation of this F# snippet without changing its computational steps.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Write a version of this F# function in Go with identical behavior.
open System open System.Text.RegularExpressions let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v let toUri = fun s -> Uri(s.ToString()) let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri) urisFromString """ foo: urn:example:animal:ferret:nose jdbc:mysql: ftp: http: ldap: mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 """ |> Seq.iter (fun u -> writeline "\nURI:" (u.ToString()) writeline " scheme:" (u.Scheme) writeline " host:" (u.Host) writeline " port:" (if u.Port < 0 then "" else u.Port.ToString()) writeline " path:" (u.AbsolutePath) writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "") writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "") )
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }