/**
 * findWord
 *
 * Compute the word that contains the highest number of repeated charaters
 * from the supplied text file
 *
 * @param  string $filePath The search text
 * @return string       The word with the highest number of charaters
 */
function findWord($filePath)
{
    if (!is_readable($filePath)) {
        throw new \RuntimeException(sprintf('The file path \'%s\' is not readable.', $filePath));
    }
    $text = file_get_contents($filePath);
    if (false === $text) {
        throw new \RuntimeException(sprintf('An error occured while trying to read the contents of \'%s\'', $filePath));
    }
    if (empty($text)) {
        throw new \DomainException(sprintf('The text file \'%s\' contains no text!', $filePath));
    }
    $winningWord = null;
    $charCount = 0;
    foreach (str_word_count(strtolower($text), 1) as $word) {
        $counts = count_chars($word, 1);
        if (!empty($counts)) {
            rsort($counts);
            $count = current($counts);
            if ($charCount == 0 || $count > $charCount) {
                $winningWord = $word;
                $charCount = $count;
            }
        }
    }
    return $winningWord;
}
예제 #2
0
파일: Shadowrap.php 프로젝트: sinfocol/gwf3
 /**
  * Reply to the current origin and user, display as a table
  * @todo Write a class that can display ascii art tables and stuff.
  * @author digitalseraphim
  * @since Shadowlamb 3.1
  * @param array $table where each entry is 'row label' => array(values)
  * @return true|false
  */
 public function replyTable(array $table, $langkey = '5044')
 {
     $maxRowLabelWidth = 0;
     $maxWidths = array(-1 => 0);
     foreach ($table as $key => $value) {
         $maxWidths[-1] = max($maxWidths[-1], strlen($key));
         foreach ($value as $k => $v) {
             $charcounts = count_chars($v, 0);
             $vlen = strlen($v) - $charcounts[2];
             if (!array_key_exists($k, $maxWidths)) {
                 $maxWidths[$k] = $vlen;
             } else {
                 $maxWidths[$k] = max($maxWidths[$k], $vlen);
             }
         }
     }
     foreach ($table as $key => $value) {
         $s = sprintf('%-' . ($maxWidths[-1] + 1) . 's', $key);
         foreach ($value as $k => $v) {
             $charcounts = count_chars($v, 0);
             $s .= sprintf('| %-' . ($maxWidths[$k] + 1 + $charcounts[2]) . 's', $v);
         }
         $this->reply(Shadowrun4::lang($langkey, array($s)));
         // 			$this->reply($s);
     }
 }
예제 #3
0
 /**
  * sp_Installer::install() - this method performs the installation of SubjectsPlus
  *
  * @return boolean
  */
 public function install()
 {
     $db = new Querier();
     foreach ($this->lobjCreateQueries as $lstrCQuery) {
         if ($db->exec($lstrCQuery) === FALSE) {
             var_dump($db->errorInfo());
             $this->displayInstallationErrorPage(_("Problem creating new table."));
             return FALSE;
         }
     }
     foreach ($this->lobjInsertQueries as $lstrIQuery) {
         if ($db->exec($lstrIQuery) === FALSE) {
             $this->displayInstallationErrorPage(_("Problem inserting new data into table."));
             $error_info = $db->errorInfo();
             if (count_chars($error_info[2]) > 0) {
                 var_dump($db->errorInfo());
                 echo $lstrIQuery;
             }
             return FALSE;
         }
     }
     if (!$this->updateRewriteBases()) {
         return FALSE;
     }
     return TRUE;
 }
예제 #4
0
 public function process($str)
 {
     $str = $this->prepareString($str);
     $this->analysis = array();
     switch ($this->analysis_type) {
         case Cryptography::SCOPE_LETTER:
             $res = count_chars($str, 1);
             foreach ($res as $i => $v) {
                 $this->analysis[chr($i)] = $v;
             }
             break;
         case Cryptography::SCOPE_WORD:
             $parts = explode(' ', $str);
             foreach ($parts as $part) {
                 if (!array_key_exists($part, $this->analysis)) {
                     $this->analysis[$part] = substr_count($str, $part);
                 }
             }
             break;
         case Cryptography::SCOPE_RANDOM:
             break;
     }
     uasort($this->analysis, function ($a, $b) {
         return $a > $b ? -1 : ($a == $b ? 0 : 1);
     });
     return $this;
 }
예제 #5
0
/**
 * word-sensitive substring function with html tags awareness
 * @param text The text to cut
 * @param len The maximum length of the cut string
 * @returns string
 * http://de2.php.net/manual/en/function.substr.php#92063
 **/
function mb_substrws($text, $len = 180)
{
    if (mb_strlen($text) > $len) {
        $whitespaceposition = mb_strpos($text, " ", $len) - 1;
        if ($whitespaceposition > 0) {
            $chars = count_chars(mb_substr($text, 0, $whitespaceposition + 1), 1);
            if (array_key_exists(ord('<'), $chars) && array_key_exists(ord('>'), $chars) && $chars[ord('<')] > $chars[ord('>')]) {
                $whitespaceposition = mb_strpos($text, ">", $whitespaceposition) - 1;
            }
            $text = mb_substr($text, 0, $whitespaceposition + 1);
        }
        // close unclosed html tags
        if (preg_match_all("|<([a-zA-Z]+)|", $text, $aBuffer)) {
            if (!empty($aBuffer[1])) {
                preg_match_all("|</([a-zA-Z]+)>|", $text, $aBuffer2);
                if (count($aBuffer[1]) != count($aBuffer2[1])) {
                    foreach ($aBuffer[1] as $index => $tag) {
                        if (empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag) {
                            $text .= '</' . $tag . '>';
                        }
                    }
                }
            }
        }
    }
    return $text;
}
예제 #6
0
 /**
  * Follows the instructions to calculate the floor reached by Santa
  *
  * @param string $instructions The instructions to use for the calculation
  * @return int The floor that has been reached
  */
 public static function calculateFloor($instructions)
 {
     $tokens = count_chars($instructions, 1);
     $ups = (isset($tokens[self::GO_UP]) ? $tokens[self::GO_UP] : 0) * 1;
     $downs = (isset($tokens[self::GO_DOWN]) ? $tokens[self::GO_DOWN] : 0) * -1;
     return $ups + $downs;
 }
예제 #7
0
function is_anagram($a, $b)
{
    if (count_chars($a, 1) == count_chars($b, 1)) {
        return "1";
    }
    return '0';
}
예제 #8
0
 private function countChars($data)
 {
     foreach (count_chars($data, 1) as $char => $count) {
         $this->charCount[chr($char)] = $count;
     }
     $this->sortChars($this->charCount);
 }
예제 #9
0
 public function match(&$collection, $needle, $tolerance)
 {
     $best = $tolerance;
     $match = '';
     $needle_chars = count_chars($needle);
     foreach ($collection as $userAgent) {
         $ua_chars = count_chars($userAgent);
         $sum = 0;
         $can_apply_ld = true;
         //Check from 32 (space) to 122 ('z')
         for ($i = 32; $i < 122; $i++) {
             $sum += abs($needle_chars[$i] - $ua_chars[$i]);
             if ($sum > 2 * $tolerance) {
                 $can_apply_ld = false;
                 break;
             }
         }
         if ($can_apply_ld === true) {
             $current = levenshtein($needle, $userAgent);
             if ($current <= $best) {
                 $best = $current - 1;
                 $match = $userAgent;
             }
         }
     }
     return $match;
 }
예제 #10
0
 function compose($o)
 {
     if ($this->debug || $this->get->src) {
         $o = parent::compose($o);
         $o->cookie_path = $CONFIG['session.cookie_path'];
         $o->cookie_domain = $CONFIG['session.cookie_domain'];
         $o->document_domain = $CONFIG['document.domain'];
         $o->maxage = $CONFIG['maxage'];
     } else {
         ++self::$recursion;
         $src = Patchwork\Superloader::class2file(substr(get_class($this), 6));
         $src = Patchwork\Serverside::returnAgent($src, (array) $this->get);
         --self::$recursion;
         $parser = new JSqueeze();
         if ('/*!' != substr(ltrim(substr($src, 0, 512)), 0, 3)) {
             $o->DATA = Patchwork::__URI__();
             $o->DATA .= (false === strpos($o->DATA, '?') ? '?' : '&') . 'src=1';
             $o->DATA = "// Copyright & source: {$o->DATA}\n";
             foreach (count_chars($o->DATA, 1) as $k => $w) {
                 $parser->charFreq[$k] += $w;
             }
             $o->DATA .= $parser->squeeze($src);
         } else {
             $o->DATA = $parser->squeeze($src);
         }
     }
     return $o;
 }
예제 #11
0
 function runIndentationLoop()
 {
     $lines = explode("\n", $this->body);
     $previousSelector = '';
     $pastLevel = 0;
     $this->body = '';
     foreach ($lines as $key => $line) {
         if (eregi('([a-z]+)\\:', $line)) {
             //Rule
             $this->body .= "\n\t" . trim($line) . ';';
         } elseif (eregi('(\\t*)[\\.a-z]', $line)) {
             // Selector
             if ($previousSelector) {
                 $this->body .= "\n}\n";
             }
             //echo $line."\n";
             $charCount = count_chars($line, 1);
             if (eregi('&', $line)) {
                 $pastLevel = $charCount[9];
                 $this->body .= str_replace('&', trim($previousSelector), trim($line)) . ' {';
             } else {
                 if ($charCount[9] > $pastLevel) {
                     $pastLevel = $pastLevel + 1;
                     $this->body .= eregi('(\\t*)\\:', $line) ? $previousSelector : $previousSelector . ' ';
                     $this->body .= trim($line) . ' {';
                 } else {
                     $this->body .= trim($line) . ' {';
                 }
             }
             $previousSelector = trim($line);
         }
     }
     $this->body .= "\n}";
 }
 /**
  * Create a random string composed of a characters.
  * $length - The number of random strings to include in the result.
  *
  * @param int    $length
  * @param string $charset
  *
  * @throws \InvalidArgumentException If the charset is invalid or if the length is less than 1.
  *
  * @return string
  */
 public static function getRandomString($length, $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~+/')
 {
     self::checkLength($length);
     $charset = count_chars($charset, 3);
     self::checkCharset($charset);
     $characterSet = str_split($charset);
     $charSetLen = count($characterSet);
     $random = self::getRandomInts($length * 2);
     $mask = self::getMinimalBitMask($charSetLen - 1);
     $password = '';
     $iterLimit = max($length, $length * 64);
     // If length is close to PHP_INT_MAX we don't want to overflow.
     $randIdx = 0;
     while (self::safeStringLength($password) < $length) {
         if ($randIdx >= count($random)) {
             $random = self::getRandomInts(2 * ($length - self::safeStringLength($password)));
             $randIdx = 0;
         }
         // This is wasteful, but RNGs are fast and doing otherwise adds complexity and bias.
         $c = $random[$randIdx++] & $mask;
         // Only use the random number if it is in range, otherwise try another (next iteration).
         if ($c < $charSetLen) {
             $password .= self::sideChannelSafeArrayIndex($characterSet, $c);
         }
         // Guarantee termination
         $iterLimit--;
         if ($iterLimit <= 0) {
             throw new \RuntimeException('Hit iteration limit when generating password.');
         }
     }
     return $password;
 }
예제 #13
0
function arrayLetraCount($str)
{
    $tengo = array();
    foreach (count_chars($str, 1) as $i => $val) {
        $tengo[chr($i)] = $val;
    }
    return $tengo;
}
 public function stringorder($string)
 {
     if (preg_match('/[^a-zA-Z\\s-]/i', $string)) {
         abort(404, "Inputan Salah");
     }
     $sortnya = count_chars($string, 3);
     return trim($sortnya);
 }
예제 #15
0
파일: indent.php 프로젝트: philum/cms
function countchars_b($v)
{
    foreach (count_chars($v, 1) as $i => $val) {
        $res += $val;
    }
    //chr($i)
    return $res;
}
예제 #16
0
function getCharactersNumber($message)
{
    $result = 0;
    foreach (count_chars($message, 0) as $i => $val) {
        $result += $i !== 32 ? $val : 0;
    }
    return $result;
}
예제 #17
0
 public function sort($string)
 {
     if (preg_match("/[^a-zA-Z ]/", $string)) {
         abort(404, "invalid input");
     }
     $string = preg_replace("/[^a-zA-Z]+/", "", $string);
     $stringSorted = count_chars($string, 3);
     return trim($stringSorted);
 }
예제 #18
0
 public function write_log($message)
 {
     if (!is_dir($this->log_path)) {
         die('Directory ' . $this->log_path . ' not exist!');
     }
     $f = fopen($this->log_path . $this->file_name, "w+");
     $log_message = $this->format_message($message);
     fputs($f, $log_message, count_chars($log_message));
 }
예제 #19
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;
	}
예제 #20
0
 private function repeatingTimes($haystack, $atomicNeedle)
 {
     if (count_chars($haystack) == 0) {
         return 0;
     }
     if (count_chars($atomicNeedle) == 0) {
         return 0;
     }
     return count(explode(mb_strtolower($atomicNeedle, 'UTF-8'), mb_strtolower($haystack, 'UTF-8'))) - 1;
 }
예제 #21
0
 function is_alpha($val)
 {
     // If the field consists solely of numerics, then we return it as an integer
     // otherwise we return it as an alpha
     $numval = strtr($val, "012345678", "999999999");
     if (count_chars($numval, 3) == '9') {
         return false;
     }
     return true;
 }
예제 #22
0
파일: UUID.php 프로젝트: madal3x/evso
 private function entropy($string)
 {
     $h = 0;
     $size = strlen($string);
     foreach (count_chars($string, 1) as $v) {
         $p = $v / $size;
         $h -= $p * log($p) / log(2);
     }
     return $h;
 }
예제 #23
0
 public function test_letter_frequency()
 {
     $words = new Map(['aardvark', 'roads', 'sparks']);
     $freqs = $words->map(function ($word) {
         return new MapOfInts(count_chars($word, 1));
     })->reduce(function ($totals, $counts) {
         return $totals->translate($counts);
     }, new MapOfInts())->rekey('chr($_1)');
     $this->assertSame(['a' => 5, 'd' => 2, 'k' => 2, 'r' => 4, 'v' => 1, 'o' => 1, 's' => 3, 'p' => 1], $freqs->toArray());
 }
 public function testShuffleString()
 {
     $crypt = new PasswordLib();
     $string = 'abcdefghijklmnopqrstuvwxyz';
     $newString = $crypt->shuffleString($string);
     $this->assertNotEquals($string, $newString);
     $cnt = count_chars($string, 1);
     $cnt2 = count_chars($newString, 1);
     $this->assertEquals($cnt, $cnt2);
 }
예제 #25
0
function prepareCmd($cmd)
{
    //return str_replace("\\;",";",escapeshellcmd($cmd));
    //return $cmd;
    $newcmd = $cmd;
    $c = count_chars($cmd);
    $c[ord("\"")] % 2 ? $newcmd = substr($newcmd, 0, strrpos($newcmd, "\"")) . "\\" . substr($newcmd, strrpos($newcmd, "\"")) : 0;
    $c[ord("'")] % 2 ? $newcmd = substr($newcmd, 0, strrpos($newcmd, "'")) . "\\" . substr($newcmd, strrpos($newcmd, "'")) : 0;
    return $newcmd;
}
예제 #26
0
 public function getAuthSetsForMethod(Request $request)
 {
     $params = $request->getMethodParams();
     MethodUtils::checkSignature(array(Types::STRING), $params);
     $parts = explode('.', $params[0]);
     if (count($parts) != 2 || count_chars($parts[0]) < 1 || count_chars($parts[1]) < 1) {
         throw new InvalidParameterException('methodId must consist of an ' . 'owner object and a method name separated by a single dot.');
     }
     return new ReturnValue(call_user_func_array(array($this->authenticator, 'getAuthSetsForMethod'), $parts));
 }
예제 #27
0
/**
 * Prints first available movie link.
 */
function printMovieAutoLink($url)
{
    $content = file_get_contents($url);
    $newlines = array("\t", "\n", "\r", "  ", "", "\v");
    $content = str_replace($newlines, "", utf8_decode($content));
    if (strpos($content, "http://www.megavideo.com/v")) {
        $regex = "|www.megavideo.com\\/v\\/(.*)\"|U";
    } else {
        if (strpos($content, "&v=")) {
            $regex = "|\\&v\\=(.*)\"|U";
        } else {
            $regex = false;
        }
    }
    if ($regex) {
        preg_match_all($regex, $content, $links);
        if ($links && $links[1]) {
            $links = $links[1];
            $links = array_unique($links);
            foreach ($links as $value) {
                //Get megavideo id
                if (count_chars($value) > 20) {
                    $megavideo_id = substr($value, 0, -32);
                } else {
                    $megavideo_id = $value;
                }
                if (COOKIE_STATE_ACTIVATED && $megavideo_id) {
                    $array = VideoUtil::generateMegavideoPremiumLink($megavideo_id);
                    if ($array) {
                        echo $array[1];
                        return;
                    }
                }
            }
        }
    }
    //Get megaupload links
    if (strpos($content, "www.megaupload.com/?d=")) {
        preg_match_all("|www\\.megaupload\\.com\\/\\?d\\=(.*)\\s?\" class\\=\"Stylehopbleu\"|U", $content, $links);
        if ($links && $links[1]) {
            $links = $links[1];
            $links = array_unique($links);
            foreach ($links as $megaupload_id) {
                if (COOKIE_STATE_ACTIVATED) {
                    $array = VideoUtil::generateMegauploadPremiumLink($megaupload_id);
                    if ($array) {
                        echo $array[1];
                        return;
                    }
                }
            }
        }
    }
    echo "ERROR";
}
예제 #28
0
 /**
  * Creates a new instance of StringDigitList.
  *
  * The list of digits must be provided as a string. Each character
  * represents a single digit and the position in the string represents the
  * value for that digit. For example, base 16 could be defined as
  * `0123456789ABCDEF`.
  *
  * @param string $digits Digits for the numeral system
  * @throws \InvalidArgumentException If the list of digits is invalid
  */
 public function __construct($digits)
 {
     if (strlen($digits) < 2) {
         throw new \InvalidArgumentException('Number base needs at least 2 characters');
     } elseif (strlen(count_chars($digits, 3)) !== strlen($digits)) {
         throw new \InvalidArgumentException('Number base cannot have duplicate characters');
     }
     $this->digits = str_split($digits);
     $this->stringConflict = false;
     $this->setValueMap(array_flip($this->digits));
 }
예제 #29
0
 /**
  * Takes a string and returns the distinct character count.
  *
  * @param $string
  * @return array
  */
 public function getDistinctCharCount($string)
 {
     $charCountBag = [];
     foreach (count_chars($string, 1) as $i => $val) {
         if (!ctype_alpha(chr($i))) {
             continue;
         }
         $charCountBag[chr($i)] = $val;
     }
     return $charCountBag;
 }
예제 #30
0
 /**
  * To calculate entropy of a string.
  * @param string $string    The string whose entropy is to be calculated
  * @return float        The entropy of the string
  */
 public static function Entropy($string)
 {
     $h = 0;
     $size = strlen($string);
     //Calculate the occurence of each character and compare that number with the overall length of the string and put it in the entropy formula.
     foreach (count_chars($string, 1) as $v) {
         $p = $v / $size;
         $h -= $p * log($p) / log(2);
     }
     return $h;
 }