function Generate($level)
 {
     if ($level <= 3) {
         $num1 = pow(2, rand(2, 3));
         $num2 = pow(2, rand(4, 5));
     } elseif ($level <= 6) {
         $num1 = pow(2, rand(1, 3)) * pow(3, rand(0, 1));
         $num2 = pow(2, rand(1, 4)) * pow(3, rand(2, 3));
     } else {
         $num1 = pow(2, rand(1, 3)) * pow(3, rand(0, 3)) * pow(5, rand(0, 1));
         $num2 = pow(2, rand(1, 4)) * pow(3, rand(0, 3)) * pow(5, rand(2, 3));
     }
     $gcd = gcd($num1, $num2);
     $num3 = rand(1, 2) == 1 ? $gcd : $gcd / 2;
     // // Original exercise
     // $num1 = 48;
     // $num2 = 120;
     // $num3 = 12;
     // $gcd = gcd($num1, $num2);
     $correct = $num3 == $gcd ? 0 : 1;
     $options = ['Igaz', 'Hamis'];
     $solution = $options[$correct];
     $question = 'Adja meg az alábbi állítás logikai értékét (igaz vagy hamis)!<br />' . The($num1, TRUE) . ' $' . $num1 . '$ és ' . The($num2) . ' $' . $num2 . '$ legnagyobb közös osztója ' . The($num3) . ' $' . $num3 . '$.';
     $page[] = '<div class="alert alert-info"><strong>Közös osztó:</strong> az a szám, amivel mind a két szám osztható.</div>';
     $page[] = '<div class="alert alert-info"><strong>Legnagyobb közös osztó:</strong> a közös osztók közül a legnagyobb. Az $a$ és $b$ számok legnagyobb közös osztóját $(a;b)$-vel jelöljük.</div>';
     $page[] = 'A legnagyobb közös osztó kiszámításához először írjuk fel mindkét szám prímtényezős felbontását!';
     $hints[] = $page;
     $hints[][] = 'Az első szám prímtényezős felbontása: $' . $num1 . '=' . implode('\\cdot', $this->CanonicForm($num1)) . '$, ugyanis:' . $this->Factorization($num1);
     $hints[][] = 'A második szám prímtényezős felbontása: $' . $num2 . '=' . implode('\\cdot', $this->CanonicForm($num2)) . '$, ugyanis:' . $this->Factorization($num2);
     $page = [];
     $page[] = 'Most gyűjtsünk össze a közös prímtényezőket (ha mindkét számban előfordul, akkor a kisebb kitevőt nézzük): $$(' . $num1 . ';' . $num2 . ')=' . implode('\\cdot', $this->CanonicForm($gcd)) . '=' . $gcd . '$$';
     $page[] = 'Mivel a legnagyobb közös osztó ' . ($gcd == $num3 ? 'megegyezik' : 'nem egyezik meg') . ' ' . The($num3) . ' $' . $num3 . '$-' . With($num3) . ', ezért az állítás <span class="label label-success">' . strtolower($solution) . '</span>.';
     $hints[] = $page;
     return array('question' => $question, 'correct' => $correct, 'solution' => $solution, 'options' => $options, 'hints' => $hints);
 }
Beispiel #2
0
function fract_label($v)
{
    # Add leading sign and make positive:
    if ($v < 0) {
        $result = '-';
        $v *= -1;
    } elseif ($v == 0) {
        $result = '0';
    } else {
        $result = '';
    }
    # Process whole number part.
    # Prepare for space between number and fraction.
    if ($v >= 1) {
        $whole = (int) $v;
        $v -= $whole;
        $result .= $whole;
        $space_between = ' ';
    } else {
        $space_between = '';
    }
    # Process fractional part:
    if ($v > 0) {
        $p64 = (int) round($v * 64);
        $factor = gcd($p64, 64);
        $numerator = $p64 / $factor;
        $denominator = 64 / $factor;
        $result .= $space_between . $numerator . '/' . $denominator;
    }
    return $result;
}
Beispiel #3
0
function gcd($a, $b)
{
    if ($b == 0) {
        return $a;
    }
    return gcd($b, $a % $b);
}
Beispiel #4
0
function gcd($a, $b)
{
    if (!b) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}
Beispiel #5
0
function gcd($a, $b)
{
    if ($a == 0) {
        return $b;
    } else {
        return gcd($b, $a % $b);
    }
}
Beispiel #6
0
function lcd($a, $b)
{
    if ($a < $b) {
        $c = $a;
        $a = $b;
        $b = $c;
    }
    return $a * $b / gcd($a, $b);
}
Beispiel #7
0
function lcd($a, $b)
{
    if ($a < $b) {
        $c = $a;
        $a = $b;
        $b = $c;
    }
    //return ($a * $b) / gmp_intval(gmp_gcd($a, $b));
    return $a * $b / gcd($a, $b);
}
Beispiel #8
0
function ritmo($durações)
{
    $tempos = 0;
    $unidade = max($durações);
    foreach ($durações as $duração) {
        $tempos += $unidade / $duração;
    }
    $gcd = gcd($tempos, $unidade);
    $tempos /= $gcd;
    $unidade /= $gcd;
    return "{$tempos}/{$unidade}";
}
    function Generate($level)
    {
        $m = pow(-1, rand(1, 2)) * rand(1, 2);
        $b = rand(-5, 5);
        $A[0] = pow(-1, rand(1, 2)) * rand(1, 10);
        // Ax != 0
        $A[1] = $A[0] * $m + $b;
        $B[0] = -$A[0];
        $B[1] = $B[0] * $m + $b;
        // // Original exercise
        // $A = [-3,-1];
        // $B = [3,7];
        // $m = ($A[1]-$B[1])/($A[0]-$B[0]);
        // $b = $A[1] - $A[0]*$m;
        // print_r('m='.$m.', b='.$b.'<br />');
        // print_r('A('.$A[0].';'.$A[1].'), B('.$B[0].';'.$B[1].')	<br />');
        $mfrac['nom'] = ($B[1] - $A[1]) / gcd($B[1] - $A[1], $B[0] - $A[0]);
        $mfrac['denum'] = ($B[0] - $A[0]) / gcd($B[1] - $A[1], $B[0] - $A[0]);
        $question = 'Írja fel a hozzárendelési utasítását annak a lineáris függvénynek, mely $' . ($A[0] < 0 ? '(' . $A[0] . ')' : $A[0]) . '$-' . To($A[0]) . ' $' . ($A[1] < 0 ? '(' . $A[1] . ')' : $A[1]) . '$-' . Dativ($A[1]) . ' és $' . ($B[0] < 0 ? '(' . $B[0] . ')' : $B[0]) . '$-' . To($B[0]) . ' $' . ($B[1] < 0 ? '(' . $B[1] . ')' : $B[1]) . '$-' . Dativ($B[1]) . ' rendel! (A hozzárendelési utasítást $x\\mapsto mx+b$ alakban adja meg!)';
        $page[] = 'A hozzárendelés egy $y=mx+b$ alakú lineáris függvény lesz.';
        $page[] = 'A függvény $' . ($A[0] < 0 ? '(' . $A[0] . ')' : $A[0]) . '$-' . To($A[0]) . ' $' . ($A[1] < 0 ? '(' . $A[1] . ')' : $A[1]) . '$-' . Dativ($A[1]) . ' rendel, azaz:$$' . $A[1] . '=' . $A[0] . '\\cdot m+b$$';
        $page[] = 'Továbbá azt is tudjuk, hogy $' . ($B[0] < 0 ? '(' . $B[0] . ')' : $B[0]) . '$-' . To($B[0]) . ' $' . ($B[1] < 0 ? '(' . $B[1] . ')' : $B[1]) . '$-' . Dativ($B[1]) . ' rendel, azaz:$$' . $B[1] . '=' . $B[0] . '\\cdot m+b$$';
        $hints[] = $page;
        $page = [];
        $page[] = '$$\\begin{eqnarray}
			I.\\quad& ' . $A[1] . '&=&' . $A[0] . '\\cdot m+b\\\\
			II.\\quad& ' . $B[1] . '&=&' . $B[0] . '\\cdot m+b
		\\end{eqnarray}$$
			Vonjuk ki az első egyenletből a másodikat! Ekkor a $b$-s tagok kiesnek:$$\\begin{eqnarray}
			' . $A[1] . (-$B[1] < 0 ? '' : '+') . strval(-$B[1]) . '&=&(' . $A[0] . (-$B[0] < 0 ? '' : '+') . strval(-$B[0]) . ')\\cdot m+b-b\\\\
			' . strval($A[1] - $B[1]) . '&=&' . strval($A[0] - $B[0]) . '\\cdot m\\\\
			\\frac{' . strval($A[1] - $B[1]) . '}{' . strval($A[0] - $B[0]) . '}&=&m\\\\
		\\end{eqnarray}$$';
        $page[] = 'Tehát az $m$ értéke <span class="label label-success">$' . (round($m) == $m ? $m : '\\frac{' . $mfrac['nom'] . '}{' . $mfrac['denum'] . '}') . '$</span>.';
        $hints[] = $page;
        $page = [];
        $page[] = '$$\\begin{eqnarray}
			I.\\quad& ' . $A[1] . '&=&' . $A[0] . '\\cdot m+b\\\\
			II.\\quad& ' . $B[1] . '&=&' . $B[0] . '\\cdot m+b
		\\end{eqnarray}$$
		Most adjuk össze a két egyenletet! Ekkor az $m$-es tagok esnek ki:$$\\begin{eqnarray}
			' . $A[1] . ($B[1] < 0 ? '' : '+') . $B[1] . '&=&(' . $A[0] . ($B[0] < 0 ? '' : '+') . $B[0] . ')\\cdot m+b+b\\\\
			' . strval($A[1] + $B[1]) . '&=&2\\cdot b\\\\
			\\frac{' . strval($A[1] + $B[1]) . '}{2}&=&b\\\\
		\\end{eqnarray}$$';
        $page[] = 'Tehát a $b$ értéke <span class="label label-success">$' . $b . '$</span>.';
        $hints[] = $page;
        $correct = [round1($m), $b];
        $solution = '$m=' . round2($m) . '\\quad b=' . $b . '$';
        return array('question' => $question, 'correct' => $correct, 'type' => 'array', 'solution' => $solution, 'hints' => $hints, 'labels' => ['$m$', '$b$']);
    }
Beispiel #10
0
function gcd($m, $n)
{
    if ($m < $n) {
        return -1;
    }
    if ($n == 0) {
        return $m;
    }
    $m = $m % $n;
    if ($m == 0) {
        return $n;
    }
    return gcd($n, $m);
}
Beispiel #11
0
function gcd($x, $y)
{
    if ($x >= $y) {
        $a = $x;
        $b = $y;
    } else {
        $a = $y;
        $b = $x;
    }
    if ($b <= 0) {
        if ($b >= 0) {
            return $a + 0;
        }
    }
    return gcd($b + 0, $a - $b);
}
Beispiel #12
0
/**
 * Weighted round-robin
 *
 * Adapted from LVS Weighted round-robin implementation
 * (@see http://kb.linuxvirtualserver.org/wiki/Weighted_Round-Robin_Scheduling)
 *
 * @param  array    $S  weights
 * @param  integer &$i  current position
 * @param  integer &$cw current weight
 * @return integer
 */
function wrr($S, &$i = -1, &$cw = 0)
{
    if (!($n = count($S))) {
        return null;
    }
    while (true) {
        $i = ($i + 1) % $n;
        if ($i == 0) {
            $cw = $cw - gcd($S);
            if ($cw <= 0) {
                $cw = max($S);
                if ($cw == 0) {
                    return null;
                }
            }
        }
        if ($S[$i] >= $cw) {
            return $i;
        }
    }
}
Beispiel #13
0
function cryptorsakeys($p, $q)
{
    $n = $p * $q;
    $phi = ($p - 1) * ($q - 1);
    $e = 3;
    while (gcd($e, $phi) != 1 && $e < $phi) {
        $e++;
    }
    if ($e >= $phi) {
        echo 'e bigger than phi - fail';
        return;
    }
    list($d, $j, $k) = extended_gcd($e, $phi);
    if ($d < 0) {
        $d += $phi;
    }
    return array($n, $e, $d);
}
Beispiel #14
0
function smd($num, $den)
{
    $g = gcd($num, $den);
    return $den / $g;
}
Beispiel #15
0
function fractionreduce()
{
    $args = func_get_args();
    $retarr = false;
    if (count($args) == 1) {
        if (is_array($args[0])) {
            $f = $args[0];
        } else {
            $f = fractionparse($args[0]);
        }
    } else {
        if (count($args) == 2 && is_array($args[0])) {
            $f = $args[0];
            $retarr = $args[1];
        } else {
            if (count($args) == 2) {
                $f = array($args[0], $args[1]);
            } else {
                if (count($args) == 3) {
                    $f = array($args[0], $args[1]);
                    $retarr = $args[2];
                }
            }
        }
    }
    $g = gcd($f[0], $f[1]);
    $f[0] /= $g;
    $f[1] /= $g;
    if ($f[1] < 0) {
        $f[0] *= -1;
        $f[1] *= -1;
    }
    if ($retarr) {
        return $f;
    }
    if ($f[1] == 1) {
        return $f[0];
    } else {
        return $f[0] . '/' . $f[1];
    }
}
function fraction_divide($level)
{
    if ($level <= 3) {
        $num1 = rand(1, 2);
        $num2 = rand(1, 2);
        $denom1 = rand(1, 3);
        $denom2 = rand(1, 3);
    } elseif ($level <= 6) {
        $num1 = rand(3, 5);
        $num2 = rand(3, 5);
        $denom1 = rand(5, 10);
        $denom2 = rand(5, 10);
    } else {
        $num1 = rand(5, 10);
        $num2 = rand(5, 10);
        $denom1 = rand(10, 20);
        $denom2 = rand(10, 20);
    }
    $frac1 = $num1 / $denom1;
    $frac2 = $num2 / $denom2;
    $num = $num1 * $denom2;
    $denom = $denom1 * $num2;
    $gcd = gcd($num, $denom);
    if ($gcd) {
        $num /= $gcd;
        $denom /= $gcd;
    }
    $question = 'Mennyi lesz az alábbi művelet eredménye? $$\\frac{' . $num1 . '}{' . $denom1 . '}:\\frac{' . $num2 . '}{' . $denom2 . '}$$';
    $solution = '$\\frac{' . $num . '}{' . $denom . '}$';
    $correct = array($num, $denom);
    $type = 'fraction';
    return array('question' => $question, 'correct' => $correct, 'solution' => $solution, 'type' => $type);
}
Beispiel #17
0
function simplexpivot($sm, $pivotpoint)
{
    if (!is_array($pivotpoint)) {
        $pivotpoint = explode(',', $pivotpoint);
    }
    $Pivotrow = $pivotpoint[0];
    $Pivotcol = $pivotpoint[1];
    $PivotValue = $sm[$Pivotrow][$Pivotcol];
    // change pivot point to a one
    for ($j = 0; $j < count($sm[$Pivotrow]); $j++) {
        $top = $sm[$Pivotrow][$j][0] * $PivotValue[1];
        $bot = $sm[$Pivotrow][$j][1] * $PivotValue[0];
        if ($bot < 0) {
            $top *= -1;
            $bot *= -1;
            // must be positive
        }
        $gcf = gcd($top, $bot);
        $top /= $gcf;
        $bot /= $gcf;
        $sm[$Pivotrow][$j] = array($top, $bot);
        // divide by $PivotValue
    }
    // now zero out all other values in that row
    for ($r = 0; $r < count($sm); $r++) {
        if ($r != $Pivotrow) {
            $PivotValue = array(-$sm[$r][$Pivotcol][0], $sm[$r][$Pivotcol][1]);
            for ($c = 0; $c < count($sm[$r]); $c++) {
                // multiplication
                $top = $PivotValue[0] * $sm[$Pivotrow][$c][0];
                $bot = $PivotValue[1] * $sm[$Pivotrow][$c][1];
                // addition
                $top = $top * $sm[$r][$c][1] + $sm[$r][$c][0] * $bot;
                $bot = $bot * $sm[$r][$c][1];
                if ($bot < 0) {
                    $top *= -1;
                    $bot *= -1;
                    // must be positive
                }
                $gcf = gcd($top, $bot);
                $top /= $gcf;
                $bot /= $gcf;
                $sm[$r][$c] = array($top, $bot);
            }
        }
    }
    return $sm;
}
Beispiel #18
0
<?php

require "example.php";
# Call our gcd() function
$x = "42 aaa";
$y = 105;
$g = gcd($x, $y);
print "The gcd of {$x} and {$y} is {$g}\n";
# Manipulate the Foo global variable
# Output its current value
print "Foo = " . Foo_get() . "\n";
# Change its value
Foo_set(3.1415926);
# See if the change took effect ( this isn't a good example for php, see
#				  manual for why. )
print "Foo = " . Foo_get() . "\n";
print_Foo();
 public static function order_mod($x, $m)
 {
     if (extension_loaded('gmp') && USE_EXT == 'GMP') {
         if ($m <= 1) {
             return 0;
         }
         if (gcd($x, m) == 1) {
             $z = $x;
             $result = 1;
             while ($z != 1) {
                 $z = gmp_strval(gmp_Utils::gmp_mod2(gmp_mul($z, $x), $m));
                 $result = gmp_add($result, 1);
             }
             return gmp_strval($result);
         }
     } elseif (extension_loaded('bcmath') && USE_EXT == 'BCMATH') {
         if ($m <= 1) {
             return 0;
         }
         if (gcd($x, m) == 1) {
             $z = $x;
             $result = 1;
             while ($z != 1) {
                 $z = bcmod(bcmul($z, $x), $m);
                 $result = bcadd($result, 1);
             }
             return $result;
         }
     } else {
         throw new ErrorException("Please install BCMATH or GMP");
     }
 }
Beispiel #20
0
function lowestTerm($e)
{
    $part = explode('/', $e);
    $gcd = gcd($part[0], $part[1]);
    return $gcd;
}
function simplify($var, $num)
{
    $result = 0;
    $var = str_replace('x', '', $var);
    if (fmod($num, $var) == 0) {
        $result = $num / $var;
    } else {
        $gcd = gcd($num, $var);
        $num /= $gcd;
        $var /= $gcd;
        $result = "{$num}/{$var} or " . round($num / $var, 2);
    }
    return $result;
}
Beispiel #22
0
function solution_ChocolatesByNumbers($N, $M)
{
    return $N / gcd($N, $M);
}
Beispiel #23
0
function lcm($a, $b)
{
    if ($a == 0 || $b == 0) {
        return 0;
    }
    $a = abs($a);
    $b = abs($b);
    return $a * $b / gcd($a, $b);
}
    public function searchByProximity($center, $tolerance=1000, $maxItems=0) {
        // approximate upper/lower bounds for lat/lon before calculating GCD
        $dLatRadians = $tolerance / EARTH_RADIUS_IN_METERS;
        // by haversine formula
        $dLonRadians = 2 * asin(sin($dLatRadians / 2) / cos($center['lat'] * M_PI / 180));

        $dLatDegrees = $dLatRadians * 180 / M_PI;
        $dLonDegrees = $dLonRadians * 180 / M_PI;

        $maxLat = $center['lat'] + $dLatDegrees;
        $minLat = $center['lat'] - $dLatDegrees;
        $maxLon = $center['lon'] + $dLonDegrees;
        $minLon = $center['lon'] - $dLonDegrees;

        $this->searchResults = array();
        $resultsByDistance = array();

        // please think twice before refactoring this.
        foreach ($this->feeds as $categoryID => $feedData) {
            $controller = MapDataController::factory($feedData['CONTROLLER_CLASS'], $feedData);
            $controller->setDebugMode($GLOBALS['siteConfig']->getVar('DATA_DEBUG'));

            if ($controller->canSearch()) { // respect config settings
                foreach ($controller->items() as $itemID => $item) {
                    if ($item instanceof MapFeature) {
                        $geometry = $item->getGeometry();
                        if ($geometry) {
                            $featureCenter = $geometry->getCenterCoordinate();
                            if ($featureCenter['lat'] <= $maxLat && $featureCenter['lat'] >= $minLat
                                && $featureCenter['lon'] <= $maxLon && $featureCenter['lon'] >= $minLon)
                            {
                                $distance = gcd($center['lat'], $center['lon'], $featureCenter['lat'], $featureCenter['lon']);
                                if ($distance > $tolerance) continue;

                                // keep keys unique; give priority to whatever came first
                                $intDist = intval($distance * 1000);
                                while (array_key_exists($intDist, $resultsByDistance)) {
                                    $intDist += 1; // one centimeter
                                }
                                $subtitle = sprintf("%s (%.0f meters away)", $item->getSubtitle(), $distance);
                                $resultsByDistance[$intDist] = array(
                                    'title'    => $item->getTitle(),
                                    'subtitle' => $subtitle,
                                    'category' => $categoryID,
                                    'index'    => $itemID,
                                    );
                            }
                        }

                    } else {
                        foreach ($item->getItems() as $featureID => $feature) {
                            $geometry = $feature->getGeometry();
                            if ($geometry) {
                                $featureCenter = $geometry->getCenterCoordinate();
                                if ($featureCenter['lat'] <= $maxLat && $featureCenter['lat'] >= $minLat
                                    && $featureCenter['lon'] <= $maxLon && $featureCenter['lon'] >= $minLon)
                                {
                                    $distance = gcd($center['lat'], $center['lon'], $featureCenter['lat'], $featureCenter['lon']);
                                    if ($distance > $tolerance) continue;

                                    // keep keys unique; give priority to whatever came first
                                    $intDist = intval($distance * 1000);
                                    while (array_key_exists($intDist, $resultsByDistance)) {
                                        $intDist += 1; // one centimeter
                                    }
                                    $subtitle = sprintf("%s (%.0f meters away)", $item->getSubtitle(), $distance);
                                    $resultsByDistance[$distance] = array(
                                        'title'       => $item->getTitle(),
                                        'subtitle'    => $subtitle,
                                        'category'    => $categoryID,
                                        'subcategory' => $itemID,
                                        'index'       => $featureID,
                                        );
                                }
                            }
                        }
                    } // instanceof MapFeature
                } // foreach items
            } // if canSearch
        } // foreach feeds

        ksort($resultsByDistance);

        if ($maxItems && count($resultsByDistance) > $maxItems) {
            array_splice($resultsByDistance, $maxItems);
        }

        $this->searchResults = array_values($resultsByDistance);
        return $this->searchResults;
    }
Beispiel #25
0
function checkanswerformat($tocheck, $ansformats)
{
    $tocheck = trim($tocheck);
    $tocheck = str_replace(',', '', $tocheck);
    if (strtoupper($tocheck) == 'DNE' || $tocheck == 'oo' || $tocheck == '+oo' || $tocheck == '-oo') {
        return true;
    }
    if (in_array("fraction", $ansformats) || in_array("reducedfraction", $ansformats) || in_array("fracordec", $ansformats)) {
        $tocheck = preg_replace('/\\s/', '', $tocheck);
        if (!preg_match('/^\\(?\\-?\\(?\\d+\\)?\\/\\(?\\d+\\)?$/', $tocheck) && !preg_match('/^\\(?\\d+\\)?\\/\\(?\\-?\\d+\\)?$/', $tocheck) && !preg_match('/^\\s*?\\-?\\d+\\s*$/', $tocheck) && (!in_array("fracordec", $ansformats) || !preg_match('/^\\s*?\\-?\\d*?\\.\\d*?\\s*$/', $tocheck))) {
            return false;
        } else {
            if (in_array("reducedfraction", $ansformats) && strpos($tocheck, '/') !== false) {
                $tocheck = str_replace(array('(', ')'), '', $tocheck);
                $tmpa = explode("/", $tocheck);
                if (gcd(abs($tmpa[0]), abs($tmpa[1])) != 1 || $tmpa[1] == 1) {
                    return false;
                }
            }
        }
    }
    if (in_array("notrig", $ansformats)) {
        if (preg_match('/(sin|cos|tan|cot|csc|sec)/', $tocheck)) {
            return false;
        }
    }
    if (in_array("nolongdec", $ansformats)) {
        if (preg_match('/\\.\\d{6}/', $tocheck)) {
            return false;
        }
    }
    if (in_array("scinot", $ansformats)) {
        $totest = str_replace(' ', '', $tocheck);
        if (!preg_match('/^\\-?[1-9](\\.\\d*)?(\\*|x|X|×)10\\^(\\(?\\-?\\d+\\)?)$/', $totest)) {
            return false;
        }
    }
    if (in_array("mixednumber", $ansformats) || in_array("sloppymixednumber", $ansformats) || in_array("mixednumberorimproper", $ansformats)) {
        if (!preg_match('/^\\s*\\-?\\s*\\d+\\s*(_|\\s)\\s*(\\d+)\\s*\\/\\s*(\\d+)\\s*$/', $tocheck, $mnmatches) && !preg_match('/^\\s*?\\-?\\d+\\s*$/', $tocheck) && !preg_match('/^\\s*\\-?\\d+\\s*\\/\\s*\\-?\\d+\\s*$/', $tocheck)) {
            //if doesn't match any format, exit
            return false;
        } else {
            if (preg_match('/^\\s*\\-?\\d+\\s*\\/\\s*\\-?\\d+\\s*$/', $tocheck)) {
                //if a fraction
                $tmpa = explode("/", $tocheck);
                if (in_array("mixednumber", $ansformats)) {
                    if (gcd(abs($tmpa[0]), abs($tmpa[1])) != 1 || abs($tmpa[0]) >= abs($tmpa[1])) {
                        return false;
                    }
                } else {
                    if (in_array("mixednumberorimproper", $ansformats)) {
                        if (gcd(abs($tmpa[0]), abs($tmpa[1])) != 1) {
                            return false;
                        }
                    }
                }
            } else {
                if (!preg_match('/^\\s*?\\-?\\d+\\s*$/', $tocheck)) {
                    //is in mixed number format
                    if (in_array("mixednumber", $ansformats)) {
                        if ($mnmatches[2] >= $mnmatches[3] || gcd($mnmatches[2], $mnmatches[3]) != 1) {
                            return false;
                        }
                    } else {
                        if (in_array("mixednumberorimproper", $ansformats)) {
                            if (gcd($mnmatches[2], $mnmatches[3]) != 1) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
    }
    if (in_array("nodecimal", $ansformats)) {
        if (strpos($tocheck, '.') !== false) {
            return false;
        }
        if (strpos($tocheck, 'E-') !== false) {
            return false;
        }
        if (preg_match('/10\\^\\(?\\-/', $tocheck)) {
            return false;
        }
    }
    return true;
}
Beispiel #26
0
        // special case for first whole value
        if ($whole > 0) {
            $lines .= <<<_OUT

        {
            "display": "{$whole}",
            "value": {$whole}
        },

_OUT;
        }
        // start at the first fractional value, NOT first whole value
        for ($i = 1; $i < $f; $i++) {
            $value = $whole + $i / $f;
            // calculate the gcd of the fraction, so it can be reduced
            $gcd = gcd($i, $f);
            // reduce the fraction
            if ($gcd > 1) {
                $display = ($whole > 0 ? $whole . ' ' : '') . $i / $gcd . '/' . $f / $gcd;
            } else {
                $display = ($whole > 0 ? $whole . ' ' : '') . $i . '/' . $f;
            }
            $lines .= <<<_OUT
        
            {
                "display": "{$display}",
                "value": {$value}
            },
    
_OUT;
        }
Beispiel #27
0
function create_response($npc_id)
{
    $response = '<br />Для данного монстра добавлены выпадающие предметы:
	<table border=1 cellspacing=2 cellpadding=2>';
    //Форма добавлени лута
    $response .= '<tr><td>
	<div id="content" onclick="hideSuggestions();">
	<table bgcolor="#003E00" border=0 cellspacing=2 cellpadding=2>
	<tr><td>Вариант выпадения: </td><td>
	<select id="variant">
		<option value="0" selected>Выпадает постоянно</option>
		<option value="1">Выпадает один раз</option>
	</select>
	</td></tr>
	<tr><td>Тип дроповой вещи: </td><td>
	<select id="drop_type" onChange="switch_type(this)">
		<option value="1" selected>Предмет</option>
		<option value="2">Ресурс</option>
	</select>
	<input id="keyword" type="text" size="50" onkeyup="handleKeyUp(event)" value=""><div style="display:none;" id="scroll"><div id="suggest"></div></div>
	</td></tr>
	<tr><td>
	Шанс выпадения:</td><td>
	<input id="chance" size="10" type="text" value="0"> из <input type="text" id="chance_max" size="10" value="100">
	</td></tr>
	<tr><td> Куда выпадает предмет: </td><td>
	<select id="kuda">
		<option value="0" selected>Падает на землю</option>
		<option value="1">Перемещается в инвентарь</option>
	</select>
	</td></tr>
	<tr><td>Количество одновременно "падающих" предметов</td><td>От <input type="text" maxsize="5" size="5" id="mincount" value="1"> до <input type="text" maxsize="5" size="5" id="maxcount" value="1"></td></tr>
	<tr><td colspan="2"><!--Если из монстра выпадает более 1 предмета, то для каждого предмета можно задать шанс выпадания среди всего списка выпадающих предметов<br><input type="text" maxsize="3" size="5" id="random_all" value="0"> - % выпадания этого элемента среди всего списка--></td></tr>
	</table>
	</div></td>
	<td><input style="width:100%" type="button" value="Добавить" onclick="save_res(\'new\')"></td></tr>';
    $sel = myquery("SELECT * FROM game_npc_drop WHERE npc_id=" . $npc_id . "");
    $i = 0;
    $lcm = array();
    $all = 0;
    while ($drop = mysql_fetch_array($sel)) {
        $i++;
        $response .= '<tr><td>
		<table border=0 cellspacing=2 cellpadding=2';
        if ($i % 2 == 0) {
            $response .= ' bgcolor="#00004F"';
        } else {
            $response .= ' bgcolor="#420000"';
        }
        $response .= '>
		<tr><td>Вариант выпадения: </td><td>
		<select id="variant' . $drop['id'] . '">
			<option value="0" ';
        if ($drop['variant'] == 0) {
            $response .= 'selected';
        }
        $response .= '>Выпадает постоянно</option>
			<option value="1" ';
        if ($drop['variant'] == 1) {
            $response .= 'selected';
        }
        $response .= '>Выпадает один раз</option>
		</select>
		</td></tr>
		<tr><td>Тип дроповой вещи: </td><td>
		<select id="drop_type' . $drop['id'] . '" onChange="switch_type(this)">
			<option value="1" ';
        if ($drop['drop_type'] == 1) {
            $response .= 'selected';
        }
        $response .= '>Предмет</option>
			<option value="2" ';
        if ($drop['drop_type'] == 2) {
            $response .= 'selected';
        }
        $response .= '>Ресурс</option>
		</select>';
        $name_item = "";
        if ($drop['drop_type'] == 1) {
            $selname = myquery("SELECT name FROM game_items_factsheet WHERE id=" . $drop['items_id'] . "");
            if (mysql_num_rows($selname) > 0) {
                list($name_item) = mysql_fetch_array($selname);
            }
        } elseif ($drop['drop_type'] == 2) {
            $selname = myquery("SELECT name FROM craft_resource WHERE id=" . $drop['items_id'] . "");
            if (mysql_num_rows($selname) > 0) {
                list($name_item) = mysql_fetch_array($selname);
            }
        }
        $response .= '&nbsp;<input id="name_items' . $drop['id'] . '" type="text" size="50" value="' . $name_item . '">';
        $response .= '</td></tr>
		<tr><td>
		Шанс выпадения:</td><td>
		<input id="chance' . $drop['id'] . '" size="10" type="text" value="' . $drop['random'] . '"> из <input type="text" id="chance_max' . $drop['id'] . '" size="10" value="' . $drop['random_max'] . '">
		</td></tr>
		<tr><td> Куда выпадает предмет: </td><td>
		<select id="kuda' . $drop['id'] . '">
			<option value="0" ';
        if ($drop['kuda'] == 0) {
            $response .= 'selected';
        }
        $response .= '>Падает на землю</option>
			<option value="1" ';
        if ($drop['kuda'] == 1) {
            $response .= 'selected';
        }
        $response .= '>Перемещается в инвентарь</option>
		</select>
		</td></tr>
		<tr><td>Количество одновременно "падающих" предметов</td><td>От <input type="text" maxsize="5" size="5" id="mincount' . $drop['id'] . '" value="' . $drop['mincount'] . '"> до <input type="text" maxsize="5" size="5" id="maxcount' . $drop['id'] . '" value="' . $drop['maxcount'] . '"></td></tr>
		<tr><td colspan="2"><!--Если из монстра выпадает более 1 предмета, то для каждого предмета можно задать шанс выпадания среди всего списка выпадающих предметов<br><input type="text" maxsize="3" size="5" id="random_all' . $drop['id'] . '" value="0"> - % выпадания этого элемента среди всего списка--></td></tr>
		</table></td>
		<td><input style="width:100%" type="button" value="Сохранить" onclick="save_res(\'' . $drop['id'] . '\')"><br /><br /><br /><input style="width:100%" type="button" value="Удалить" onclick="delete_res(\'' . $drop['id'] . '\')"></td></tr>';
        $lcm[] = $drop['random_max'];
    }
    $lcm = lcm_arr($lcm);
    if ($lcm != 0) {
        mysql_data_seek($sel, 0);
        while ($chance = mysql_fetch_array($sel)) {
            $all += $chance['random'] * $lcm / gcd($lcm, $chance['random_max']);
        }
        if ($all <= $lcm) {
            $response .= "</table><br /><br />Общий шанс лута: <font color=green><b><u>" . $all . "/" . $lcm . "</u></b></font> (" . round(100 * $all / $lcm, 2) . "%)";
        } else {
            $response .= "</table><br /><br />Общий шанс лута: <font color=red><b><u>" . $all . "/" . $lcm . "</u></b></font> (" . round(100 * $all / $lcm, 2) . "%)";
        }
    } else {
        $response .= "</table><br /><br />Лута нет.";
    }
    return $response;
}
Beispiel #28
0
 function scissors_media_meta($string, $post)
 {
     // From v2.9 the media box is different, there is one table cell more
     global $wp_version;
     if (version_compare($wp_version, '2.9', '>=')) {
         $scissors_extra_cell = "</tr><tr>";
         $scissors_hide_editbutton = "<style type='text/css'>input#imgedit-open-btn-" . $post->ID . "{display:none;}</style>";
     } else {
         $scissors_extra_cell = "";
         $scissors_hide_editbutton = "";
     }
     $errstr = "";
     if (!scissors_supports_imagetype($post->post_mime_type)) {
         $errstr = sprintf(__('Failed to load image. Image type %s not supported.', 'scissors'), $post->post_mime_type);
     }
     $postId = $post->ID;
     $filename = get_attached_file($postId);
     if (!$filename || !file_exists($filename)) {
         $errstr = __('Failed to load image. File not found.', 'scissors');
     } else {
         list($width, $height) = getimagesize($filename);
         if ($width <= 0 || $height <= 0) {
             $errstr = __('Failed to load image. Invalid image dimensions.', 'scissors');
         }
     }
     if ($errstr != "") {
         $string .= "</td></tr>\n\t\t<tr>";
         $string .= "<th valign='top' scope='row' class='label'><label>Scissors</label></th><td class='field'>";
         $string .= "<p class='help'>{$errstr}</p>";
     } else {
         $text_crop = __('Crop', 'scissors');
         $text_resize = __('Resize', 'scissors');
         $text_rotate = __('Rotate', 'scissors');
         $text_watermarks = __('Watermarks', 'scissors');
         $text_apply = __('Apply', 'scissors');
         $text_abort = __('Abort', 'scissors');
         $text_crop2 = __('Crop %s.', 'scissors');
         $text_crop3 = __('Lock aspect ratio to %s.', 'scissors');
         $text_width = __('width', 'scissors');
         $text_height = __('height', 'scissors');
         $text_longside = __('long side', 'scissors');
         $text_shortside = __('short side', 'scissors');
         $text_reir = __('Use automatic relevance-enhanced image reduction.', 'scissors');
         $image_url = wp_get_attachment_url($post->ID);
         $nonce = wp_create_nonce("scissors-{$postId}");
         $img_size = $width . '&nbsp;&times;&nbsp;' . $height;
         $string .= "\n\n" . $scissors_hide_editbutton . "\n\n";
         $string .= "<span id='scissorsSize-{$postId}'>({$img_size} - " . __('just edited', 'scissors') . ")</span></td></tr>\n\t\t<tr>" . $scissors_extra_cell;
         $string .= "<th valign='top' scope='row' class='label'><label>Scissors</label></th><td class='field'>";
         $string .= "<div id='scissorsShowBtn-{$postId}'>";
         $string .= "<button class='button' onclick=\"return scissorsShowCrop({$postId}, '{$image_url}')\">{$text_crop}</button>&nbsp;";
         $string .= "<button class='button' onclick=\"return scissorsShowResize({$postId})\">{$text_resize}</button>&nbsp;";
         if (function_exists('imagerotate')) {
             $string .= "<button class='button' onclick=\"return scissorsShowRotate({$postId})\">{$text_rotate}</button>&nbsp;";
         }
         $string .= "<button class='button' onclick=\"return scissorsShowWatermarks({$postId})\">{$text_watermarks}</button>";
         $string .= "</div>";
         $cropTargets = "<select id='scissorsCropTarget-{$postId}' onchange=\"scissorsCropTargetChange({$postId})\">";
         $cropTargets .= "<option value='chain' selected='selected'>" . __('full chain', 'scissors') . "</option>";
         $cropTargets .= "<option value='full'>" . __('full', 'scissors') . "</option>";
         $metadata = wp_get_attachment_metadata($postId);
         if (is_array($metadata) && isset($metadata['sizes']) && count($metadata['sizes']) > 0) {
             foreach ($metadata['sizes'] as $size => $value) {
                 $cropTargets .= "<option value='{$size}'>" . __($size, 'scissors') . "</option>";
             }
         }
         $cropTargets .= "</select>";
         $aspectMode = get_option('scissors_crop_defaultaspect');
         $aspectChecked = $aspectMode != 2 ? "checked='checked'" : "";
         if ($aspectMode == 1) {
             $aspectX = intval(get_option('scissors_crop_useraspectx'));
             $aspectY = intval(get_option('scissors_crop_useraspecty'));
         }
         if ($aspectMode != 1 || $aspectX <= 0 || $aspectY <= 0) {
             $aspectX = $width;
             $aspectY = $height;
             while (($g = gcd($aspectX, $aspectY)) > 1) {
                 $aspectX = intval($aspectX / $g);
                 $aspectY = intval($aspectY / $g);
             }
         }
         $cropAspect = "<input style='width:2em;text-align:center;' type='text' onchange=\"scissorsManualAspectChange({$postId})\" id='scissorsLockX-{$postId}' value='{$aspectX}' />:";
         $cropAspect .= "<input style='width:2em;text-align:center;' type='text' onchange=\"scissorsManualAspectChange({$postId})\" id='scissorsLockY-{$postId}' value='{$aspectY}' />";
         $reirChecked = get_option('scissors_crop_defaultreir') ? "checked='checked'" : "";
         $string .= "<div class='scissorsPane' id='scissorsCropPane-{$postId}'>";
         $string .= sprintf($text_crop2, $cropTargets);
         $string .= "&nbsp;<button class='button' onclick=\"return scissorsCrop({$postId}, '{$nonce}')\">{$text_crop}</button>";
         $string .= "&nbsp;<button class='button' onclick=\"return scissorsAbortCrop({$postId})\">{$text_abort}</button>";
         $string .= "<div class='scissorsImgHost' id='scissorsImgHost-{$postId}'><img id='scissorsImg-{$postId}' /></div>";
         $string .= "<input type='hidden' id='scissorsX-{$postId}' /><input type='hidden' id='scissorsY-{$postId}' />";
         $string .= "<input type='hidden' id='scissorsW-{$postId}' /><input type='hidden' id='scissorsH-{$postId}' />";
         $string .= "<span id='scissorsSel-{$postId}'></span>";
         $string .= "<div id='scissorsAspect-{$postId}'><input type='checkbox' onchange=\"scissorsAspectChange({$postId})\" id='scissorsLockBox-{$postId}' {$aspectChecked} />&nbsp;";
         $string .= sprintf($text_crop3, $cropAspect);
         $string .= " <button style='margin-left:1em;' class='button' onclick=\"scissorsStdImgAspectRatio({$postId}); return false;\">" . __('current', 'scissors') . "</button>";
         $string .= "</div><div id='scissorsReir-{$postId}'><input type='checkbox' id='scissorsReirEnable-{$postId}' {$reirChecked} />&nbsp;{$text_reir}&nbsp;<a href=\"http://www.useit.com/alertbox/9611.html\" target=\"_blank\">[?]</a></div>";
         $string .= "</div>";
         $fields = "<input style='width:4em;text-align:center;' type='text' id='scissorsWidth-{$postId}' value='{$width}' onkeyup='scissorsResizeChanged({$postId}, 0)' />&nbsp;&times;&nbsp;";
         $fields .= "<input style='width:4em;text-align:center;' type='text' id='scissorsHeight-{$postId}' value='{$height}' onkeyup='scissorsResizeChanged({$postId}, 1)' />";
         $string .= "<div class='scissorsPane' id='scissorsResizePane-{$postId}'>";
         $string .= sprintf(__('Resize to %s pixels.', 'scissors'), $fields);
         $string .= "&nbsp;<button class='button' onclick=\"return scissorsResize({$postId}, '{$nonce}')\">{$text_resize}</button>";
         $string .= "&nbsp;<button class='button' onclick=\"return scissorsAbortResize({$postId})\">{$text_abort}</button><br/>";
         $string .= "<input type='checkbox' id='scissorsMaintainAspect-{$postId}' checked='checked' onchange='scissorsResizeChanged({$postId}, 0)' />";
         $string .= "<input type='hidden' id='scissorsCurWidth-{$postId}' value='{$width}' />";
         $string .= "<input type='hidden' id='scissorsCurHeight-{$postId}' value='{$height}' />";
         $string .= "<input type='hidden' id='scissorsUserAspect-{$postId}' value='" . ($aspectMode == 1 ? "1" : "0") . "' />";
         $string .= "<label style='display:inline;font-size:11px' for='scissorsMaintainAspect-{$postId}'>" . __('Maintain aspect ratio.', 'scissors') . "</label>";
         $string .= "</div>";
         $text_rotate2 = __('Rotate by', 'scissors');
         $text_left90 = __('90 degrees left', 'scissors');
         $text_right90 = __('90 degrees right', 'scissors');
         $text_180 = __('180 degrees', 'scissors');
         if (function_exists('imagerotate')) {
             $string .= "<div class='scissorsPane' id='scissorsRotatePane-{$postId}'>";
             $string .= "{$text_rotate2} <select id='scissorsRotateAngle-{$postId}'><option value='90' selected='selected'>{$text_left90}</option><option value='-90'>{$text_right90}</option><option value='180'>{$text_180}</option></select>.";
             $string .= "&nbsp;<button class='button' onclick=\"return scissorsRotate({$postId}, '{$nonce}')\">{$text_rotate}</button>";
             $string .= "&nbsp;<button class='button' onclick=\"return scissorsAbortRotate({$postId})\">{$text_abort}</button>";
             $string .= "</div>";
         }
         $string .= "<div class='scissorsPane' id='scissorsWatermarkPane-{$postId}'>";
         $wstate = scissors_get_watermarking_state($postId);
         $string .= "<input id='scissors_watermarking_state-{$postId}' type='hidden' value='{$wstate}'/>";
         $sizes = is_array($metadata) && isset($metadata['sizes']) && count($metadata['sizes']) > 0 ? array_keys($metadata['sizes']) : array();
         $sizes[] = 'full';
         $sizes[] = 'custom';
         foreach ($sizes as $size) {
             $checked = scissors_is_watermarking_enabled($size, $postId, TRUE) ? "checked" : "";
             $string .= " <input type='checkbox' id='scissors_watermark_target_{$size}-{$postId}' {$checked}";
             $string .= " onchange=\"scissorsWatermarkStateChanged({$postId}, '{$size}')\"";
             $string .= "><label style='display:inline;font-size:11px' for='scissors_watermark_target_{$size}-{$postId}'>" . __($size, 'scissors') . "</label>";
         }
         $string .= " <button class='button' onclick=\"return scissorsWatermark({$postId}, '{$nonce}')\">{$text_apply}</button>";
         $string .= "&nbsp;<button class='button' onclick=\"return scissorsAbortWatermark({$postId})\">{$text_abort}</button>";
         $string .= "</div>";
         $string .= "<div class='scissorsPane scissorsWaitFld' id='scissorsWaitFld-{$postId}'></div>";
     }
     return $string;
 }
Beispiel #29
0
 public function drop_loot($user_id)
 {
     if ($this->error == 1) {
         return;
     }
     if ($this->npc['dropable'] == 1) {
         $seldrop = myquery("SELECT * FROM game_npc_drop WHERE npc_id=" . $this->templ['npc_id'] . ";");
         if ($seldrop != false and mysql_num_rows($seldrop)) {
             $sum_chance = 0;
             $massiv = array(0);
             $m_last = 1;
             $mes = "";
             $lcm = array();
             $str = "";
             $r = 0;
             $no_loot = 0;
             //Обработаем профессию "Охотник"
             if ($this->templ['npc_id'] == npc_id_olen) {
                 if (checkCraftTrain($user_id, 8)) {
                     $r = $r + 2 * getCraftLevel($user_id, 8);
                 } else {
                     $no_loot = 1;
                 }
             }
             while ($chance = mysql_fetch_array($seldrop)) {
                 $lcm[] = $chance['random_max'];
             }
             mysql_data_seek($seldrop, 0);
             $lcm = lcm_arr($lcm);
             while ($chance = mysql_fetch_array($seldrop)) {
                 $this_chance = ($chance['random'] + $r) * $lcm / gcd($lcm, $chance['random_max']);
                 $massiv = array_merge($massiv, array_fill($m_last, $this_chance, $chance));
                 $m_last += $this_chance;
             }
             if ($m_last < $lcm + 1) {
                 $massiv = array_merge($massiv, array_fill($m_last, $lcm + 1 - $m_last, array('items_id' => 0)));
             }
             $drop = $massiv[mt_rand(1, $lcm)];
             if ($drop['items_id'] != 0 and $no_loot == 0) {
                 $it_user_id = 0;
                 $priznak = 2;
                 $kol_predmetov = mt_rand($drop['mincount'], $drop['maxcount']);
                 $map_name = 0;
                 $map_xpos = 0;
                 $map_ypos = 0;
                 for ($cikl = 1; $cikl <= $kol_predmetov; $cikl++) {
                     $add_result = array(0);
                     if ($drop['kuda'] == 1) {
                         $it_user_id = $user_id;
                         $priznak = 0;
                         //проверим вес
                         if ($drop['drop_type'] == 1) {
                             $item = mysql_fetch_array(myquery("SELECT * FROM game_items_factsheet WHERE id=" . $drop['items_id'] . ""));
                         } elseif ($drop['drop_type'] == 2) {
                             $item = mysql_fetch_array(myquery("SELECT * FROM craft_resource WHERE id=" . $drop['items_id'] . ""));
                         }
                         list($CW, $CC) = mysql_fetch_array(myquery("SELECT CW,CC FROM view_active_users WHERE user_id={$it_user_id}"));
                         $prov = mysqlresult(myquery("SELECT COUNT(*) FROM game_wm WHERE user_id={$it_user_id} AND type=1"), 0, 0);
                         if ($CC - $CW < $item['weight'] and $prov == 0) {
                             //инвентарь заполнен. На землю его!
                             $it_user_id = 0;
                             $priznak = 2;
                             list($map_name, $map_xpos, $map_ypos) = mysql_fetch_array(myquery("SELECT map_name,map_xpos,map_ypos FROM game_users_map WHERE user_id={$it_user_id}"));
                             $drop['kuda'] = 0;
                         }
                     }
                     //если предмет
                     if ($drop['drop_type'] == 1) {
                         if ($priznak == 0) {
                             $Item = new Item();
                             $add_result = $Item->add_user($drop['items_id'], $it_user_id, 0, 0, 1);
                             // не получилось добавить один - не выйдет и остальные.
                             if ($add_result[0] == 0) {
                                 break;
                             }
                         } else {
                             if (!isset($item)) {
                                 $item = mysql_fetch_array(myquery("SELECT * FROM game_items_factsheet WHERE id=" . $drop['items_id'] . ""));
                             }
                             myquery("INSERT INTO game_items (user_id,item_id,priznak,ref_id,item_uselife,item_uselife_max,item_cost,map_name,map_xpos,map_ypos) VALUES ('{$it_user_id}','" . $drop['items_id'] . "','{$priznak}',0,'" . $item['item_uselife'] . "','" . $item['item_uselife_max'] . "','" . $item['item_cost'] . "','{$map_name}','{$map_xpos}','{$map_ypos}')");
                         }
                     } elseif ($drop['drop_type'] == 2) {
                         if ($drop['kuda'] == 1) {
                             $Res = new Res($item, 0);
                             $Res->add_user(0, $it_user_id, 1);
                             if ($this->templ['npc_id'] == npc_id_olen) {
                                 myquery("INSERT INTO craft_stat (build_id, gp, res_id, dob, vip, dat, user, type) values (0, 0, " . $drop['items_id'] . ", 0, 1, " . time() . ", {$it_user_id}, 'z')");
                                 setCraftTimes($it_user_id, 8, 1, 1);
                                 add_exp_for_craft($it_user_id, 8);
                             }
                         } elseif ($drop['kuda'] == 0) {
                             $Res = new Res(0, $drop['items_id']);
                             $Res->add_map(0, 0, 1, 0, $map_name, $map_xpos, $map_ypos);
                             myquery("INSERT INTO craft_resource_market (user_id,town,col,price,res_id,opis,map_name,map_xpos,map_ypos) VALUES (0,0,1,0," . $drop['items_id'] . ",'','" . $map_name . "','" . $map_xpos . "','" . $map_ypos . "')");
                         }
                     }
                     if ($it_user_id > 0) {
                         if ($drop['drop_type'] == 1) {
                             $mes = '<font color=\\"#eeeeee\\">После убийства монстра ты ' . echo_sex('увидел', 'увидела') . ' оставшийся от него предмет: <b>' . $item['name'] . '</b>.Ты быстро ' . echo_sex('подобрал', 'подобрала') . ' выпавший предмет и ' . echo_sex('положил', 'положила') . ' его в свой инвентарь!</font>';
                         } elseif ($drop['drop_type'] == 2) {
                             $mes = '<font color=\\"#eeeeee\\">После убийства монстра ты ' . echo_sex('заметил', 'заметила') . ', как он выронил из рук: <b>' . $item['name'] . '<b/>. Не мешкая ты быстро ' . echo_sex('подобрал', 'подобрала') . ' выпавший ресурс и ' . echo_sex('положил', 'положила') . ' его в свой инвентарь!</font>';
                         }
                         $result = myquery("INSERT game_battles SET attacker_id=" . $user_id . ", target_id=0, map_name=" . $map_name . ", map_xpos=" . $map_xpos . ", map_ypos=" . $map_ypos . ", contents='" . $mes . "', post_time=" . time() . "");
                     }
                 }
             }
         }
     }
 }
    public function searchByProximity($center, $tolerance, $maxItems) {
        // approximate upper/lower bounds for lat/lon before calculating GCD
        $dLatRadians = $tolerance / EARTH_RADIUS_IN_METERS;
        // by haversine formula
        $dLonRadians = 2 * asin(sin($dLatRadians / 2) / cos($center['lat'] * M_PI / 180));

        $dLatDegrees = $dLatRadians * 180 / M_PI;
        $dLonDegrees = $dLonRadians * 180 / M_PI;

        $maxLat = $center['lat'] + $dLatDegrees;
        $minLat = $center['lat'] - $dLatDegrees;
        $maxLon = $center['lon'] + $dLonDegrees;
        $minLon = $center['lon'] - $dLonDegrees;

        $results = array();
        foreach ($this->getAllLeafNodes() as $item) {
            $geometry = $item->getGeometry();
            if ($geometry) {
                $featureCenter = $geometry->getCenterCoordinate();
                if ($featureCenter['lat'] <= $maxLat && $featureCenter['lat'] >= $minLat
                    && $featureCenter['lon'] <= $maxLon && $featureCenter['lon'] >= $minLon
                ) {
                    $distance = gcd($center['lat'], $center['lon'], $featureCenter['lat'], $featureCenter['lon']);
                    if ($distance > $tolerance) continue;

                    // keep keys unique; give priority to whatever came first
                    $intDist = intval($distance * 1000);
                    while (array_key_exists($intDist, $results)) {
                        $intDist += 1; // one centimeter
                    }
                    $item->setField('distance', $distance);
                    $results[$intDist] = $item;
                }
            }
        }
        return $results;
    }