public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz)
 {
     $entity = null;
     $chunk = $level->getChunk($block->getX() >> 4, $block->getZ() >> 4);
     if (!$chunk instanceof FullChunk) {
         return false;
     }
     $nbt = new Compound("", ["Pos" => new Enum("Pos", [new Double("", $block->getX() + 0.5), new Double("", $block->getY()), new Double("", $block->getZ() + 0.5)]), "Motion" => new Enum("Motion", [new Double("", 0), new Double("", 0), new Double("", 0)]), "Rotation" => new Enum("Rotation", [new Float("", lcg_value() * 360), new Float("", 0)])]);
     $entity = Entity::createEntity($this->meta, $chunk, $nbt);
     if ($entity instanceof Entity) {
         if ($player->isSurvival()) {
             --$this->count;
         }
         $entity->spawnToAll();
         return true;
     }
     return false;
 }
Example #2
0
 public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz)
 {
     if ($target->getId() == Block::MONSTER_SPAWNER) {
         return true;
     } else {
         $entity = null;
         $chunk = $level->getChunk($block->getX() >> 4, $block->getZ() >> 4);
         if (!$chunk instanceof FullChunk) {
             return false;
         }
         $nbt = new CompoundTag("", ["Pos" => new EnumTag("Pos", [new DoubleTag("", $block->getX() + 0.5), new DoubleTag("", $block->getY()), new DoubleTag("", $block->getZ() + 0.5)]), "Motion" => new EnumTag("Motion", [new DoubleTag("", 0), new DoubleTag("", 0), new DoubleTag("", 0)]), "Rotation" => new EnumTag("Rotation", [new FloatTag("", lcg_value() * 360), new FloatTag("", 0)])]);
         if ($this->hasCustomName()) {
             $nbt->CustomName = new StringTag("CustomName", $this->getCustomName());
         }
         $entity = Entity::createEntity($this->meta, $chunk, $nbt);
         if ($entity instanceof Entity) {
             if ($player->isSurvival()) {
                 --$this->count;
             }
             $entity->spawnToAll();
             return true;
         }
     }
     return false;
 }
Example #3
0
 /**
  * Constructs the object
  * @param string $query The query
  * @param string $query The query before the redirect (e.g. oprobiu before the automatic redirect to oprobriu)
  * @param int $searchType The seach type
  * @param boolean $redirect If true, then the result is a redirect [OPTIONAL]
  * @param Definition[] $results The results [OPTIONAL]
  * @access public
  * @return void
  **/
 public function __construct($query, $queryBeforeRedirect, $searchType, $redirect = false, &$results = null)
 {
     if (!Config::get('global.logSearch') || lcg_value() > Config::get('global.logSampling')) {
         $this->query = null;
         return false;
     }
     $this->query = $query;
     $this->queryBeforeRedirect = $queryBeforeRedirect;
     $this->searchType = $searchType;
     if (session_variableExists('user')) {
         $this->registeredUser = '******';
         $this->preferences = $_SESSION['user']->preferences;
     } else {
         $this->registeredUser = '******';
         $this->preferences = session_getCookieSetting('anonymousPrefs');
     }
     $this->skin = session_getSkin();
     $this->resultCount = count($results);
     $this->redirect = $redirect ? 'y' : 'n';
     $this->resultList = '';
     if ($results != null) {
         $numResultsToLog = min(count($results), Config::get('global.logResults'));
         $this->resultList = '';
         for ($i = 0; $i < $numResultsToLog; $i++) {
             $this->resultList .= ($this->resultList ? ',' : '') . $results[$i]->id;
         }
     }
 }
function sa($members)
{
    $T = 100.0;
    $now_temp = 10000;
    $n = count($members);
    $status = 0;
    $best = 1000000000;
    while ($T > 0) {
        do {
            $t1 = rand(0, $n - 1);
            $t2 = rand(0, $n - 1);
        } while ($t1 == $t2);
        $now = sqr(abs($members[$t1]['chosen1'] - $t1)) + sqr(abs($members[$t2]['chosen1'] - $t2));
        $new = sqr(abs($members[$t1]['chosen1'] - $t2)) + sqr(abs($members[$t2]['chosen1'] - $t1));
        if ($new < $now || lcg_value() <= exp(($now - $new) / $T)) {
            $temp = $members[$t1];
            $members[$t1] = $members[$t2];
            $members[$t2] = $temp;
            $status += $new - $now;
            if ($status < $best) {
                $res = $members;
            }
        }
        $T -= 0.02;
    }
    return $res;
}
Example #5
0
 public static function generate($length = 10, $charlist = '0-9a-z')
 {
     $charlist = str_shuffle(preg_replace_callback('#.-.#', function ($m) {
         return implode('', range($m[0][0], $m[0][2]));
     }, $charlist));
     $chLen = strlen($charlist);
     if (function_exists('openssl_random_pseudo_bytes') && (PHP_VERSION_ID >= 50400 || !defined('PHP_WINDOWS_VERSION_BUILD'))) {
         $rand3 = openssl_random_pseudo_bytes($length);
     }
     if (empty($rand3) && function_exists('mcrypt_create_iv') && (PHP_VERSION_ID >= 50307 || !defined('PHP_WINDOWS_VERSION_BUILD'))) {
         // PHP bug #52523
         $rand3 = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
     }
     if (empty($rand3) && @is_readable('/dev/urandom')) {
         $rand3 = file_get_contents('/dev/urandom', false, null, -1, $length);
     }
     if (empty($rand3)) {
         static $cache;
         $rand3 = $cache ?: ($cache = md5(serialize($_SERVER), true));
     }
     $s = '';
     $rand = null;
     $rand2 = null;
     for ($i = 0; $i < $length; $i++) {
         if ($i % 5 === 0) {
             list($rand, $rand2) = explode(' ', microtime());
             $rand += lcg_value();
         }
         $rand *= $chLen;
         $s .= $charlist[($rand + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
         $rand -= (int) $rand;
     }
     return $s;
 }
 /**
  * @return BundleInterface|\PHPUnit_Framework_MockObject_MockObject
  */
 private function createBundleMock()
 {
     $bundleMock = $this->getMock('Symfony\\Component\\HttpKernel\\Bundle\\BundleInterface');
     $bundleMock->expects($this->any())->method('getNamespace')->will($this->returnValue('Sonata\\AdminBundle\\Tests\\Fixtures'));
     $bundleMock->expects($this->any())->method('getPath')->will($this->returnValue(sprintf('%s/%s', sys_get_temp_dir(), lcg_value())));
     return $bundleMock;
 }
Example #7
0
function random_float($min, $max)
{
    $val = round($min + lcg_value() * abs($max - $min), 3);
    $bal = round(fmod($val, 0.005), 3);
    $val = $val - $bal;
    echo $val;
}
 /**
  * Генерация ид с жизнью до 35 лет для signed и 70 unsigned
  *
  * @param int $id
  *   Идентификатор, по которому идет парцирование данных, если не указан,
  *   то выбирается случайное число
  * @return int
  */
 protected static function generateId($id = 0)
 {
     // Пытаемся получить метку и сгенерировать ид
     if ($epoch = config('common.epoch')) {
         return (floor(microtime(true) * 1000 - $epoch) << 23) + (mt_rand(0, 4095) << 13) + ($id ? $id : lcg_value() * 10000000) % 1024;
     }
     return 0;
 }
 /**
  * Initializes a new instance of this class.
  *
  * @param float $min The minimum value.
  * @param float $max The maximum value.
  * @param float $decimals The amount of decimals to round to.
  */
 public function __construct($min = 0.0, $max = 1.0, $decimals = 0)
 {
     $value = $min + lcg_value() * abs($max - $min);
     if ($decimals != 0) {
         $value = round($value, $decimals);
     }
     parent::__construct($value);
 }
Example #10
0
 function getRandNumber($min, $max)
 {
     if ($min > $max) {
         $temp = $min;
         $min = $max;
         $max = $temp;
     }
     return $min + lcg_value() * abs($max - $min);
 }
Example #11
0
	/**
	 * Generate random string.
	 * @param  int
	 * @param  string
	 * @return string
	 */
	public static function generate($length = 10, $charlist = '0-9a-z')
	{
		$charlist = count_chars(preg_replace_callback('#.-.#', function ($m) {
			return implode('', range($m[0][0], $m[0][2]));
		}, $charlist), 3);
		$chLen = strlen($charlist);

		if ($length < 1) {
			return ''; // mcrypt_create_iv does not support zero length
		} elseif ($chLen < 2) {
			return str_repeat($charlist, $length); // random_int does not support empty interval
		}

		$res = '';
		if (PHP_VERSION_ID >= 70000) {
			for ($i = 0; $i < $length; $i++) {
				$res .= $charlist[random_int(0, $chLen - 1)];
			}
			return $res;
		}

		$windows = defined('PHP_WINDOWS_VERSION_BUILD');
		$bytes = '';
		if (function_exists('openssl_random_pseudo_bytes')
			&& (PHP_VERSION_ID >= 50400 || !defined('PHP_WINDOWS_VERSION_BUILD')) // slow in PHP 5.3 & Windows
		) {
			$bytes = openssl_random_pseudo_bytes($length, $secure);
			if (!$secure) {
				$bytes = '';
			}
		}
		if (strlen($bytes) < $length && function_exists('mcrypt_create_iv') && (PHP_VERSION_ID >= 50307 || !$windows)) { // PHP bug #52523
			$bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
		}
		if (strlen($bytes) < $length && !$windows && @is_readable('/dev/urandom')) {
			$bytes = file_get_contents('/dev/urandom', FALSE, NULL, -1, $length);
		}
		if (strlen($bytes) < $length) {
			$rand3 = md5(serialize($_SERVER), TRUE);
			$charlist = str_shuffle($charlist);
			for ($i = 0; $i < $length; $i++) {
				if ($i % 5 === 0) {
					list($rand1, $rand2) = explode(' ', microtime());
					$rand1 += lcg_value();
				}
				$rand1 *= $chLen;
				$res .= $charlist[($rand1 + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
				$rand1 -= (int) $rand1;
			}
			return $res;
		}

		for ($i = 0; $i < $length; $i++) {
			$res .= $charlist[($i + ord($bytes[$i])) % $chLen];
		}
		return $res;
	}
Example #12
0
 public static function dropExpOrb__api200(Position $source, $exp = 1, Vector3 $motion = \null, $delay = 40)
 {
     $motion = $motion === \null ? new Vector3(\lcg_value() * 0.2 - 0.1, 0.4, \lcg_value() * 0.2 - 0.1) : $motion;
     $entity = Entity::createEntity("ExperienceOrb", $source->getLevel()->getChunk($source->getX() >> 4, $source->getZ() >> 4, \true), new \pocketmine\nbt\tag\CompoundTag("", ["Pos" => new \pocketmine\nbt\tag\ListTag("Pos", [new \pocketmine\nbt\tag\DoubleTag("", $source->getX()), new \pocketmine\nbt\tag\DoubleTag("", $source->getY()), new \pocketmine\nbt\tag\DoubleTag("", $source->getZ())]), "Motion" => new \pocketmine\nbt\tag\ListTag("Motion", [new \pocketmine\nbt\tag\DoubleTag("", $motion->x), new \pocketmine\nbt\tag\DoubleTag("", $motion->y), new \pocketmine\nbt\tag\DoubleTag("", $motion->z)]), "Rotation" => new \pocketmine\nbt\tag\ListTag("Rotation", [new \pocketmine\nbt\tag\FloatTag("", \lcg_value() * 360), new \pocketmine\nbt\tag\FloatTag("", 0)]), "Health" => new \pocketmine\nbt\tag\ShortTag("Health", 20), "PickupDelay" => new \pocketmine\nbt\tag\ShortTag("PickupDelay", $delay)]));
     if ($entity instanceof ExperienceOrb) {
         $entity->setExp($exp);
     }
     $entity->spawnToAll();
 }
function randomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0)
{
    static $lastRandom = "";
    $output = "";
    $length = abs((int) $length);
    $secureValue = "";
    $rounds = 0;
    $drop = 0;
    while (!isset($output[$length - 1])) {
        //some entropy, but works ^^
        $weakEntropy = array(is_array($startEntropy) ? implode($startEntropy) : $startEntropy, serialize(stat(__FILE__)), __DIR__, PHP_OS, microtime(), (string) lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, (string) PHP_INT_MAX . "." . PHP_INT_SIZE, serialize($_SERVER), serialize(get_defined_constants()), get_current_user(), serialize(ini_get_all()), (string) memory_get_usage() . "." . memory_get_peak_usage(), php_uname(), phpversion(), extension_loaded("gmp") ? gmp_strval(gmp_random(4)) : microtime(), zend_version(), (string) getmypid(), (string) getmyuid(), (string) mt_rand(), (string) getmyinode(), (string) getmygid(), (string) rand(), function_exists("zend_thread_id") ? (string) zend_thread_id() : microtime(), var_export(@get_browser(), true), function_exists("getrusage") ? @implode(getrusage()) : microtime(), function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(), serialize(get_loaded_extensions()), sys_get_temp_dir(), (string) disk_free_space("."), (string) disk_total_space("."), uniqid(microtime(), true), file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime());
        shuffle($weakEntropy);
        $value = hash("sha512", implode($weakEntropy), true);
        $lastRandom .= $value;
        foreach ($weakEntropy as $k => $c) {
            //mixing entropy values with XOR and hash randomness extractor
            $value ^= hash("sha256", $c . microtime() . $k, true) . hash("sha256", mt_rand() . microtime() . $k . $c, true);
            $value ^= hash("sha512", (string) lcg_value() . $c . microtime() . $k, true);
        }
        unset($weakEntropy);
        if ($secure === true) {
            $strongEntropyValues = array(is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("", 64), (function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("", 64), function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("", 64), $value);
            $strongEntropy = array_pop($strongEntropyValues);
            foreach ($strongEntropyValues as $value) {
                $strongEntropy = $strongEntropy ^ $value;
            }
            $value = "";
            //Von Neumann randomness extractor, increases entropy
            $bitcnt = 0;
            for ($j = 0; $j < 64; ++$j) {
                $a = ord($strongEntropy[$j]);
                for ($i = 0; $i < 8; $i += 2) {
                    $b = ($a & 1 << $i) > 0 ? 1 : 0;
                    if ($b != (($a & 1 << $i + 1) > 0 ? 1 : 0)) {
                        $secureValue |= $b << $bitcnt;
                        if ($bitcnt == 7) {
                            $value .= chr($secureValue);
                            $secureValue = 0;
                            $bitcnt = 0;
                        } else {
                            ++$bitcnt;
                        }
                        ++$drop;
                    } else {
                        $drop += 2;
                    }
                }
            }
        }
        $output .= substr($value, 0, min($length - strlen($output), $length));
        unset($value);
        ++$rounds;
    }
    $lastRandom = hash("sha512", $lastRandom, true);
    return $raw === false ? bin2hex($output) : $output;
}
Example #14
0
 public function Neuron($nInputs)
 {
     $this->numInputs = $nInputs;
     for ($i = 0; $i < $nInputs + 1; $i++) {
         // The last item of the array is to store the bias
         // Initialize with random float between -1 and 1
         $this->weights[] = lcg_value() * 2 - 1;
         //$this->weights[] = rand();
     }
 }
Example #15
0
 public function reset()
 {
     // Random initial position
     $this->posx = lcg_value() * $fieldmaxx;
     $this->posy = lcg_value() * $fieldmaxy;
     $this->lookatx = 0;
     $this->lookaty = 0;
     // Random initial rotation
     $this->rotation = lcg_value() * pi();
     $this->fitness = 0;
 }
Example #16
0
 function __construct($installation_data = NULL)
 {
     $this->_core =& Vevui::get();
     if ($installation_data && array_key_exists('missing', $installation_data)) {
         $this->_core->missing_component(get_class($this), $installation_data['missing']);
     }
     $config = $this->e->app;
     $this->_debug = $config->debug;
     $this->_profiling = $config->profiling;
     if (lcg_value() < $this->_profiling) {
     }
 }
Example #17
0
function work()
{
    $time_start = microtime(true);
    $np = 0;
    for ($i = 0; $i <= rand(0, 1000); $i++) {
        $x = lcg_value() * 2 - 1;
        $y = lcg_value() * 2 - 1;
        if ($x ** 2 + $y ** 2 <= 1) {
            $np++;
        }
    }
    return json_encode(array('duration' => microtime(true) - $time_start, 'results' => $np, 'start_time' => $this->time_start));
}
Example #18
0
 function ociexecute($null, $mode = false)
 {
     _mysqlbindbyname($GLOBALS['$stmt'], ':oci_unique', round(lcg_value() * 100000000));
     preg_match('/^[\\s]*([\\w]+)/', $GLOBALS['$stmt']['$sql'], $matchs);
     $GLOBALS['$stmt_mode'] = empty($matchs[1]) ? 'default' : strtolower($matchs[1]);
     $GLOBALS['$stmt']['$sql'] = preg_replace(array('/[\\w_]+_doc_list[\\s\\S]+where l\\.list_id=d\\.list_id\\(\\+\\)/', "/\\(\\+\\)[\\s]+/", '/decode\\(([^,]+),([^,]+),([^,]+),([^,]+)\\)/', '/[\\w\\_]+\\.nextval/', '/to_char\\(([^,\'"]+),([^\\)]+)\\)/es', '/to_date\\(([^,\\)]+),([^\\)]+)\\)([\\s\\d\\+\\-\\/]*)/es', '/nvl\\(([^,]+),([^\\)]+)\\)/', '/^[\\s]*select(.*)\\.currval(.*)dual[\\s]*$/', '/^[\\s]*(insert[^\\(]+)([\\s]+t[\\s]+)\\(/', '/(regexp_substr|regexp_replace)\\(([^,\\)]+),.*\'\\)/U', '/trunc\\(([^,\\)]+)(\\)|,([^\\)]+)\\))/es', '/(sysdate|SYSDATE)([ \\d\\+\\-\\/]*)/es', '/([\\s]*)LOAD([\\s]*)/', '/^[\\s]*alter[\\s]*session.*$/', '/^([\\s]*update[\\s]+.*[\\s]+(set|SET)[\\s]+)/', '/=[\\s]+(null|NULL)[\\s]+/'), array('tuijian_doc_list l left join tuijian_doc_detail d on l.list_id=d.list_id where 1', ' ', ' case when \\1 = \\2 then \\3  else \\4 End ', 'NULL', '_oci_to_char("\\1", "\\2")', '_oci_to_date("\\1", "\\2", "\\3")', 'ifnull(\\1,\\2)', 'SELECT last_insert_id()', '\\1 (', ' \\2 ', '_oci_trunc("\\1", "\\3")', '_oci_sysdate("\\2")', '\\1`LOAD`\\2', 'select 1', '\\1 oci_unique=:oci_unique, ', ' is NULL '), $GLOBALS['$stmt']['$sql']);
     $GLOBALS['lastSql'] = $GLOBALS['$stmt']['$sql'];
     $mysql_error = _mysqlexecute($GLOBALS['$stmt']);
     if ($mysql_error) {
         var_dump($mysql_error, $GLOBALS['lastSql'], 'mysqlmysql');
     }
     return $mysql_error;
 }
 public function proportional($population)
 {
     for ($i = 0; $i < count($population); $i++) {
         //random float
         $randomR1 = lcg_value();
         $selectionIndex = 0;
         while ($selectionIndex < count($population) - 2 && $population[$selectionIndex]['distribution'] <= $randomR1) {
             $selectionIndex++;
         }
         $population[$i]['rand_selection'] = $randomR1;
         $population[$i]['x_after_selection'] = $population[$selectionIndex]['xreal'];
     }
     return $population;
 }
Example #20
0
 /**
  * Generate random string.
  * @param  int
  * @param  string
  * @return string
  */
 public static function generate($length = 10, $charlist = '0-9a-z')
 {
     $charlist = count_chars(preg_replace_callback('#.-.#', function (array $m) {
         return implode('', range($m[0][0], $m[0][2]));
     }, $charlist), 3);
     $chLen = strlen($charlist);
     if ($length < 1) {
         throw new Nette\InvalidArgumentException('Length must be greater than zero.');
     } elseif ($chLen < 2) {
         throw new Nette\InvalidArgumentException('Character list must contain as least two chars.');
     }
     $res = '';
     if (PHP_VERSION_ID >= 70000) {
         for ($i = 0; $i < $length; $i++) {
             $res .= $charlist[random_int(0, $chLen - 1)];
         }
         return $res;
     }
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes')) {
         $bytes = (string) openssl_random_pseudo_bytes($length, $secure);
         if (!$secure) {
             $bytes = '';
         }
     }
     if (strlen($bytes) < $length && function_exists('mcrypt_create_iv')) {
         $bytes = (string) mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
     }
     if (strlen($bytes) < $length && !defined('PHP_WINDOWS_VERSION_BUILD') && is_readable('/dev/urandom')) {
         $bytes = (string) file_get_contents('/dev/urandom', FALSE, NULL, -1, $length);
     }
     if (strlen($bytes) < $length) {
         $rand3 = md5(serialize($_SERVER), TRUE);
         $charlist = str_shuffle($charlist);
         for ($i = 0; $i < $length; $i++) {
             if ($i % 5 === 0) {
                 list($rand1, $rand2) = explode(' ', microtime());
                 $rand1 += lcg_value();
             }
             $rand1 *= $chLen;
             $res .= $charlist[($rand1 + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
             $rand1 -= (int) $rand1;
         }
         return $res;
     }
     for ($i = 0; $i < $length; $i++) {
         $res .= $charlist[($i + ord($bytes[$i])) % $chLen];
     }
     return $res;
 }
 public function uniformSingle($single)
 {
     $binReturn = '';
     $binMutation = array();
     for ($i = 0; $i < strlen($single); $i++) {
         $probability = lcg_value();
         if ($probability <= $this->_probability) {
             $binReturn = $binReturn . ($single[$i] ? 0 : 1);
             $binMutation[] = $i;
         } else {
             $binReturn = $binReturn . $single[$i];
         }
     }
     return array('xbin' => $binReturn, 'mutationBits' => count($binMutation) ? implode(',', $binMutation) : '-');
 }
Example #22
0
 public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz)
 {
     if (!$target instanceof Fence) {
         return false;
     }
     foreach ($level->getChunkEntities($target->x >> 4, $target->z >> 4) as $entity) {
         if ($entity->isLeashed()) {
             if ($entity->leadHolder === $player->getId()) {
                 $nbt = new CompoundTag("", ["Pos" => new ListTag("Pos", [new DoubleTag("", $block->getX() + 0.5), new DoubleTag("", $block->getY()), new DoubleTag("", $block->getZ() + 0.5)]), "Motion" => new ListTag("Motion", [new DoubleTag("", 0), new DoubleTag("", 0), new DoubleTag("", 0)]), "Rotation" => new ListTag("Rotation", [new FloatTag("", lcg_value() * 360), new FloatTag("", 0)])]);
                 $level->addEntity($knot = new LeashKnot($level->getChunkAt($target->x >> 4, $target->z >> 4), $nbt));
                 $entity->setLeashHolder($knot);
             }
         }
     }
 }
 public function getCanCross($population)
 {
     for ($i = 0; $i < count($population); $i++) {
         $parentProbability = lcg_value();
         $population[$i]['parent_probability'] = $parentProbability;
         if ($parentProbability <= $this->_from) {
             $this->_indexsCanCrossElements[] = $i;
         }
         $population[$i]['xbin_after_selection'] = $this->_alg->realToBin($population[$i]['x_after_selection']);
         $population[$i]['cross_point'] = '-';
         $population[$i]['xbin_children'] = '-';
         $population[$i]['x_after_cross'] = $population[$i]['xbin_after_selection'];
     }
     return $population;
 }
Example #24
0
 public function png()
 {
     $img = imagecreate(145, 33);
     $zufall_farbe = imagecolorallocate($img, $this->getRandomColor(), $this->getRandomColor(), $this->getRandomColor());
     imagefill($img, 0, 0, $zufall_farbe);
     $text_farbe = imagecolorallocate($img, 255, 255, 255);
     //weiß
     $alle_zeichen = "abcdfghkmnorstvwxyz123456789";
     //aus diesem    28
     // pool werden dann die zeichen random erzeugt
     $fonts = array('black_jack.ttf', 'arial.ttf', 'Capture_it.ttf', 'SpicyRice.ttf', 'Pacifico.ttf');
     $random_font = $fonts[mt_rand(0, 4)];
     $font = "image/fonts/{$random_font}";
     $laenge = strlen($alle_zeichen);
     $text = "";
     //lines
     $line_color = imagecolorallocate($img, $this->getRandomColor(), $this->getRandomColor(), $this->getRandomColor());
     for ($i = 0; $i < 5; $i++) {
         imageline($img, 0, mt_rand() % 35, 150, mt_rand() % 50, $line_color);
     }
     //ende lines
     //punkte
     $pixel_color = imagecolorallocate($img, $this->getRandomColor(), $this->getRandomColor(), $this->getRandomColor());
     for ($i = 0; $i < 100; $i++) {
         imagesetpixel($img, rand() % 150, rand() % 35, $pixel_color);
     }
     //punkte ende
     for ($i = 1; $i <= 5; $i++) {
         $index = floor(lcg_value() * $laenge);
         $zeichen = substr($alle_zeichen, $index, 1);
         $text .= $zeichen;
         $x = $laenge * $i - 20;
         $y = $laenge - $i * 6;
         imagettftext($img, 20, -$laenge * $i, $x, $y, $text_farbe, $font, $zeichen);
     }
     $this->code = md5($text);
     ob_start();
     // buffers future output
     imagepng($img);
     // writes to output/buffer
     $b64 = base64_encode(ob_get_contents());
     // returns output
     ob_end_clean();
     // clears buffered output
     return "data:image/png;base64," . $b64;
 }
Example #25
0
 public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz)
 {
     $entity = null;
     $chunk = $level->getChunkAt($block->getX() >> 4, $block->getZ() >> 4);
     if (!$chunk instanceof FullChunk) {
         return false;
     }
     $nbt = new Compound("", ["Pos" => new Enum("Pos", [new Double("", $block->getX()), new Double("", $block->getY()), new Double("", $block->getZ())]), "Motion" => new Enum("Motion", [new Double("", 0), new Double("", 0), new Double("", 0)]), "Rotation" => new Enum("Rotation", [new Float("", lcg_value() * 360), new Float("", 0)])]);
     switch ($this->meta) {
         case Villager::NETWORK_ID:
             $nbt->Health = new Short("Health", 20);
             $entity = new Villager($chunk, $nbt);
             break;
         case Zombie::NETWORK_ID:
             $nbt->Health = new Short("Health", 20);
             $entity = new Zombie($chunk, $nbt);
             break;
             /*
             			//TODO: use entity constants
             			case 10:
             			case 11:
             			case 12:
             			case 13:
             				$data = array(
             					"x" => $block->x + 0.5,
             					"y" => $block->y,
             					"z" => $block->z + 0.5,
             				);
             				//$e = Server::getInstance()->api->entity->add($block->level, ENTITY_MOB, $this->meta, $data);
             				//Server::getInstance()->api->entity->spawnToAll($e);
             				if(($player->gamemode & 0x01) === 0){
             					--$this->count;
             				}
             
             				return true;*/
     }
     if ($entity instanceof Entity) {
         if (($player->gamemode & 0x1) === 0) {
             --$this->count;
         }
         $entity->spawnToAll();
         return true;
     }
     return false;
 }
Example #26
0
function createContainer($source, $config = NULL)
{
    $class = 'Container' . md5(lcg_value());
    if ($source instanceof Nette\DI\ContainerBuilder) {
        $code = implode('', $source->generateClasses($class));
    } elseif ($source instanceof Nette\DI\Compiler) {
        if (is_string($config)) {
            $loader = new Nette\DI\Config\Loader();
            $config = $loader->load(is_file($config) ? $config : Tester\FileMock::create($config, 'neon'));
        }
        $code = $source->compile((array) $config, $class, 'Nette\\DI\\Container');
    } else {
        return;
    }
    file_put_contents(TEMP_DIR . '/code.php', "<?php\n\n{$code}");
    require TEMP_DIR . '/code.php';
    return new $class();
}
Example #27
0
 /**
  * Process the RandomFloat expression.
  *
  * * Throws an ExpressionProcessingException if 'min' is greater than 'max'.
  *
  * @return float A Random float value.
  * @throws \qtism\runtime\expressions\ExpressionProcessingException
  */
 public function process()
 {
     $expr = $this->getExpression();
     $min = $expr->getMin();
     $max = $expr->getMax();
     $state = $this->getState();
     $min = is_float($min) ? $min : $state[Utils::sanitizeVariableRef($min)]->getValue();
     $max = is_float($max) ? $max : $state[Utils::sanitizeVariableRef($max)]->getValue();
     if (is_float($min) && is_float($max)) {
         if ($min <= $max) {
             return new Float($min + lcg_value() * abs($max - $min));
         } else {
             $msg = "'min':'{$min}' is greater than 'max':'{$max}'.";
             throw new ExpressionProcessingException($msg, $this, ExpressionProcessingException::LOGIC_ERROR);
         }
     } else {
         $msg = "At least one of the following values is not a float: 'min', 'max'.";
         throw new ExpressionProcessingException($msg, $this, ExpressionProcessingException::WRONG_VARIABLE_BASETYPE);
     }
 }
Example #28
0
	/**
	* Logs a view against the current product with the current visitor credentials
	*
	* @param int $productId
	* @return void
	*/
	public static function logView($productId)
	{
		if (!self::isEnabled() || self::isCurrentSessionFlagged()) {
			// the setting is disabled or the current session has been flagged; this stops data tracking
			return;
		}

		if (lcg_value() <= self::VIEW_SESSION_END_PROBABILITY / self::VIEW_SESSION_END_DIVISOR) {
			// trigger a session cleanup based on the above chances
			self::summariseOldSessions();
		}

		$time = time();
		$sql = "INSERT INTO `[|PREFIX|]product_views` (product, `session`, lastview) VALUES (" . $productId . ", '" . $GLOBALS['ISC_CLASS_DB']->Quote(session_id()) . "', " . $time . ") ON DUPLICATE KEY UPDATE lastview = " . $time;
		$GLOBALS['ISC_CLASS_DB']->Query($sql);

		if (self::countCurrentSessionProductViews() > self::VIEW_CRAWLER_THRESHOLD) {
			self::flagCurrentSession();
			self::discardCurrentSession();
		}
	}
Example #29
0
 /**
  * Generate random string.
  * @param  int
  * @param  string
  * @return string
  */
 public static function generate($length = 10, $charlist = '0-9a-z')
 {
     if ($length === 0) {
         return '';
         // random_bytes and mcrypt_create_iv do not support zero length
     }
     $charlist = str_shuffle(preg_replace_callback('#.-.#', function (array $m) {
         return implode('', range($m[0][0], $m[0][2]));
     }, $charlist));
     $chLen = strlen($charlist);
     if (PHP_VERSION_ID >= 70000) {
         $rand3 = random_bytes($length);
     }
     if (empty($rand3) && function_exists('openssl_random_pseudo_bytes')) {
         $rand3 = openssl_random_pseudo_bytes($length);
     }
     if (empty($rand3) && function_exists('mcrypt_create_iv')) {
         $rand3 = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
     }
     if (empty($rand3) && !defined('PHP_WINDOWS_VERSION_BUILD') && is_readable('/dev/urandom')) {
         $rand3 = file_get_contents('/dev/urandom', FALSE, NULL, -1, $length);
     }
     if (empty($rand3)) {
         static $cache;
         $rand3 = $cache ?: ($cache = md5(serialize($_SERVER), TRUE));
     }
     $s = '';
     for ($i = 0; $i < $length; $i++) {
         if ($i % 5 === 0) {
             list($rand, $rand2) = explode(' ', microtime());
             $rand += lcg_value();
         }
         $rand *= $chLen;
         $s .= $charlist[($rand + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
         $rand -= (int) $rand;
     }
     return $s;
 }
Example #30
-1
 public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz)
 {
     $entity = null;
     $chunk = $level->getChunk($block->getX() >> 4, $block->getZ() >> 4);
     if (!$chunk instanceof FullChunk) {
         return false;
     }
     $nbt = new Compound("", ["Pos" => new Enum("Pos", [new Double("", $block->getX() + 0.5), new Double("", $block->getY()), new Double("", $block->getZ() + 0.5)]), "Motion" => new Enum("Motion", [new Double("", 0), new Double("", 0), new Double("", 0)]), "Rotation" => new Enum("Rotation", [new Float("", lcg_value() * 360), new Float("", 0)])]);
     if ($this->hasCustomName()) {
         $nbt->CustomName = new String("CustomName", $this->getCustomName());
     }
     $entity = Entity::createEntity($this->meta, $chunk, $nbt);
     if ($entity instanceof Entity) {
         $entity->setDataProperty(15, Entity::DATA_TYPE_BYTE, 1);
         $entity->getLevel()->getServer()->broadcastPopup(TextFormat::RED . "Mob AI isn't implemented yet!");
         if ($player->isSurvival()) {
             --$this->count;
         }
         $entity->spawnToAll();
         return true;
     }
     return false;
 }