Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {
return true;
}
else {
return false;
}
}
function explore_field($field) {
if (!isset($_SESSION['minesweeper'][$field])
|| !in_array($_SESSION['minesweeper'][$field],
array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {
return;
}
$mines = 0;
$fields = &$_SESSION['minesweeper'];
if ($field % MINEGRID_WIDTH !== 1) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);
$mines += check_field(@$fields[$field - 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);
}
$mines += check_field(@$fields[$field - MINEGRID_WIDTH]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH]);
if ($field % MINEGRID_WIDTH !== 0) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);
$mines += check_field(@$fields[$field + 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);
}
$fields[$field] = $mines;
if ($mines === 0) {
if ($field % MINEGRID_WIDTH !== 1) {
explore_field($field - MINEGRID_WIDTH - 1);
explore_field($field - 1);
explore_field($field + MINEGRID_WIDTH - 1);
}
explore_field($field - MINEGRID_WIDTH);
explore_field($field + MINEGRID_WIDTH);
if ($field % MINEGRID_WIDTH !== 0) {
explore_field($field - MINEGRID_WIDTH + 1);
explore_field($field + 1);
explore_field($field + MINEGRID_WIDTH + 1);
}
}
}
session_start(); // will start session storage
if (!isset($_SESSION['minesweeper'])) {
$_SESSION['minesweeper'] = array_fill(1,
MINEGRID_WIDTH * MINEGRID_HEIGHT,
MINESWEEPER_NOT_EXPLORED);
$number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,
0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);
$random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);
foreach ($random_keys as $key) {
$_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;
}
$_SESSION['numberofmines'] = $number_of_mines;
}
if (isset($_GET['explore'])) {
if(isset($_SESSION['minesweeper'][$_GET['explore']])) {
switch ($_SESSION['minesweeper'][$_GET['explore']]) {
case MINESWEEPER_NOT_EXPLORED:
explore_field($_GET['explore']);
break;
case MINESWEEPER_MINE:
$lost = 1;
$_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
elseif (isset($_GET['flag'])) {
if(isset($_SESSION['minesweeper'][$_GET['flag']])) {
$tile = &$_SESSION['minesweeper'][$_GET['flag']];
switch ($tile) {
case MINESWEEPER_NOT_EXPLORED:
$tile = MINESWEEPER_FLAGGED;
break;
case MINESWEEPER_MINE:
$tile = MINESWEEPER_FLAGGED_MINE;
break;
case MINESWEEPER_FLAGGED:
$tile = MINESWEEPER_NOT_EXPLORED;
break;
case MINESWEEPER_FLAGGED_MINE:
$tile = MINESWEEPER_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
if (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])
&& !in_array(MINESWEEPER_FLAGGED, $_SESSION['minesweeper'])) {
$won = true;
}
?>
<!DOCTYPE html>
<title>Minesweeper</title>
<style>
table {
border-collapse: collapse;
}
td, a {
text-align: center;
width: 1em;
height: 1em;
}
a {
display: block;
color: black;
text-decoration: none;
font-size: 2em;
}
</style>
<script>
function flag(number, e) {
if (e.which === 2 || e.which === 3) {
location = '?flag=' + number;
return false;
}
}
</script>
<?php
echo "<p>This field contains $_SESSION[numberofmines] mines.";
?>
<table border="1">
<?php
$mine_copy = $_SESSION['minesweeper'];
for ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {
echo '<tr>';
for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {
echo '<td>';
$number = array_shift($mine_copy);
switch ($number) {
case MINESWEEPER_FLAGGED:
case MINESWEEPER_FLAGGED_MINE:
if (!empty($lost) || !empty($won)) {
if ($number === MINESWEEPER_FLAGGED_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
else {
echo '<a href=# onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">?</a>';
}
break;
case ACTIVATED_MINE:
echo '<a>:(</a>';
break;
case MINESWEEPER_MINE:
case MINESWEEPER_NOT_EXPLORED:
if (!empty($lost)) {
if ($number === MINESWEEPER_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
elseif (!empty($won)) {
echo '<a>*</a>';
}
else {
echo '<a href="?explore=',
($x - 1) * MINEGRID_WIDTH + $y,
'" onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">.</a>';
}
break;
case 0:
echo '<a></a>';
break;
default:
echo '<a>', $number, '</a>';
break;
}
}
}
?>
</table>
<?php
if (!empty($lost)) {
unset($_SESSION['minesweeper']);
echo '<p>You lost :(. <a href="?">Reboot?</a>';
}
elseif (!empty($won)) {
unset($_SESSION['minesweeper']);
echo '<p>Congratulations. You won :).';
}
|
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) )
|
Produce a functionally identical Python code for the snippet given in PHP. | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?>
| class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)__')
__reBleh = re.compile('\Wbleh$')
@property
def reBleh(self):
return self.__reBleh
def __init__(self, name, *args):
super(Child, self).__init__(name)
self.args = args
def __dir__(self):
myDir = filter(
lambda p: not self.__rePrivate.match(p),
list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
)))
return myDir + map(
lambda p: p + '_bleh',
filter(
lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
myDir))
def __getattr__(self, name):
if name[-5:] == '_bleh':
return str(getattr(self, name[:-5])) + ' bleh'
if hasattr(super(Child, chld), '__getattr__'):
return super(Child, self).__getattr__(name)
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __setattr__(self, name, value):
if name[-5:] == '_bleh':
if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
setattr(self, name[:-5], self.reBleh.sub('', value))
elif hasattr(super(Child, self), '__setattr__'):
super(Child, self).__setattr__(name, value)
elif hasattr(self, '__dict__'):
self.__dict__[name] = value
def __repr__(self):
return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
def doStuff(self):
return (1+1.0/1e6) ** 1e6
par = Parent('par')
par.parent = True
dir(par)
inspect.getmembers(par)
chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)
inspect.getmembers(chld)
|
Write a version of this PHP function in Python with identical behavior. | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?>
| class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)__')
__reBleh = re.compile('\Wbleh$')
@property
def reBleh(self):
return self.__reBleh
def __init__(self, name, *args):
super(Child, self).__init__(name)
self.args = args
def __dir__(self):
myDir = filter(
lambda p: not self.__rePrivate.match(p),
list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
)))
return myDir + map(
lambda p: p + '_bleh',
filter(
lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
myDir))
def __getattr__(self, name):
if name[-5:] == '_bleh':
return str(getattr(self, name[:-5])) + ' bleh'
if hasattr(super(Child, chld), '__getattr__'):
return super(Child, self).__getattr__(name)
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __setattr__(self, name, value):
if name[-5:] == '_bleh':
if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
setattr(self, name[:-5], self.reBleh.sub('', value))
elif hasattr(super(Child, self), '__setattr__'):
super(Child, self).__setattr__(name, value)
elif hasattr(self, '__dict__'):
self.__dict__[name] = value
def __repr__(self):
return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
def doStuff(self):
return (1+1.0/1e6) ** 1e6
par = Parent('par')
par.parent = True
dir(par)
inspect.getmembers(par)
chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)
inspect.getmembers(chld)
|
Generate an equivalent Python version of this PHP code. | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?>
| class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)__')
__reBleh = re.compile('\Wbleh$')
@property
def reBleh(self):
return self.__reBleh
def __init__(self, name, *args):
super(Child, self).__init__(name)
self.args = args
def __dir__(self):
myDir = filter(
lambda p: not self.__rePrivate.match(p),
list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
)))
return myDir + map(
lambda p: p + '_bleh',
filter(
lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
myDir))
def __getattr__(self, name):
if name[-5:] == '_bleh':
return str(getattr(self, name[:-5])) + ' bleh'
if hasattr(super(Child, chld), '__getattr__'):
return super(Child, self).__getattr__(name)
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __setattr__(self, name, value):
if name[-5:] == '_bleh':
if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
setattr(self, name[:-5], self.reBleh.sub('', value))
elif hasattr(super(Child, self), '__setattr__'):
super(Child, self).__setattr__(name, value)
elif hasattr(self, '__dict__'):
self.__dict__[name] = value
def __repr__(self):
return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
def doStuff(self):
return (1+1.0/1e6) ** 1e6
par = Parent('par')
par.parent = True
dir(par)
inspect.getmembers(par)
chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)
inspect.getmembers(chld)
|
Port the provided PHP code into Python while preserving the original functionality. | <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = array();
foreach (explode("\n", $str) as $line)
$fieldsbyrow[] = explode('$', $line);
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
$result = '';
foreach ($fieldsbyrow as $fields)
$result .= implode(' ', $fields) . "\n";
return $result;
}
$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
foreach (array('L', 'R', 'C') as $j)
echo aligner($textinfile, $j);
?>
| from itertools import zip_longest
txt =
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
|
Rewrite the snippet below in Python so it works the same as the original PHP code. | <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = array();
foreach (explode("\n", $str) as $line)
$fieldsbyrow[] = explode('$', $line);
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
$result = '';
foreach ($fieldsbyrow as $fields)
$result .= implode(' ', $fields) . "\n";
return $result;
}
$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
foreach (array('L', 'R', 'C') as $j)
echo aligner($textinfile, $j);
?>
| from itertools import zip_longest
txt =
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
|
Rewrite this program in Python while keeping its functionality equivalent to the PHP version. | <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = array();
foreach (explode("\n", $str) as $line)
$fieldsbyrow[] = explode('$', $line);
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
$result = '';
foreach ($fieldsbyrow as $fields)
$result .= implode(' ', $fields) . "\n";
return $result;
}
$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
foreach (array('L', 'R', 'C') as $j)
echo aligner($textinfile, $j);
?>
| from itertools import zip_longest
txt =
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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 following PHP code into Python without altering its purpose. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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)
|
Produce a functionally identical Python code for the snippet given in PHP. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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 the following code from PHP to Python, ensuring the logic remains intact. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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)
|
Write a version of this PHP function in Python with identical behavior. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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)
|
Maintain the same structure and functionality when rewriting this code in Python. | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto: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',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}
| 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 the following code from PHP to Python, ensuring the logic remains intact. | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
| >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
|
Produce a language-to-language conversion: from PHP to Python, same semantics. | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
| >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
| >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
| import inspect
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Super method'
@staticmethod
def supStatic():
return 'static method'
class Other(object):
def otherMethod(self):
return 'other method'
class Sub(Other, Super):
def __init__(self, name, *args):
super(Sub, self).__init__(name);
self.rest = args;
self.methods = {}
def __dir__(self):
return list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
+ self.methods.keys() \
))
def __getattr__(self, name):
if name in self.methods:
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
if self.methods[name].__code__.co_varnames[0] == 'self':
return self.methods[name].__get__(self, type(self))
if self.methods[name].__code__.co_varnames[0] == 'cls':
return self.methods[name].__get__(type(self), type)
return self.methods[name]
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __str__(self):
return "Sub(%s)" % self.name
def doSub():
return 'did sub stuff'
@classmethod
def cls(cls):
return 'cls method (in Sub)'
@classmethod
def subCls(cls):
return 'Sub method'
@staticmethod
def subStatic():
return 'Sub method'
sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x
[method for method in dir(sub) if callable(getattr(sub, method))]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
inspect.getmembers(sub, predicate=inspect.ismethod)
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
|
Write the same algorithm in Python as shown in this PHP implementation. | <?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
| import inspect
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Super method'
@staticmethod
def supStatic():
return 'static method'
class Other(object):
def otherMethod(self):
return 'other method'
class Sub(Other, Super):
def __init__(self, name, *args):
super(Sub, self).__init__(name);
self.rest = args;
self.methods = {}
def __dir__(self):
return list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
+ self.methods.keys() \
))
def __getattr__(self, name):
if name in self.methods:
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
if self.methods[name].__code__.co_varnames[0] == 'self':
return self.methods[name].__get__(self, type(self))
if self.methods[name].__code__.co_varnames[0] == 'cls':
return self.methods[name].__get__(type(self), type)
return self.methods[name]
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __str__(self):
return "Sub(%s)" % self.name
def doSub():
return 'did sub stuff'
@classmethod
def cls(cls):
return 'cls method (in Sub)'
@classmethod
def subCls(cls):
return 'Sub method'
@staticmethod
def subStatic():
return 'Sub method'
sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x
[method for method in dir(sub) if callable(getattr(sub, method))]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
inspect.getmembers(sub, predicate=inspect.ismethod)
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
|
Change the following PHP code into Python without altering its purpose. | <?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
| import inspect
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Super method'
@staticmethod
def supStatic():
return 'static method'
class Other(object):
def otherMethod(self):
return 'other method'
class Sub(Other, Super):
def __init__(self, name, *args):
super(Sub, self).__init__(name);
self.rest = args;
self.methods = {}
def __dir__(self):
return list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
+ self.methods.keys() \
))
def __getattr__(self, name):
if name in self.methods:
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
if self.methods[name].__code__.co_varnames[0] == 'self':
return self.methods[name].__get__(self, type(self))
if self.methods[name].__code__.co_varnames[0] == 'cls':
return self.methods[name].__get__(type(self), type)
return self.methods[name]
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __str__(self):
return "Sub(%s)" % self.name
def doSub():
return 'did sub stuff'
@classmethod
def cls(cls):
return 'cls method (in Sub)'
@classmethod
def subCls(cls):
return 'Sub method'
@staticmethod
def subStatic():
return 'Sub method'
sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x
[method for method in dir(sub) if callable(getattr(sub, method))]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
inspect.getmembers(sub, predicate=inspect.ismethod)
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
|
Generate an equivalent Python version of this PHP code. | # this is commented
|
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
Produce a functionally identical Python code for the snippet given in PHP. | # this is commented
|
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | # this is commented
|
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
Write the same code in Python as shown below in PHP. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
|
Write a version of this PHP function in Python with identical behavior. | <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
|
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
|
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
|
Generate an equivalent Python version of this PHP code. | <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
|
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
|
Produce a functionally identical Python code for the snippet given in PHP. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Generate an equivalent Python version of this PHP code. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Produce a language-to-language conversion: from PHP to Python, same semantics. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Write a version of this PHP function in Python with identical behavior. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Write the same algorithm in Python as shown in this PHP implementation. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Write the same code in Python as shown below in PHP. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
Generate an equivalent Python version of this PHP code. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Maintain the same structure and functionality when rewriting this code in Python. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| >>> exec
10
|
Keep all operations the same but rewrite the snippet in Python. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Please provide an equivalent version of this PHP code in Python. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Change the following PHP code into Python without altering its purpose. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Maintain the same structure and functionality when rewriting this code in Python. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Translate the given PHP code snippet into Python without altering its behavior. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
|
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
|
Convert this PHP snippet to Python and keep its semantics consistent. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = $num1 & $m_1;
$num2 = $num2 & $m_1;
if ($c == '1') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_128;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 6;
$num2 = $num2 << 25;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '2') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_16;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 3;
$num2 = $num2 << 28;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '3') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_8;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 2;
$num2 = $num2 << 29;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '4') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 1;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 30;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '5') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 5;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 26;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '6') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 12;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 19;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '7') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFF00;
$num1 = $num1 + (( $num2 & 0xFF ) << 24 );
$num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );
$num2 = $num2 & $m_16777216;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '8') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFFFF;
$num1 = $num1 << 16;
$numx = $num2 >> 1;
$numx = $numx & $msr;
$numx = $numx >> 23;
$num1 = $num1 + $numx;
$num2 = $num2 & 0xFF0000;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '9') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = ~(int)$num2;
$flag = False;
} else {
$num1 = $num2;
}
$num2 = $num1;
}
return sprintf('%u', $num1 & $m_1);
}
| def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:
print("c: %s num1: %08x num2: %08x" % (c, num1, num2))
if c == '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
elif c == '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
elif c == '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
elif c == '4':
num1 = num2 << 1
num2 = num2 >> 31
elif c == '5':
num1 = num2 << 5
num2 = num2 >> 27
elif c == '6':
num1 = num2 << 12
num2 = num2 >> 20
elif c == '7':
num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )
num2 = ( num2 & 0xFF000000 ) >> 8
elif c == '8':
num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )
num2 = (num2 & 0x00FF0000) >> 8
elif c == '9':
num1 = ~num2
else :
num1 = num2
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if (c not in "09"):
num1 |= num2
if test:
print(" num1: %08x num2: %08x" % (num1, num2))
num2 = num1
return num1
def test_passwd_calc(passwd, nonce, expected):
res = ownCalcPass(passwd, nonce, False)
m = passwd+' '+nonce+' '+str(res)+' '+str(expected)
if res == int(expected) :
print('PASS '+m)
else :
print('FAIL '+m)
if __name__ == '__main__':
test_passwd_calc('12345','603356072','25280520')
test_passwd_calc('12345','410501656','119537670')
test_passwd_calc('12345','630292165','4269684735')
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = $num1 & $m_1;
$num2 = $num2 & $m_1;
if ($c == '1') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_128;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 6;
$num2 = $num2 << 25;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '2') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_16;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 3;
$num2 = $num2 << 28;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '3') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_8;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 2;
$num2 = $num2 << 29;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '4') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 1;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 30;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '5') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 5;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 26;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '6') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 12;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 19;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '7') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFF00;
$num1 = $num1 + (( $num2 & 0xFF ) << 24 );
$num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );
$num2 = $num2 & $m_16777216;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '8') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFFFF;
$num1 = $num1 << 16;
$numx = $num2 >> 1;
$numx = $numx & $msr;
$numx = $numx >> 23;
$num1 = $num1 + $numx;
$num2 = $num2 & 0xFF0000;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '9') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = ~(int)$num2;
$flag = False;
} else {
$num1 = $num2;
}
$num2 = $num1;
}
return sprintf('%u', $num1 & $m_1);
}
| def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:
print("c: %s num1: %08x num2: %08x" % (c, num1, num2))
if c == '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
elif c == '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
elif c == '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
elif c == '4':
num1 = num2 << 1
num2 = num2 >> 31
elif c == '5':
num1 = num2 << 5
num2 = num2 >> 27
elif c == '6':
num1 = num2 << 12
num2 = num2 >> 20
elif c == '7':
num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )
num2 = ( num2 & 0xFF000000 ) >> 8
elif c == '8':
num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )
num2 = (num2 & 0x00FF0000) >> 8
elif c == '9':
num1 = ~num2
else :
num1 = num2
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if (c not in "09"):
num1 |= num2
if test:
print(" num1: %08x num2: %08x" % (num1, num2))
num2 = num1
return num1
def test_passwd_calc(passwd, nonce, expected):
res = ownCalcPass(passwd, nonce, False)
m = passwd+' '+nonce+' '+str(res)+' '+str(expected)
if res == int(expected) :
print('PASS '+m)
else :
print('FAIL '+m)
if __name__ == '__main__':
test_passwd_calc('12345','603356072','25280520')
test_passwd_calc('12345','410501656','119537670')
test_passwd_calc('12345','630292165','4269684735')
|
Port the following code from PHP to Python with equivalent syntax and logic. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = $num1 & $m_1;
$num2 = $num2 & $m_1;
if ($c == '1') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_128;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 6;
$num2 = $num2 << 25;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '2') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_16;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 3;
$num2 = $num2 << 28;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '3') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_8;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 2;
$num2 = $num2 << 29;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '4') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 1;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 30;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '5') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 5;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 26;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '6') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 12;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 19;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '7') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFF00;
$num1 = $num1 + (( $num2 & 0xFF ) << 24 );
$num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );
$num2 = $num2 & $m_16777216;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '8') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFFFF;
$num1 = $num1 << 16;
$numx = $num2 >> 1;
$numx = $numx & $msr;
$numx = $numx >> 23;
$num1 = $num1 + $numx;
$num2 = $num2 & 0xFF0000;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '9') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = ~(int)$num2;
$flag = False;
} else {
$num1 = $num2;
}
$num2 = $num1;
}
return sprintf('%u', $num1 & $m_1);
}
| def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:
print("c: %s num1: %08x num2: %08x" % (c, num1, num2))
if c == '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
elif c == '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
elif c == '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
elif c == '4':
num1 = num2 << 1
num2 = num2 >> 31
elif c == '5':
num1 = num2 << 5
num2 = num2 >> 27
elif c == '6':
num1 = num2 << 12
num2 = num2 >> 20
elif c == '7':
num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )
num2 = ( num2 & 0xFF000000 ) >> 8
elif c == '8':
num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )
num2 = (num2 & 0x00FF0000) >> 8
elif c == '9':
num1 = ~num2
else :
num1 = num2
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if (c not in "09"):
num1 |= num2
if test:
print(" num1: %08x num2: %08x" % (num1, num2))
num2 = num1
return num1
def test_passwd_calc(passwd, nonce, expected):
res = ownCalcPass(passwd, nonce, False)
m = passwd+' '+nonce+' '+str(res)+' '+str(expected)
if res == int(expected) :
print('PASS '+m)
else :
print('FAIL '+m)
if __name__ == '__main__':
test_passwd_calc('12345','603356072','25280520')
test_passwd_calc('12345','410501656','119537670')
test_passwd_calc('12345','630292165','4269684735')
|
Convert the following code from PHP to Python, ensuring the logic remains intact. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
|
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
Generate an equivalent Python version of this PHP code. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
|
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
Rewrite this program in Python while keeping its functionality equivalent to the PHP version. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
|
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
Generate a Python translation of this PHP snippet without changing its computational steps. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == "r") {
$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "g") {
$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "b") {
$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
|
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
im = np.array(im, dtype=float)
im2 = gaussian_filter(im, blur)
im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])
im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])
grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
theta = np.arctan2(im3v, im3h)
thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5
gradSup = grad.copy()
for r in range(im.shape[0]):
for c in range(im.shape[1]):
if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
gradSup[r, c] = 0
continue
tq = thetaQ[r, c] % 4
if tq == 0:
if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
gradSup[r, c] = 0
if tq == 1:
if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
gradSup[r, c] = 0
if tq == 2:
if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
gradSup[r, c] = 0
if tq == 3:
if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
gradSup[r, c] = 0
strongEdges = (gradSup > highThreshold)
thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)
finalEdges = strongEdges.copy()
currentPixels = []
for r in range(1, im.shape[0]-1):
for c in range(1, im.shape[1]-1):
if thresholdedEdges[r, c] != 1:
continue
localPatch = thresholdedEdges[r-1:r+2,c-1:c+2]
patchMax = localPatch.max()
if patchMax == 2:
currentPixels.append((r, c))
finalEdges[r, c] = 1
while len(currentPixels) > 0:
newPix = []
for r, c in currentPixels:
for dr in range(-1, 2):
for dc in range(-1, 2):
if dr == 0 and dc == 0: continue
r2 = r+dr
c2 = c+dc
if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:
newPix.append((r2, c2))
finalEdges[r2, c2] = 1
currentPixels = newPix
return finalEdges
if __name__=="__main__":
im = imread("test.jpg", mode="L")
finalEdges = CannyEdgeDetector(im)
imshow(finalEdges)
|
Convert this PHP block to Python, preserving its control flow and logic. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == "r") {
$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "g") {
$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "b") {
$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
|
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
im = np.array(im, dtype=float)
im2 = gaussian_filter(im, blur)
im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])
im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])
grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
theta = np.arctan2(im3v, im3h)
thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5
gradSup = grad.copy()
for r in range(im.shape[0]):
for c in range(im.shape[1]):
if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
gradSup[r, c] = 0
continue
tq = thetaQ[r, c] % 4
if tq == 0:
if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
gradSup[r, c] = 0
if tq == 1:
if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
gradSup[r, c] = 0
if tq == 2:
if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
gradSup[r, c] = 0
if tq == 3:
if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
gradSup[r, c] = 0
strongEdges = (gradSup > highThreshold)
thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)
finalEdges = strongEdges.copy()
currentPixels = []
for r in range(1, im.shape[0]-1):
for c in range(1, im.shape[1]-1):
if thresholdedEdges[r, c] != 1:
continue
localPatch = thresholdedEdges[r-1:r+2,c-1:c+2]
patchMax = localPatch.max()
if patchMax == 2:
currentPixels.append((r, c))
finalEdges[r, c] = 1
while len(currentPixels) > 0:
newPix = []
for r, c in currentPixels:
for dr in range(-1, 2):
for dc in range(-1, 2):
if dr == 0 and dc == 0: continue
r2 = r+dr
c2 = c+dc
if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:
newPix.append((r2, c2))
finalEdges[r2, c2] = 1
currentPixels = newPix
return finalEdges
if __name__=="__main__":
im = imread("test.jpg", mode="L")
finalEdges = CannyEdgeDetector(im)
imshow(finalEdges)
|
Change the programming language of this snippet from PHP to Python without modifying what it does. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == "r") {
$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "g") {
$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "b") {
$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
|
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
im = np.array(im, dtype=float)
im2 = gaussian_filter(im, blur)
im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])
im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])
grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
theta = np.arctan2(im3v, im3h)
thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5
gradSup = grad.copy()
for r in range(im.shape[0]):
for c in range(im.shape[1]):
if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
gradSup[r, c] = 0
continue
tq = thetaQ[r, c] % 4
if tq == 0:
if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
gradSup[r, c] = 0
if tq == 1:
if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
gradSup[r, c] = 0
if tq == 2:
if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
gradSup[r, c] = 0
if tq == 3:
if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
gradSup[r, c] = 0
strongEdges = (gradSup > highThreshold)
thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)
finalEdges = strongEdges.copy()
currentPixels = []
for r in range(1, im.shape[0]-1):
for c in range(1, im.shape[1]-1):
if thresholdedEdges[r, c] != 1:
continue
localPatch = thresholdedEdges[r-1:r+2,c-1:c+2]
patchMax = localPatch.max()
if patchMax == 2:
currentPixels.append((r, c))
finalEdges[r, c] = 1
while len(currentPixels) > 0:
newPix = []
for r, c in currentPixels:
for dr in range(-1, 2):
for dc in range(-1, 2):
if dr == 0 and dc == 0: continue
r2 = r+dr
c2 = c+dc
if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:
newPix.append((r2, c2))
finalEdges[r2, c2] = 1
currentPixels = newPix
return finalEdges
if __name__=="__main__":
im = imread("test.jpg", mode="L")
finalEdges = CannyEdgeDetector(im)
imshow(finalEdges)
|
Convert this PHP snippet to Python and keep its semantics consistent. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
| class empty(object):
pass
e = empty()
|
Keep all operations the same but rewrite the snippet in Python. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
| class empty(object):
pass
e = empty()
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
| class empty(object):
pass
e = empty()
|
Keep all operations the same but rewrite the snippet in Python. | <?php
class PeriodicTable
{
private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);
private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);
public function rowAndColumn($n)
{
$i = 7;
while ($this->aArray[$i] > $n)
$i--;
$m = $n + $this->bArray[$i];
return array(floor($m / 18) + 1, $m % 18 + 1);
}
}
$pt = new PeriodicTable();
foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {
list($r, $c) = $pt->rowAndColumn($n);
echo $n, " -> ", $r, " ", $c, PHP_EOL;
}
?>
| def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble:
nb_elem = noble - prev_noble
rank = atomic - prev_noble
if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:
row += 2
col = rank + 1
else:
nb_empty = LINE_WIDTH - nb_elem
inside_left_element_rank = 2 if noble > 2 else 1
col = rank + (nb_empty if rank > inside_left_element_rank else 0)
break
prev_noble = noble
return row+1, col
TESTS = {
1: (1, 1),
2: (1, 18),
29: (4,11),
42: (5, 6),
58: (8, 5),
59: (8, 6),
57: (8, 4),
71: (8, 18),
72: (6, 4),
89: (9, 4),
90: (9, 5),
103: (9, 18),
}
for input, out in TESTS.items():
found = perta(input)
print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
class PeriodicTable
{
private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);
private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);
public function rowAndColumn($n)
{
$i = 7;
while ($this->aArray[$i] > $n)
$i--;
$m = $n + $this->bArray[$i];
return array(floor($m / 18) + 1, $m % 18 + 1);
}
}
$pt = new PeriodicTable();
foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {
list($r, $c) = $pt->rowAndColumn($n);
echo $n, " -> ", $r, " ", $c, PHP_EOL;
}
?>
| def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble:
nb_elem = noble - prev_noble
rank = atomic - prev_noble
if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:
row += 2
col = rank + 1
else:
nb_empty = LINE_WIDTH - nb_elem
inside_left_element_rank = 2 if noble > 2 else 1
col = rank + (nb_empty if rank > inside_left_element_rank else 0)
break
prev_noble = noble
return row+1, col
TESTS = {
1: (1, 1),
2: (1, 18),
29: (4,11),
42: (5, 6),
58: (8, 5),
59: (8, 6),
57: (8, 4),
71: (8, 18),
72: (6, 4),
89: (9, 4),
90: (9, 5),
103: (9, 18),
}
for input, out in TESTS.items():
found = perta(input)
print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
|
Write a version of this PHP function in Python with identical behavior. | <?php
class PeriodicTable
{
private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);
private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);
public function rowAndColumn($n)
{
$i = 7;
while ($this->aArray[$i] > $n)
$i--;
$m = $n + $this->bArray[$i];
return array(floor($m / 18) + 1, $m % 18 + 1);
}
}
$pt = new PeriodicTable();
foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {
list($r, $c) = $pt->rowAndColumn($n);
echo $n, " -> ", $r, " ", $c, PHP_EOL;
}
?>
| def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble:
nb_elem = noble - prev_noble
rank = atomic - prev_noble
if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:
row += 2
col = rank + 1
else:
nb_empty = LINE_WIDTH - nb_elem
inside_left_element_rank = 2 if noble > 2 else 1
col = rank + (nb_empty if rank > inside_left_element_rank else 0)
break
prev_noble = noble
return row+1, col
TESTS = {
1: (1, 1),
2: (1, 18),
29: (4,11),
42: (5, 6),
58: (8, 5),
59: (8, 6),
57: (8, 4),
71: (8, 18),
72: (6, 4),
89: (9, 4),
90: (9, 5),
103: (9, 18),
}
for input, out in TESTS.items():
found = perta(input)
print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
|
Generate a VB translation of this PHP snippet without changing its computational steps. | class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
| Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)
Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height)
Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)
Dim bytes(bufferSize - 1) As Byte
Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)
Dim index As Integer = header.Length
For y As Integer = 0 To rasterBitmap.Height - 1
For x As Integer = 0 To rasterBitmap.Width - 1
Dim color As Rgb = rasterBitmap.GetPixel(x, y)
bytes(index) = color.R
bytes(index + 1) = color.G
bytes(index + 2) = color.B
index += 3
Next
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub
|
Convert this PHP block to VB, preserving its control flow and logic. | <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
| Option Explicit
Sub DeleteFileOrDirectory()
Dim myPath As String
myPath = "C:\Users\surname.name\Desktop\Docs"
Kill myPath & "\input.txt"
RmDir myPath
End Sub
|
Preserve the algorithm and functionality while converting the code from PHP to VB. | <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
| Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)
|
Can you help me rewrite this code in VB instead of PHP, keeping it the same logically? | <?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return $count % 2;
}
function west($A, $B, $x, $y)
{
if ($A['y'] <= $B['y']) {
if ($y <= $A['y'] || $y > $B['y'] ||
$x >= $A['x'] && $x >= $B['x']) {
return false;
}
if ($x < $A['x'] && $x < $B['x']) {
return true;
}
if ($x == $A['x']) {
if ($y == $A['y']) {
$result1 = NAN;
} else {
$result1 = INF;
}
} else {
$result1 = ($y - $A['y']) / ($x - $A['x']);
}
if ($B['x'] == $A['x']) {
if ($B['y'] == $A['y']) {
$result2 = NAN;
} else {
$result2 = INF;
}
} else {
$result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);
}
return $result1 > $result2;
}
return west($B, $A, $x, $y);
}
$square = [
'name' => 'square',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]
];
$squareHole = [
'name' => 'squareHole',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]
];
$strange = [
'name' => 'strange',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]
];
$hexagon = [
'name' => 'hexagon',
'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]
];
$shapes = [$square, $squareHole, $strange, $hexagon];
$testPoints = [
['lng' => 10, 'lat' => 10],
['lng' => 10, 'lat' => 16],
['lng' => -20, 'lat' => 10],
['lng' => 0, 'lat' => 10],
['lng' => 20, 'lat' => 10],
['lng' => 16, 'lat' => 10],
['lng' => 20, 'lat' => 20]
];
for ($s = 0; $s < count($shapes); $s++) {
$shape = $shapes[$s];
for ($tp = 0; $tp < count($testPoints); $tp++) {
$testPoint = $testPoints[$tp];
echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;
}
}
| Imports System.Math
Module RayCasting
Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}
Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}
Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}
Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}
Private shapes As Integer()()() = {square, squareHole, strange, hexagon}
Public Sub Main()
Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}
For Each shape As Integer()() In shapes
For Each point As Double() In testPoints
Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7)))
Next
Console.WriteLine()
Next
End Sub
Private Function Contains(shape As Integer()(), point As Double()) As Boolean
Dim inside As Boolean = False
Dim length As Integer = shape.Length
For i As Integer = 0 To length - 1
If Intersects(shape(i), shape((i + 1) Mod length), point) Then
inside = Not inside
End If
Next
Return inside
End Function
Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean
If a(1) > b(1) Then Return Intersects(b, a, p)
If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001
If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False
If p(0) < Min(a(0), b(0)) Then Return True
Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))
Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))
Return red >= blue
End Function
End Module
|
Write a version of this PHP function in VB with identical behavior. | <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
| Public Sub Main()
Print countSubstring("the three truths", "th")
Print countSubstring("ababababab", "abab")
Print countSubString("zzzzzzzzzzzzzzz", "z")
End
Function countSubstring(s As String, search As String) As Integer
If s = "" Or search = "" Then Return 0
Dim count As Integer = 0, length As Integer = Len(search)
For i As Integer = 1 To Len(s)
If Mid(s, i, length) = Search Then
count += 1
i += length - 1
End If
Next
Return count
End Function
|
Write the same algorithm in VB as shown in this PHP implementation. | #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
| Imports System.IO
Module Notes
Function Main(ByVal cmdArgs() As String) As Integer
Try
If cmdArgs.Length = 0 Then
Using sr As New StreamReader("NOTES.TXT")
Console.WriteLine(sr.ReadToEnd)
End Using
Else
Using sw As New StreamWriter("NOTES.TXT", True)
sw.WriteLine(Date.Now.ToString())
sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs))
End Using
End If
Catch
End Try
End Function
End Module
|
Write a version of this PHP function in VB with identical behavior. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| Public Function CommonDirectoryPath(ParamArray Paths()) As String
Dim v As Variant
Dim Path() As String, s As String
Dim i As Long, j As Long, k As Long
Const PATH_SEPARATOR As String = "/"
For Each v In Paths
ReDim Preserve Path(0 To i)
Path(i) = v
i = i + 1
Next v
k = 1
Do
For i = 0 To UBound(Path)
If i Then
If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
Exit Do
ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then
Exit Do
End If
Else
j = InStr(k, Path(i), PATH_SEPARATOR)
If j = 0 Then
Exit Do
End If
End If
Next i
s = Left$(Path(0), j + CLng(k <> 1))
k = j + 1
Loop
CommonDirectoryPath = s
End Function
Sub Main()
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") = _
"/home/user1/tmp"
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members", _
"/home/user1/abc/coven/members") = _
"/home/user1"
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/hope/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") = _
"/"
End Sub
|
Ensure the translated VB code behaves exactly like the original PHP snippet. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
Keep all operations the same but rewrite the snippet in VB. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
Port the provided PHP code into VB while preserving the original functionality. | <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
| Option Explicit
Private Lines(1 To 3, 1 To 3) As String
Private Nb As Byte, player As Byte
Private GameWin As Boolean, GameOver As Boolean
Sub Main_TicTacToe()
Dim p As String
InitLines
printLines Nb
Do
p = WhoPlay
Debug.Print p & " play"
If p = "Human" Then
Call HumanPlay
GameWin = IsWinner("X")
Else
Call ComputerPlay
GameWin = IsWinner("O")
End If
If Not GameWin Then GameOver = IsEnd
Loop Until GameWin Or GameOver
If Not GameOver Then
Debug.Print p & " Win !"
Else
Debug.Print "Game Over!"
End If
End Sub
Sub InitLines(Optional S As String)
Dim i As Byte, j As Byte
Nb = 0: player = 0
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
Lines(i, j) = "#"
Next j
Next i
End Sub
Sub printLines(Nb As Byte)
Dim i As Byte, j As Byte, strT As String
Debug.Print "Loop " & Nb
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strT = strT & Lines(i, j)
Next j
Debug.Print strT
strT = vbNullString
Next i
End Sub
Function WhoPlay(Optional S As String) As String
If player = 0 Then
player = 1
WhoPlay = "Human"
Else
player = 0
WhoPlay = "Computer"
End If
End Function
Sub HumanPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Do
L = Application.InputBox("Choose the row", "Numeric only", Type:=1)
If L > 0 And L < 4 Then
C = Application.InputBox("Choose the column", "Numeric only", Type:=1)
If C > 0 And C < 4 Then
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "X"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
End If
End If
Loop Until GoodPlay
End Sub
Sub ComputerPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Randomize Timer
Do
L = Int((Rnd * 3) + 1)
C = Int((Rnd * 3) + 1)
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "O"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
Loop Until GoodPlay
End Sub
Function IsWinner(S As String) As Boolean
Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String
Ch = String(UBound(Lines, 1), S)
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strTL = strTL & Lines(i, j)
strTC = strTC & Lines(j, i)
Next j
If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For
strTL = vbNullString: strTC = vbNullString
Next i
strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)
strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)
If strTL = Ch Or strTC = Ch Then IsWinner = True
End Function
Function IsEnd() As Boolean
Dim i As Byte, j As Byte
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
If Lines(i, j) = "#" Then Exit Function
Next j
Next i
IsEnd = True
End Function
|
Write the same code in VB as shown below in PHP. | <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
| #include "win\winsock2.bi"
Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long
Dim As WSADATA _wsadate
Dim As in_addr addr
Dim As hostent Ptr res
Dim As Integer i = 0
WSAStartup(MAKEWORD(2,2),@_wsadate)
res = gethostbyname(stuff)
If res Then
Print !"\nURL: "; stuff
While (res->h_addr_list[i] <> 0)
addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i]))
Print "IPv4 address: ";*inet_ntoa(addr)
i+=1
Wend
WSACleanup()
Return 1
Else
Print "website error?"
Return 0
End If
End Function
GetSiteAddress "rosettacode.org"
GetSiteAddress "www.kame.net"
Sleep
|
Convert the following code from PHP to VB, ensuring the logic remains intact. | <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
| Private Function call_fn(f As String, n As Long) As Long
call_fn = Application.Run(f, f, n)
End Function
Private Function Y(f As String) As String
Y = f
End Function
Private Function fac(self As String, n As Long) As Long
If n > 1 Then
fac = n * call_fn(self, n - 1)
Else
fac = 1
End If
End Function
Private Function fib(self As String, n As Long) As Long
If n > 1 Then
fib = call_fn(self, n - 1) + call_fn(self, n - 2)
Else
fib = n
End If
End Function
Private Sub test(name As String)
Dim f As String: f = Y(name)
Dim i As Long
Debug.Print name
For i = 1 To 10
Debug.Print call_fn(f, i);
Next i
Debug.Print
End Sub
Public Sub main()
test "fac"
test "fib"
End Sub
|
Change the following PHP code into VB without altering its purpose. | function addsub($x, $y) {
return array($x + $y, $x - $y);
}
| Type Contact
Name As String
firstname As String
Age As Byte
End Type
Function SetContact(N As String, Fn As String, A As Byte) As Contact
SetContact.Name = N
SetContact.firstname = Fn
SetContact.Age = A
End Function
Sub Test_SetContact()
Dim Cont As Contact
Cont = SetContact("SMITH", "John", 23)
Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
End Sub
|
Convert the following code from PHP to VB, ensuring the logic remains intact. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
GenerateNewDigits:
For i = 1 To 4
Digit(i) = [randbetween(1,9)]
Next i
GetUserExpression:
bValidExpression = True
stFailMessage = ""
stFailDigits = ""
stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _
Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game")
bValidDigits = True
stFailDigits = ""
For i = 1 To 4
If InStr(stUserExpression, Digit(i)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Digit(i)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 1 To Len(stUserExpression)
If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
iDigitCount = 0
For i = 1 To Len(stUserExpression)
If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then
iDigitCount = iDigitCount + 1
If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
End If
Next i
If iDigitCount > 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr
End If
If iDigitCount < 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr
End If
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 11 To 99
If Not InStr(stUserExpression, i) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & i
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr
End If
On Error GoTo EvalFail
vResult = Evaluate(stUserExpression)
If Not vResult = 24 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult
End If
If bValidExpression = False Then
vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED")
If vTryAgain = vbRetry Then
vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY")
If vSameDigits = vbYes Then
GoTo GetUserExpression
Else
GoTo GenerateNewDigits
End If
End If
Else
vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _
vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS")
If vTryAgain = vbRetry Then
GoTo GenerateNewDigits
End If
End If
Exit Sub
EvalFail:
bValidExpression = False
vResult = Err.Description
Resume
End Sub
|
Can you help me rewrite this code in VB instead of PHP, keeping it the same logically? | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
GenerateNewDigits:
For i = 1 To 4
Digit(i) = [randbetween(1,9)]
Next i
GetUserExpression:
bValidExpression = True
stFailMessage = ""
stFailDigits = ""
stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _
Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game")
bValidDigits = True
stFailDigits = ""
For i = 1 To 4
If InStr(stUserExpression, Digit(i)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Digit(i)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 1 To Len(stUserExpression)
If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
iDigitCount = 0
For i = 1 To Len(stUserExpression)
If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then
iDigitCount = iDigitCount + 1
If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
End If
Next i
If iDigitCount > 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr
End If
If iDigitCount < 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr
End If
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 11 To 99
If Not InStr(stUserExpression, i) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & i
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr
End If
On Error GoTo EvalFail
vResult = Evaluate(stUserExpression)
If Not vResult = 24 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult
End If
If bValidExpression = False Then
vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED")
If vTryAgain = vbRetry Then
vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY")
If vSameDigits = vbYes Then
GoTo GetUserExpression
Else
GoTo GenerateNewDigits
End If
End If
Else
vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _
vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS")
If vTryAgain = vbRetry Then
GoTo GenerateNewDigits
End If
End If
Exit Sub
EvalFail:
bValidExpression = False
vResult = Err.Description
Resume
End Sub
|
Generate an equivalent VB version of this PHP code. | for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}
| For i = 1 To 10
Console.Write(i)
If i Mod 5 = 0 Then
Console.WriteLine()
Else
Console.Write(", ")
End If
Next
|
Rewrite the snippet below in VB so it works the same as the original PHP code. | <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
| Option Explicit
Private Type Choice
Number As Integer
Name As String
End Type
Private MaxNumber As Integer
Sub Main()
Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$
MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1)
For i = 1 To 3
U(i) = UserChoice
Next
For i = 1 To MaxNumber
t = vbNullString
For j = 1 To 3
If i Mod U(j).Number = 0 Then t = t & U(j).Name
Next
Debug.Print IIf(t = vbNullString, i, t)
Next i
End Sub
Private Function UserChoice() As Choice
Dim ok As Boolean
Do While Not ok
UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1)
UserChoice.Name = InputBox("Enter the corresponding word : ")
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function
|
Convert this PHP block to VB, preserving its control flow and logic. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
Port the provided PHP code into VB while preserving the original functionality. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
Produce a functionally identical VB code for the snippet given in PHP. | $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
| Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial = " _
& TESTSTRING
Debug.Print "uppercase = " _
& UCase(TESTSTRING)
Debug.Print "lowercase = " _
& LCase(TESTSTRING)
Debug.Print "first letter capitalized = " _
& StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) = " _
& CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) = " _
& CStr(LenB(TESTSTRING))
Debug.Print "reversed = " _
& StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) = " _
& InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) = " _
& InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with
& TESTSTRING & "123"
End Sub
|
Translate the given PHP code snippet into VB without altering its behavior. | $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
| Imports System.Security.Cryptography
Imports System.Text
Module MD5hash
Sub Main(args As String())
Console.WriteLine(GetMD5("Visual Basic .Net"))
End Sub
Private Function GetMD5(plainText As String) As String
Dim hash As String = ""
Using hashObject As MD5 = MD5.Create()
Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))
Dim hashBuilder As New StringBuilder
For i As Integer = 0 To ptBytes.Length - 1
hashBuilder.Append(ptBytes(i).ToString("X2"))
Next
hash = hashBuilder.ToString
End Using
Return hash
End Function
End Module
|
Convert this PHP block to VB, preserving its control flow and logic. | <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
| Imports System.Threading
Module Module1
Sub SleepSort(items As IEnumerable(Of Integer))
For Each item In items
Task.Factory.StartNew(Sub()
Thread.Sleep(1000 * item)
Console.WriteLine(item)
End Sub)
Next
End Sub
Sub Main()
SleepSort({1, 5, 2, 1, 8, 10, 3})
Console.ReadKey()
End Sub
End Module
|
Generate an equivalent VB version of this PHP code. | <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
| Public Sub LoopsNested()
Dim a(1 To 10, 1 To 10) As Integer
Randomize
For i = 1 To 10
For j = 1 To 10
a(i, j) = Int(20 * Rnd) + 1
Next j
Next i
For i = 1 To 10
For j = 1 To 10
If a(i, j) <> 20 Then
Debug.Print a(i, j),
Else
i = 10
Exit For
End If
Next j
Debug.Print
Next i
End Sub
|
Generate an equivalent VB version of this PHP code. | <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
| Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
Generate an equivalent VB version of this PHP code. | <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
| Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
Transform the following PHP implementation into VB, maintaining the same output and logic. | $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
| Option Explicit
Sub Main()
Dim myArr() As Variant, i As Long
myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
For i = LBound(myArr) To UBound(myArr)
Debug.Print myArr(i)
Next
End Sub
Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long
ReDim Temp(UBound(Arr))
For i = LBound(Arr) To UBound(Arr)
On Error Resume Next
myColl.Add CStr(Arr(i)), CStr(Arr(i))
If Err.Number > 0 Then
On Error GoTo 0
Else
Temp(cpt) = Arr(i)
cpt = cpt + 1
End If
Next i
ReDim Preserve Temp(cpt - 1)
Remove_Duplicate = Temp
End Function
|
Produce a language-to-language conversion: from PHP to VB, same semantics. | <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
| function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
|
Write the same code in VB as shown below in PHP. | $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
Private myStack()
Private myStackHeight As Integer
Public Function Push(aValue)
myStackHeight = myStackHeight + 1
ReDim Preserve myStack(myStackHeight)
myStack(myStackHeight) = aValue
End Function
Public Function Pop()
If myStackHeight > 0 Then
Pop = myStack(myStackHeight)
myStackHeight = myStackHeight - 1
Else
MsgBox "Pop: stack is empty!"
End If
End Function
Public Function IsEmpty() As Boolean
IsEmpty = (myStackHeight = 0)
End Function
Property Get Size() As Integer
Size = myStackHeight
End Property
|
Convert this PHP snippet to VB and keep its semantics consistent. | <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
| Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
If A = B Then Debug.Print A & " = " & B
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
|
Can you help me rewrite this code in VB instead of PHP, keeping it the same logically? | <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
| type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
end constructor
end type
Dim Settings as TSettings
dim ConfigList as QStringList
dim x as integer
dim StrLine as string
dim StrPara as string
dim StrData as string
function Trim$(Expr as string) as string
Result = Rtrim$(Ltrim$(Expr))
end function
Sub ConfigOption(PData as string)
dim x as integer
for x = 1 to tally(PData, ",") +1
Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x))
next
end sub
Function ConfigBoolean(PData as string) as integer
PData = Trim$(PData)
Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0)
end function
sub ReadSettings
ConfigList.LoadFromFile("Rosetta.cfg")
ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ")
for x = 0 to ConfigList.ItemCount -1
StrLine = Trim$(ConfigList.item(x))
StrPara = Trim$(field$(StrLine," ",1))
StrData = Trim$(lTrim$(StrLine - StrPara))
Select case UCase$(StrPara)
case "FULLNAME" : Settings.FullName = StrData
case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData
case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData)
case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData)
case "OTHERFAMILY" : Call ConfigOption(StrData)
end select
next
end sub
Call ReadSettings
|
Convert this PHP block to VB, preserving its control flow and logic. | <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
| Imports System
Module Sorting_Using_a_Custom_Comparator
Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
Dim result As Integer
result = y.Length - x.Length
If result = 0 Then
result = String.Compare(x, y, True)
End If
Return result
End Function
Sub Main()
Dim strings As String() = {"test", "Zoom", "strings", "a"}
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from PHP to VB. | function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
| Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
|
Generate an equivalent VB version of this PHP code. | function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
| Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
|
Maintain the same structure and functionality when rewriting this code in VB. | <?php
$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';
echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";
function DOG() { return 'Bernie'; }
echo 'There is only 1 dog named ' . dog() . "\n";
| Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
|
Please provide an equivalent version of this PHP code in VB. | for ($i = 10; $i >= 0; $i--)
echo "$i\n";
| For i = 10 To 0 Step -1
Debug.Print i
Next i
|
Convert this PHP block to VB, preserving its control flow and logic. | file_put_contents($filename, $data)
| Option Explicit
Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
"The reverse of Read entire file—for when you want to update or " & vbCrLf & _
"create a file which you would read in its entirety all at once."
Sub Main()
Dim Nb As Integer
Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
Print #1, Text
Close #Nb
End Sub
|
Port the provided PHP code into VB while preserving the original functionality. | for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
| Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
|
Port the provided PHP code into VB while preserving the original functionality. | <?php
function longMult($a, $b)
{
$as = (string) $a;
$bs = (string) $b;
for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
{
for($p = 0; $p < $pi; $p++)
{
$regi[$ai][] = 0;
}
for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
{
$regi[$ai][] = $as[$ai] * $bs[$bi];
}
}
return $regi;
}
function longAdd($arr)
{
$outer = count($arr);
$inner = count($arr[$outer-1]) + $outer;
for($i = 0; $i <= $inner; $i++)
{
for($o = 0; $o < $outer; $o++)
{
$val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;
@$sum[$i] += $val;
}
}
return $sum;
}
function carry($arr)
{
for($i = 0; $i < count($arr); $i++)
{
$s = (string) $arr[$i];
switch(strlen($s))
{
case 2:
$arr[$i] = $s{1};
@$arr[$i+1] += $s{0};
break;
case 3:
$arr[$i] = $s{2};
@$arr[$i+1] += $s{0}.$s{1};
break;
}
}
return ltrim(implode('',array_reverse($arr)),'0');
}
function lm($a,$b)
{
return carry(longAdd(longMult($a,$b)));
}
if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
{
echo 'pass!';
}; // 2^64 * 2^64
| Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D
Structure bd
Public hi, lo As Decimal
End Structure
Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String
Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo),
String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo))
If Not comma Then Return r
Dim rc As String = ""
For i As Integer = r.Length - 3 To 0 Step -3
rc = "," & r.Substring(i, 3) & rc : Next
toStr = r.Substring(0, r.Length Mod 3) & rc
toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0))
End Function
Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal
If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _
Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas
End Function
Sub Main(ByVal args As String())
For p As UInteger = 64 To 95 - 1 Step 30
Dim y As bd, x As bd : a = Pow_dec(2D, p)
WriteLine("The square of (2^{0}): {1,38:n0}", p, a)
x.hi = Math.Floor(a / hm) : x.lo = a Mod hm
Dim BS As BI = BI.Pow(CType(a, BI), 2)
y.lo = x.lo * x.lo : y.hi = x.hi * x.hi
a = x.hi * x.lo * 2D
y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm
While y.lo > mx : y.lo -= mx : y.hi += 1 : End While
WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf,
toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to"))
Next
End Sub
End Module
|
Change the following PHP code into VB without altering its purpose. | <?php
$size = 4;
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ($guesses = 1; ; $guesses++) {
while (true) {
echo "\nNext guess [$guesses]: ";
$guess = rtrim(fgets(STDIN));
if (!checkguess($guess))
echo "$size digits, no repetition, no 0... retry\n";
else
break;
}
if ($guess == $chosen) {
echo "You did it in $guesses attempts!\n";
break;
} else {
$bulls = 0;
$cows = 0;
foreach (range(0, $size-1) as $i) {
if ($guess[$i] == $chosen[$i])
$bulls++;
else if (strpos($chosen, $guess[$i]) !== FALSE)
$cows++;
}
echo "$cows cows, $bulls bulls\n";
}
}
function checkguess($g)
{
global $size;
return count(array_unique(str_split($g))) == $size &&
preg_match("/^[1-9]{{$size}}$/", $g);
}
?>
| Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.