Yngvarr

All generations.

generate functionSat, 04 Feb 2023

open and save json file

function saveToJson(path, data) { fs.writeFile(path, data, err => { console.log(err); }); } function openFromJson(path) { return JSON.parse(fs.readFileSync(path).toString()); }

Javascript
View
generate functionSat, 04 Feb 2023

map to new json

const users = [ { id: 1, name: "Leanne Graham", username: "Bret", email: "Sincere@april.biz", address: { street: "Kulas Light", suite: "Apt. 556", city: "Gwenborough", zipcode: "92998-3874", geo: { lat: "-37.3159", lng: "81.1496" } }, phone: "1-770-736-8031 x56442", website: "hildegard.org", company: { name: "Romaguera-Crona", catchPhrase: "Multi-layered client-server neural-net", bs: "harness real-time e-markets" } }, { id: 2, name: "Ervin Howell", username: "Antonette", email: "Shanna@melissa.tv",

Javascript
View
generate functionSun, 19 Mar 2023

get tdl with domain

function get_tld($url) { $tld = ''; $parsed_url = parse_url($url); $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; if ($host == '') { return $tld; } $host_components = explode('.', $host); $tld_components = array_slice($host_components, -2); $tld = implode('.', $tld_components); return $tld; }

PHP
View
generate functionSat, 04 Feb 2023

ajax post this page

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.example.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&postvar2=value2"); $output = curl_exec($ch); curl_close($ch);

PHP
View
generate functionTue, 07 Feb 2023

get value onclick

<button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x; if (confirm("Press a button!") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = x; } </script>

Javascript
View
generate functionSun, 29 Jan 2023

personal hash

function personal_hash(string $password, string $salt, int $iterations, int $length): string { return substr(hash('sha256', $salt . hash('whirlpool', $password) . $salt), 0, $length); }

PHP
View
generate functionFri, 25 Nov 2022

svg base64 to jpg

function svg2png($string, $filename) { $encoded = base64_encode($string); $data = "data:image/svg+xml;base64,$encoded"; $image = new Imagick(); $image->readImageBlob($data); $image->setImageFormat("png24"); $image->writeImage("$filename"); }

PHP
View
generate functionSun, 19 Mar 2023

parse csv

// parse csv $parsed_data = array_map('str_getcsv', file('data.csv')); echo '<pre>'; print_r($parsed_data); echo '</pre>';

PHP
View
generate functionTue, 21 Mar 2023

file to utf8

function file_get_contents_utf8($fn) { $content = file_get_contents($fn); return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); }

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

function some_curl_pool($urls) { $pool = new AsyncPool(); foreach ($urls as $url) { $pool->add(function () use ($url) { return $this->curl($url); }); } $pool->start(); }

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

$pool = new Pool(10, Client::class, [ 'base_uri' => 'https://example.org', ]); for ($i = 0; $i < 100; ++$i) { $pool->submit($this->getRequest('/something')); } $promise = $pool->promise(); $response = $promise->wait();

PHP
View
generate functionMon, 02 Jan 2023

preg match< / p >

function is_password_valid($password) { if (preg_match("/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[a-zA-Z\d]{8,}$/",$password)) { echo "password valid"; } else { echo "password not valid"; } } is_password_valid("Password123");

PHP
View
generate functionTue, 14 Feb 2023

en месяцы

function enMonth($day, $month, $year) { $day = ($year % 4 == 0) ? $day: $day+1; $days = [31, $day, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; $enMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; $d = 0; for ($i = 0; $i < count($days); $i++) { if ($month > $days[$i]) { $d += $days[$i]; } else { $d += $month; break; } } //echo $d . "<br>"; $m = 0; for ($i = 0; $m < $d; $i++) { $m += $days[$i]; }

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

function month_name_rus($month) { $array = array( 'January' => 'Января', 'February' => 'Февраля', 'March' => 'Марта', 'April' => 'Апреля', 'May' => 'Мая', 'June' => 'Июня', 'July' => 'Июля', 'August' => 'Августа', 'September' => 'Сентября', 'October' => 'Октября', 'November' => 'Ноября', 'December' => 'Декабря' ); return $array[$month]; }

PHP
View
generate functionSun, 19 Mar 2023

domain age

function domain_age($domain) { $domain = DateTime::createFromFormat('Y-m-d', substr($domain, -10)); return $domain->diff(new DateTime())->format('%y'); }

PHP
View
generate functionFri, 25 Nov 2022

svg to jpg

<?php function svgtojpg($svg) { $svg = urlencode($svg) return 'http://svg2jpg.com?svg=' . $svg } echo svgtojpg('<svg></svg>') ?>

PHP
View
generate functionTue, 14 Feb 2023

only time

var today = new Date(); var hourNow = today.getHours(); var greeting; if (hourNow > 18) { greeting = 'Good evening!'; } else if (hourNow > 12) { greeting = 'Good afternoon!'; } else if (hourNow > 0) { greeting = 'Good morning!'; } else { greeting = 'Welcome!'; } document.write('<h3>' + greeting + '</h3>');

Javascript
View
generate functionFri, 09 Dec 2022

обрезать строку с конца

function truncate($string, $length) { $suffix = '...'; return (strlen($string) > $length) ? substr($string, 0, $length - strlen($suffix)) . $suffix : $string; } echo truncate('В настоящее время в мире широко распространено использование стандартных контейнеров предоставляемых языком C++. Они полезны для обработки объектов, не связанных между

PHP
View
generate functionSun, 19 Mar 2023

domain tdl

function get_domain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } get_domain('http://www.google.com/a/b/c/d/e.html')

PHP
View
generate functionThu, 01 Dec 2022

each

function each(list, callback) { for (let i = 0; i < list.length; i++) { callback(list[i], i, list); } } each([1,2,3], (item, index, array) => console.log(item, index, array)) // 1 0 [1, 2, 3] 2 1 [1, 2, 3] 3 2 [1, 2, 3]

Javascript
View
generate functionTue, 20 Dec 2022

last 10 in array

$people = [ 'John Doe', 'Jane Doe', 'Joe Bloggs', 'Sophie Doe', 'John Doe', 'Jane Doe', 'Joe Bloggs', 'Sophie Doe', 'John Doe', 'Jane Doe', 'Joe Bloggs', 'Sophie Doe' ]; function last10($array) { return array_slice($array, -10); } last10($people);

PHP
View
generate functionWed, 22 Mar 2023

day from two dates

function days_between($date1, $date2) { $tmp = DateTime::createFromFormat('Y-m-d', $date1); $start = $tmp->getTimestamp(); $tmp = DateTime::createFromFormat('Y-m-d', $date2); $end = $tmp->getTimestamp(); return round(($end - $start) / (60 * 60 * 24)); }

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

function fullname_ru($first_name, $last_name) { $fullname = $first_name . ' ' . $last_name; return $fullname; } echo fullname_ru('Иван', 'Иванов'); // Иван Иванов

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function gzip_and_stream_archive($archive_file_path) { if (file_exists($archive_file_path)) { if (function_exists('gzencode')) { $archive_size = filesize($archive_file_path); $fp = fopen($archive_file_path, 'r'); if ($fp) { // send gzipped archive header("Content-Encoding: gzip"); header("Content-Length: " . $archive_size); header("Content-Disposition: attachment; filename=backup.tar.gz"); print(gzencode(fread($fp, $archive_size))); fclose($fp); unlink($archive_file_path); return true; } } else { // send unencoded archive header("Content-Type: application/x-gzip"); header("Content-Length: " . filesize($archive_file_path)); header("

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

<?php $month = array( '01' => 'января', '02' => 'февраля', '03' => 'марта', '04' => 'апреля', '05' => 'мая', '06' => 'июня', '07' => 'июля', '08' => 'августа', '09' => 'сентября', '10' => 'октября', '11' => 'ноября', '12' => 'декабря' ); ?>

PHP
View
generate functionMon, 17 Apr 2023

Reply Keyboard Markup telegram

// Return a Small Keyboard function keyboard() { return array( 'keyboard' => array( array( 'Оплата', 'Перевод от админа' ), array( 'Данные пользователя' ), ), 'resize_keyboard' => true, 'one_time_keyboard' => true, ); }

PHP
View
generate functionSun, 12 Feb 2023

обрезка массива

function array_slice_assoc(array &$array, $offset, $length = null, $preserve_keys = false) { $array = array_slice($array, $offset, $length, $preserve_keys); return $array; } $arr = array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 ); $arr = array_slice_assoc($arr, 1); print_r($arr);

PHP
View
generate functionTue, 24 Jan 2023

5 знаков после запятой

const toFixed = (value, precision) => { const power = Math.pow(10, precision || 0); return String(Math.round(value * power) / power); }; console.log(toFixed(0.123456789, 5)); // '0.12346' console.log(toFixed(0.123456789, 2)); // '0.12' console.log(toFixed(2.345, 2)); // '2.35' console.log(toFixed(2.355, 2)); // '2.35'

Javascript
View
generate functionFri, 14 Apr 2023

search in array

function binarySearch(arr, target) { let start = 0 let end = arr.length - 1 while (start <= end) { const mid = Math.floor((start + end) / 2) if (arr[mid] === target) { return mid } else if (arr[mid] < target) { start = mid + 1 } else { end = mid - 1 } } return -1 }

Javascript
View
generate functionTue, 14 Feb 2023

return month text

function month($month_number): $month_dict = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } return $month_dict[$month_number] month(1)

PHP
View
generate functionSat, 25 Mar 2023

table to array

function tableToArray(table) { var tbl = []; $.each(table.tBodies[0].rows, function (i, row) { var theRow = []; theRow.push(row.cells[0].innerHTML + ' ' + row.cells[1].innerHTML); tbl[i] = theRow; }); return tbl; }

Javascript
View
generate functionFri, 10 Feb 2023

timeout 10 button active

<button id="button">Click me</button> var button = document.getElementById("button"); function disableButton() { button.disabled = true; } setTimeout(disableButton, 10);

Javascript
View
generate functionTue, 14 Feb 2023

en месяцы склонения

function en(mounth) { if(mounth == '1'){ return 'January' } if(mounth == '2'){ return 'February' } if(mounth == '3'){ return 'March' } if(mounth == '4'){ return 'April' } if(mounth == '5'){ return 'May' } if(mounth == '6'){ return 'June' } if(mounth == '7'){ return 'July' } if(mounth == '8'){ return 'August' } if(mounth == '9'){ return 'September' } if(mounth == '10'){ return 'October' } if(mounth == '11'){ return 'November' } if(mounth == '

PHP
View
generate functionSat, 11 Feb 2023

get url

const getUrl = (url) => { const request = new Request(url, { method: 'GET', cache: 'default' }); fetch(request).then(res => res.json()).then(res => console.log(res)); } getUrl('https://api.github.com/users/jacky99')

Javascript
View
generate functionSat, 04 Feb 2023

open and save json file

function readFile(filename, content) { fs.readFile(filename, function(err, data) { if (err) throw err; console.log('File saved!'); }); } function writeFile(filename, content) { fs.writeFile(filename, content, function(err) { if (err) throw err; console.log('File saved!'); }); }

Javascript
View
generate functionFri, 20 Jan 2023

обрезать число

function truncate(input, places) { if(input >= Math.pow(10, places)) { return input.toString().slice(0, -1 * places) + "." + input.toString().slice(-1 * places); } else { return input.toString(); } }

Javascript
View
generate functionFri, 17 Feb 2023

fullname month ru

function getMonthName($a) { $array = [ 1 => 'январь', 2 => 'февраль', 3 => 'март', 4 => 'апрель', 5 => 'май', 6 => 'июнь', 7 => 'июль', 8 => 'август', 9 => 'сентябрь', 10 => 'октябрь', 11 => 'ноябрь', 12 => 'декабрь', ]; if (array_key_exists($a, $array)) { return $array[$a]; } return null; } getMonthName(1);

PHP
View
generate functionTue, 21 Mar 2023

convert file to utf8

function convert_to_utf8_recursively($dat) { if (is_string($dat)) { return mb_convert_encoding($dat, 'UTF-8', 'UTF-8'); } elseif (is_array($dat)) { $ret = array(); foreach ($dat as $i => $d) $ret[ $i ] = convert_to_utf8_recursively($d); return $ret; } elseif (is_object($dat)) { foreach ($dat as $i => $d) $dat->$i = convert_to_utf8_recursively($d); return $dat; } else { return $dat; } }

PHP
View
generate functionTue, 21 Mar 2023

convert file to utf8

function convert_to_utf8($fileName) { $fileName = str_replace('/', '\\\\', $fileName); $encoding = mb_detect_encoding($fileName); if ($encoding != 'UTF-8') { if ($encoding == 'GB18030') { $encoding = 'GBK'; } echo 'The file is not utf8, encoding is ' . $encoding . '<br>'; $str = file_get_contents($fileName); $str = mb_convert_encoding($str, 'UTF-8', $encoding); file_put_contents($fileName, $str); } }

PHP
View
generate functionSat, 18 Feb 2023

new Date() utc0

function todayUTC() { var date = new Date(); date.setHours(date.getHours() + 9); return date.toISOString().slice(0, 10); }

Javascript
View
generate functionFri, 17 Feb 2023

fullname month ru

<?php function fullname($month) { switch ($month) { case 1: return "Январь"; break; case 2: return "Февраль"; break; case 3: return "Март"; break; case 4: return "Апрель"; break; case 5: return "Май"; break; case 6: return "Июнь"; break; case 7: return "Июль"; break; case 8: return "Август"; break; case 9: return "Сентябрь"; break; case 10: return "Октябрь"; break; case 11: return "Ноябрь";

PHP
View
generate functionSun, 19 Mar 2023

get tdl with domain

function get_tld($domain) { if (preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches)) return $matches['domain']; return ''; }

PHP
View
generate functionSat, 07 Jan 2023

gzencode return archive

<?php function gzencode($data, $mode = 9, $encoding_mode = FORCE_GZIP) { $flags = 0; if ($mode != $mode) { $flags += 1; } if ($encoding_mode == FORCE_GZIP) { $flags += 2; } if (function_exists("gzencode")) { return gzencode($data, $mode, $flags); } return $data; } ?>

PHP
View
generate functionMon, 14 Nov 2022

уникализация массива

function unique(arr) { var result = []; for (var str of arr) { if (!result.includes(str)) { result.push(str); } } return result; } var strings = ["кришна", "кришна", "харе", "харе", "харе", "харе", "кришна", "кришна", ":-O" ]; alert( unique(strings) ); // кришна, харе, :-O

Javascript
View
generate functionFri, 25 Nov 2022

svg to jpg

<?php $svg = <<< EOT ... ... ... EOT; $svg = file_get_contents('https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_announcement_48px.svg'); $im = new Imagick(); $im->setBackgroundColor(new ImagickPixel('transparent')); $im->readImageBlob($svg); $im->setImageFormat("jpg"); $im->writeImage('image.jpg'); ?>

PHP
View
generate functionTue, 24 Jan 2023

get last key

$name = array('first' => 'Jack', 'last' => 'Bauer'); function get_last_key($arr){ end($arr); return key($arr); } get_last_key($name);

PHP
View
generate functionSat, 07 Jan 2023

return xml gz archive

function get_xml(){ $xml_doc = new DOMDocument(); $xml_doc->load("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0"); $xml_string = $xml_doc->saveXML(); $filename = "xml_" . time(); $gzfilename = $filename . ".gz"; $fp = fopen($gzfilename, "w"); fwrite($fp, $xml_string); fclose($fp); $fd = fopen ($gzfilename, "r"); header("Content-Type: application/x-gzip"); header("Content-Disposition: attachment; filename=\"".$gzfilename."\""); fpassthru($fd); unlink($gzfilename); }

PHP
View
generate functionSat, 07 Jan 2023

return gz archive

$gz = gzencode($string, 9); $filename = 'compressed.gz'; header("Content-Encoding: gzip"); header("Content-Length: ".strlen($gz)); header("Content-Disposition: attachment; filename=$filename"); header("Content-Type: text/plain"); echo $gz;

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function stream_curl_gzencoded($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); $result = curl_exec($ch); curl_close($ch); return $result; }

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

<?php function gzencode_and_stream_http_archive() { function get_current_url() { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; } return $pageURL; } $url = get_current_url(); header("Content-Type: application/x-gzip"); header("Content-Disposition: attachment; filename=web.archive"); $curl = curl_init(); curl_

PHP
View
generate functionThu, 22 Dec 2022

date to text

function date_to_text(date) { return date.toLocaleDateString( "en-US", { year: "numeric", month: "short", day: "numeric" } ); }

Javascript
View
generate functionTue, 21 Mar 2023

convert file to utf8

function convert_to_utf8_recursively($dat) { if (is_string($dat)) return utf8_encode($dat); if (!is_array($dat)) return $dat; $ret = []; foreach ($dat as $i => $d) $ret[$i] = self::convert_to_utf8_recursively($d); return $ret; }

PHP
View
generate functionSat, 07 Jan 2023

generate gz archive

function tar_gz($source, $destination) { if (extension_loaded('zlib')) { if (is_file($source)) { $file = basename($source); $source = dirname($source); } else { $file = basename($destination); $source = $source; } if (!file_exists("$destination/$file.gz")) { $destination = dirname($destination); if (!extension_loaded('zlib')) { return false; } $archive = new PharData("$source/$file"); $archive->compress(Phar::GZ); unset($archive); rename("$source/$file.gz", "$destination/$file.gz"); return "$destination/$file.gz"; } } return false; }

PHP
View
generate functionTue, 14 Feb 2023

return month text

def month(i): months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] return months[i] month(4)

PHP
View
generate functionFri, 10 Feb 2023

timeout 10 button active

function timeout(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function asyncPrint(value, ms) { await timeout(ms); console.log(value); } asyncPrint('hello world', 5000);

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

<?php $url = 'https://www.google.com'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec($curl); curl_close($curl); echo $result; ?>

PHP
View
generate functionWed, 22 Mar 2023

domain age

<?php function domain_age($domain) { // TODO: return the age of the domain in years $whois = "whois $domain"; $txt = shell_exec($whois); $start = explode("Creation Date: ", $txt); $end = explode("\n", $start[1]); $date = $end[0]; $date_array = explode("/", $date); $year = $date_array[2]; $current_year = date("Y"); $age = $current_year - $year; return $age; } echo domain_age("google.com"); // returns "18" echo domain_age("bbc.co.uk"); // returns "28" echo domain_age("github.com"); // returns "9" echo domain_age("facebook.com"); // returns "13"

PHP
View
generate functionSun, 19 Mar 2023

domain tdl

function tld($domain) { $pieces = explode('.', $domain); $tld = array_pop($pieces); return $tld; } tld('www.example.com');

PHP
View
generate functionWed, 08 Feb 2023

$_SERVER get code status

function getStatusCode($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $status; }

PHP
View
generate functionSat, 10 Dec 2022

get domain whith subdomain

function get_domain_name($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; }

PHP
View
generate functionTue, 14 Feb 2023

time online

var hh = 0; var mm = 0; var ss = 0; var start = false; var timerInterval = null; function startTimer() { if (start === false) { start = true; timerInterval = setInterval(function() { ss++; if (ss === 60) { mm++; ss = 0; } if (mm === 60) { hh++; mm = 0; } var newTime = (hh < 10 ? '0' + hh : hh) + ':' + (mm < 10 ? '0' + mm : mm) + ':' + (ss < 10 ? '0' + ss : ss); document.querySelector('.timer').innerHTML = newTime; }, 1000); } } function stopTimer() { if (start === true) { start = false; clearInterval(timerInterval); } } function resetTimer() { stopTimer(); hh

Javascript
View
generate functionTue, 14 Feb 2023

clock online

function clock() { var now = new Date(); var ctx = document.getElementById('clock').getContext('2d'); ctx.save(); ctx.clearRect(0,0,150,150); ctx.translate(75,75); ctx.scale(0.4,0.4); ctx.rotate(-Math.PI/2); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.lineWidth = 8; ctx.lineCap = "round"; // Hour marks ctx.save(); for (var i=0;i<12;i++){ ctx.beginPath(); ctx.rotate(Math.PI/6); ctx.moveTo(100,0); ctx.lineTo(120,0); ctx.stroke(); } ctx.restore(); // Minute marks ctx.save(); ctx.line

Javascript
View
generate functionThu, 09 Feb 2023

generate phrase

function generatePhrase($a, $b, $c) { $phrase = "$a $b $c"; return $phrase; } $phrase = generatePhrase("nice", "to", "meet you"); echo $phrase;

PHP
View
generate functionFri, 24 Feb 2023

set time zone 0

var time = new Date().getHours() if (time < 10) { document.write("Good morning") } else if (time < 20) { document.write("Good day") } else { document.write("Good evening") }

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

<?php $urls = array( 'http://www.example.com', 'http://www.example.com/foo/bar', 'http://www.example.com/baz/qux', ); $multi = curl_multi_init(); $handles = array(); foreach ($urls as $key => $url) { $handles[$key] = curl_init($url); curl_setopt($handles[$key], CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $handles[$key]); } $running = null; do { curl_multi_exec($multi, $running); } while ($running); foreach ($handles as $key => $handle) { $results[$key] = curl_multi_getcontent($handle); curl_multi_remove_handle($multi, $handle); } curl_multi_close($multi)

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function gzencode_http_zip($gzdata){ $gzsize = strlen($gzdata); $gzcrc = crc32($gzdata); $gzdata = gzcompress($gzdata,9); $gzdata = substr($gzdata,0,strlen($gzdata)-4); $rawdata = "\x1f\x8b\x08\x00\x00\x00\x00\x00".$gzdata."\x00\xff\xff".pack('V',$gzcrc).pack('V',$gzsize); return $rawdata; }

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone

function curl_asynchrone($url, $post=array(), $cookie=array()) { $result = array( "response" => "", "http_code" => "", "header_size" => "", "request_size" => "", "filetime" => "", "ssl_verify_result" => "", "redirect_count" => "", "total_time" => "", "namelookup_time" => "", "connect_time" => "", "pretransfer_time" => "", "size_upload" => "", "size_download" => "", "speed_download" => "", "speed_upload" => "", "download_content_length" => "", "upload_content_length" => "", "starttransfer_time" => "", "redirect_time" => "", "error" => "", ); $ch = curl_

PHP
View
generate functionWed, 08 Feb 2023

get request code status

function get_status_code($url){ $str = file_get_contents($url); if(strlen($str)>0){ preg_match('/http_code:(\d+)/', $str, $matches); return $matches[1]; } return false; }

PHP
View
generate functionSat, 11 Feb 2023

get url

function getURL(url) { const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", url, false); xmlhttp.send(null); return xmlhttp.responseText }

Javascript
View
generate functionSun, 19 Mar 2023

get tdl with domain

<?php $domains = array('apple.com', 'google.com', 'microsoft.com'); if (in_array($_GET['domain'], $domains)) { echo "found"; } else { echo "not found"; } ?>

PHP
View
generate functionThu, 16 Mar 2023

ftp_put

function ftp_put($source, $destination, $mode = FTP_ASCII, $context = null) { return ftp_put($this->connection, $destination, $source, $mode, $context); }

PHP
View
generate functionThu, 16 Mar 2023

ftp_put

function ftp_put($server, $filepath, $remotepath, $username, $password) { // add code here } ftp_put('ftp.example.com', '/local/filename', '/public_html/filename', 'username', 'password');

PHP
View
generate functionThu, 06 Apr 2023

get page html

var http = require('http'); var options = { host: 'www.google.com', port: 80, path: '/' }; http.get(options, function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); });

Javascript
View
generate functionSat, 18 Feb 2023

new Date() utc0

function get_utc_datetime() { return new Date().toISOString().substr(0,19).replace('T',' ' ); } console.log(get_utc_datetime());

Javascript
View
generate functionMon, 14 Nov 2022

новый массив по ключу из другого многомерного массива

<?php function filterByKey($array, $keyName) { $result = []; foreach ($array as $item) { if (isset($item[$keyName])) { $result[] = $item[$keyName]; } } return array_unique($result); } $array = [ ['product_id' => 'xxxx', 'name' => 'iphone'], ['product_id' => 'yyyy', 'name' => 'samsung'], ['product_id' => 'xxxx', 'name' => 'iphone'], ]; $result = filterByKey($array, 'product_id'); print_r($result);

PHP
View
generate functionFri, 10 Feb 2023

валидация логина

function validLogin(login) { return /^[a-zA-Z][a-zA-Z0-9-_\.]{1,20}$/.test(login); } validLogin('eee'); // true validLogin('eee#'); // false validLogin('eee@'); // false validLogin('eee1'); // true validLogin('eee1#'); // false validLogin('eee1@'); // false validLogin('eee1.'); // true validLogin('eee1.e'); // true validLogin('eee1.eee'); // true validLogin('eee1.eee1'); // true validLogin('eee1.eee1.'); // true validLogin('eee1.eee1.e'); // true validLogin('eee1.eee1.eee'); // false validLogin('eee1.eee1.eee1'); // false validLogin('eee1.eee1.eee1.'); // false validLogin('eee

Javascript
View
regex explanationThu, 23 Mar 2023

/\B@[a-z0-9_-]+/g

The regex matches all twitter usernames, the @ is not a word boundary, so the @ is required to be matched before the username. The character class [a-z0-9_-] matches all letters, numbers and underscores. The + is a quantifier which means "one or more of the preceding character". The g modifier means "global", so the regex will find all matches.

generate functionTue, 14 Feb 2023

русские месяцы склонения

public static function getRusMonths( $year, $type = false ) { $months = array( '01' => 'января', '02' => 'февраля', '03' => 'марта', '04' => 'апреля', '05' => 'мая', '06' => 'июня', '07' => 'июля', '08' => 'августа', '09' => 'сентября', '10' => 'октября', '11' => 'ноября', '12' => 'декабря' ); $result = array(); if ( $type ) { foreach( $months as $key=>$value ) { $result[$key] = self::getRusMonth(

PHP
View
generate functionMon, 26 Dec 2022

текущий месяц номер

function getMonthNumber(monthName) { if (monthName === 'January') { return 1; } else if (monthName === 'February') { return 2; } else if (monthName === 'March') { return 3; } else if (monthName === 'April') { return 4; } else if (monthName === 'May') { return 5; } else if (monthName === 'June') { return 6; } else if (monthName === 'July') { return 7; } else if (monthName === 'August') { return 8; } else if (monthName === 'September') { return 9; } else if (monthName === 'October') { return 10; } else if (monthName === 'November') { return 11; } else if (monthName === 'December') { return 12; } }

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

//curl asynchronous pool $pool = new CurlPool($max_requests = 10); foreach (range(1, 100) as $index) { $url = "https://www.google.com/$index"; $pool->request($url, function ($content) use ($url) { echo "Loaded $url \n"; }); } $pool->finish();

PHP
View
generate functionSun, 29 Jan 2023

personal hash

<?php function personal_hash($string){ $hash = null; $key = "a1b2c3d4"; for ($i = 0; $i < strlen($string); ++$i) { $hash .= $string[$i] . $key[$i]; } return $hash; } ?>

PHP
View
generate functionFri, 25 Nov 2022

svg to jpg

$(window).load(function(){ $("#svgid").change(function(){ $.ajax({ type: "POST", url: "svgimg.php", data: {data : $("#svgid").val() } }) }); });

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

function curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); return $output; } $urls = array( 'http://www.example.com', 'http://www.example.co.uk', 'http://www.example.com.br', 'http://www.example.ru', 'http://www.example.es', ); $pool = new Pool(10); foreach ($urls as $url) { $pool->submit(new CurlTask($url)); } $pool->shutdown();

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

def ru_month(month): return { 'January': 'январь', 'February': 'февраль', 'March': 'март', 'April': 'апрель', 'May': 'май', 'June': 'июнь', 'July': 'июль', 'August': 'август', 'September': 'сентябрь', 'October': 'октябрь', 'November': 'ноябрь', 'December': 'декабрь' }[month] def fullname(first, last, month): return f"{first} {last} {ru_month(month)}" fullname('Peter', 'Parker', 'May')

PHP
View
generate functionSat, 07 Jan 2023

return xml gz archive

function get_xml_archive($target) { $xml = get_remote_data($target); $file_name = tempnam(sys_get_temp_dir(), 'xml'); file_put_contents($file_name, gzencode($xml)); return $file_name; }

PHP
View
generate functionWed, 16 Nov 2022

Math.max() by key

function max(numbers) { var currentMax = numbers[0]; for(var i = 0; i < numbers.length; i++) { if (numbers[i] > currentMax) { currentMax = numbers[i]; } } return currentMax; } max([1, 4, 2])

Javascript
View
generate functionTue, 14 Feb 2023

01 to 1

function bin2dec($str) { $str_ary = str_split($str); $result = 0; foreach ($str_ary as $key => $value) { $result += $value * pow(2, (count($str_ary) - 1 - $key)); } return $result; } echo(bin2dec(110101));

PHP
View
generate functionSun, 29 Jan 2023

uuid personal

function uuid($personal=false){ if (!$personal) { $uuid = random_bytes(16); } else { $uuid = md5(uniqid().$personal, true); } $uuid[6] = chr(ord($uuid[6]) & 0x0f | 0x40); $uuid[8] = chr(ord($uuid[8]) & 0x3f | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($uuid), 4)); } uuid('admin');

PHP
View
generate functionSun, 12 Feb 2023

обрезка массива

function cutTheArray($array, $start, $length = null) { $count = count($array); if($start < 0) { $start = $count + $start; } if($length !== null) { if($length < 0) { $length = $count - $start + $length; } return array_slice($array, $start, $length); } else { return array_slice($array, $start); } } cutTheArray([1, 2, 3, 4, 5, 6], 2, 1); // [3] cutTheArray([1, 2, 3, 4, 5, 6], 0, 3); // [1, 2, 3] cutTheArray([1, 2, 3, 4, 5, 6], -2); // [5, 6]

PHP
View
generate functionSat, 18 Feb 2023

new Date() utc0

function getDate() { const date = new Date(); return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay(); }

Javascript
View
generate functionFri, 13 Jan 2023

replace in string

function replaceInString(str, index, replacement) { return str.substr(0, index) + replacement+ str.substr(index + replacement.length); }

Javascript
View
generate functionThu, 22 Dec 2022

get name day to date

const getDay = (date) => { const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] return days[date.getDay()] } getDay(new Date(2020, 10, 16))

Javascript
View
generate functionSat, 07 Jan 2023

pack to gz and return archive file download

function pack($dir){ $dir = realpath($dir); $phar = new PharData($dir.'.tar'); $phar->buildFromDirectory($dir); $phar->compress(Phar::GZ); header('Content-Type: application/x-gzip'); header('Content-Disposition: attachment; filename="'.pathinfo($dir.'.tar.gz', PATHINFO_BASENAME).'"'); echo file_get_contents($dir.'.tar.gz'); }

PHP
View
generate functionSat, 07 Jan 2023

return xml gz archive

<?php function xml_gz_archive() { $api = new Api(); $xml = $api->getXml(); $gzfile = gzopen($xml, 'w9'); gzwrite($gzfile, $xml); gzclose($gzfile); return $gzfile; }

PHP
View
generate functionSun, 19 Mar 2023

domain age

<?php $age = 18; if ($age >= 18) { echo "<p>You are old enough to drive!</p>"; } elseif ($age > 16) { echo "<p>You can drive!</p>"; } else { echo "<p>You are not old enough to drive...</p>"; }

PHP
View
generate functionTue, 14 Feb 2023

русские месяцы склонения

function month($nom, $padezh) { $monat = array('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'); $monat_rod = array('Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Дека

PHP
View
generate functionSat, 07 Jan 2023

pack to gz and return archive file download

function pack_and_download($file){ $filename = $file->getClientOriginalName(); $tmpFile = tempnam(sys_get_temp_dir(), 'data'); $tmpFileHandle = fopen($tmpFile, 'w'); fwrite($tmpFileHandle, $file->get()); fclose($tmpFileHandle); $outputFile = tempnam(sys_get_temp_dir(), 'data') . ".gz"; $fp = gzopen($outputFile, 'wb9'); gzwrite($fp, file_get_contents($tmpFile)); gzclose($fp); $response = new Response(file_get_contents($outputFile), 200); $response->header('Content-Type', 'application/x-gzip'); $response->header('Content-Disposition', 'attachment; filename=' . $filename . '.gz'); return $response; }

PHP
View
generate functionWed, 22 Mar 2023

domain age

function domain_age($domain) { $whois = new Whois(); $whois_result = $whois->lookup($domain); $registered = $whois_result->createdDate; $now = new DateTime(); $diff = $now->diff($registered); return $diff->y; }

PHP
View
generate functionFri, 10 Feb 2023

timeout 10 button active

// Button <button>Click Me!</button> // Javascript var button = document.querySelector("button"); button.addEventListener("click", function(e) { button.style.background = "blue"; });

Javascript
View
generate functionTue, 14 Feb 2023

русские месяцы склонения

function get_months($number, $case, $sex) { $numbers = explode('-', $number); $result = array(); foreach ($numbers as $number) { $result[] = get_month($number, $case, $sex); } return implode('-', $result); } function get_month($number, $case, $sex) { $months = array( 1 => array('январь', 'января', 'январе'), 2 => array('февраль', 'февраля', 'феврале'), 3 => array('март', 'марта', 'марте'), 4 => array('апрель', 'апреля', 'апреле'), 5 => array('май', 'мая',

PHP
View
generate functionSat, 11 Feb 2023

get location url

function getUrl(key) { let url = window.location.href let urlList = url.split('?')[1].split('&') for (let i in urlList) { if (urlList[i].split('=')[0] === key) { return urlList[i].split('=')[1] } } return undefined }

Javascript
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function stream_gzencode($data) { $size = strlen($data); $crc = crc32($data); $data = gzencode($data, 9); $data = substr($data, 0, -4); echo "\x1f\x8b\x08\x00\x00\x00\x00\x00"; echo $data; echo pack('V', $crc); echo pack('V', $size); } stream_gzencode(file_get_contents('http://example.com/'));

PHP
View
generate functionSat, 25 Mar 2023

table to array

function tableToArray (table) { var rows = table.rows; var cols = table.rows[0].cells.length; var rowArray = []; var rowData = []; var cellData = []; for (var i = 0; i < rows.length; i++) { rowData = []; for (var j = 0; j < cols; j++) { rowData.push(rows[i].cells[j].innerHTML); } rowArray.push(rowData); } return rowArray; }

Javascript
View
generate functionTue, 14 Feb 2023

en месяцы склонения

function getMonthName($monthNumber) { $months = array( 1 => 'января', 2 => 'февраля', 3 => 'марта', 4 => 'апреля', 5 => 'мая', 6 => 'июня', 7 => 'июля', 8 => 'августа', 9 => 'сентября', 10 => 'октября', 11 => 'ноября', 12 => 'декабря' ); return $monthNumber > 0 && $monthNumber < 13 ? $months[$monthNumber] : null; }

PHP
View
generate functionFri, 10 Feb 2023

timeout counter

var timeout = function(counter) { if (counter > 0) { setTimeout(function() { console.log(counter); timeout(counter - 1); }, 1000); } }; timeout(5);

Javascript
View
generate functionMon, 16 Jan 2023

replace last symbols

function replaceLast($str, $from, $to) { $pos = strrpos($str, $from); if($pos !== false) { $str = substr_replace($str, $to, $pos, strlen($from)); } return $str; }

PHP
View
generate functionSun, 19 Mar 2023

get tdl with domain

function get_tld($domain){ $domain_tld = null; if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches)){ $domain_tld = $matches['domain']; } return $domain_tld; }

PHP
View
generate functionMon, 20 Feb 2023

copy to buffer

function generate_hash(str) { var hash = 0, i, chr; if (str.length === 0) return hash; for (i = 0; i < str.length; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

$client = new Client(); $promises = ['foo', 'bar', 'baz'] ->map( function ($url) use ($client) { return $client->getAsync($url); } ); $results = Promise\settle($promises)->wait();

PHP
View
generate functionSat, 07 Jan 2023

pack to gz and return archive file download

function pack_and_download($file){ // pack the file $gzfile = gzopen($file.".gz", "w9"); gzwrite($gzfile, file_get_contents($file)); gzclose($gzfile); // download the file header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'.gz"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file.".gz")); ob_clean(); flush(); readfile($file.".gz"); unlink($file.".gz"); exit; }

PHP
View
generate functionSun, 19 Feb 2023

get first 5 symbols

function get_first_five_symbols($string) { return substr($string, 0, 5); } get_first_five_symbols('Hello'); // 'Hello' get_first_five_symbols('Hello World'); // 'Hello' get_first_five_symbols('Hello World!'); // 'Hello'

PHP
View
generate functionSat, 04 Feb 2023

write to sile

<?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "John Doe\n"; fwrite($myfile, $txt); $txt = "Jane Doe\n"; fwrite($myfile, $txt); fclose($myfile); ?>

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function stream_gz_encode($data, $compressed_size) { $size = strlen($data); $crc = crc32($data); $data = gzencode($data, 9); $data = substr_replace($data, pack('V', $crc), -8, 4); $data = substr_replace($data, pack('V', $size), -4, 4); $compressed_size += strlen($data); printf('%s%s%s%s%s', substr($data, 0, 4), pack('V', $crc), pack('V', $size), pack('v', strlen($data) - 12), substr($data, -(strlen($data) - 12)) ); }

PHP
View
generate functionSat, 07 Jan 2023

pack to gz and return archive file download

<?php function pack_to_gz($file) { $zip = new ZipArchive; $filename = $file . ".gz"; //$zip->open($filename, ZipArchive::CREATE); //$zip->addFile($file); //$zip->close(); //header('Content-Type: application/zip'); //header('Content-disposition: attachment; filename=' . $filename); //header('Content-Length: ' . filesize($filename)); //readfile($filename); //return $filename; } pack_to_gz('/Users/danghong/Desktop/d-hong.com.zip'); ?>

PHP
View
generate functionFri, 10 Feb 2023

timeout counter

function timeoutCounter(seconds, callback) { setTimeout(function() { let time = seconds-- callback(time) return timeoutCounter(seconds, callback) }, 1000) } timeoutCounter(10, function(count) { console.log(count) })

Javascript
View
generate functionSat, 25 Mar 2023

table td to array

function td2array(table) { var rows = $('tr', table); var tbody = rows.parent(); var ret = []; for (var i = 0; i < rows.length; i++) { var row = rows[i]; var cols = $('td', row); for (var j = 0; j < cols.length; j++) { var col = cols[j]; var text = col.innerText; if (text === '') { text = '0'; } ret.push(text); } } return ret; }

Javascript
View
generate functionMon, 20 Feb 2023

copy text

function copyText(text) { // create textarea var textarea = document.createElement("textarea"); // set textarea value textarea.value = text; // make textarea read only textarea.readOnly = true; // append to document body document.body.appendChild(textarea); // select text textarea.select(); // copy text document.execCommand("copy"); // remove textarea document.body.removeChild(textarea); }

Javascript
View
generate functionTue, 14 Feb 2023

русские месяцы склонения

$months = array( 'январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь' ); function rusMonth($month) { global $months; $month = $months[$month - 1]; $last_letter = substr($month, -1); // последняя буква switch ($last_letter) { case "ь": $month .= "я"; break; case "й": $month .= "я"; break; default: $

PHP
View
generate functionSat, 04 Feb 2023

ajax post this page

function postData(url) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.onload = function() { var data = xhr.responseText; resolve(data); }; xhr.onerror = function() { reject(Error(xhr.statusText)); }; xhr.send(); }); } postData("/data.json") .then(data => { console.log(data); }) .catch(error => { console.error(error); });

Javascript
View
generate functionSun, 19 Mar 2023

domain age

def domain_age(domain): from datetime import datetime from tld import get_tld domain = get_tld(domain, as_object=True) return int((datetime.now() - domain.creation_date).days) domain_age('https://www.google.com')

PHP
View
generate functionSat, 18 Feb 2023

uuid

function uuid(){ return sprint_f("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

<?php // Create a curl handle to a non-existing location $ch = curl_init('http://www.example.com/doesntexist'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Create a DOM object $dom = new DOMDocument; // Augment the DOM object with the addCallback function $dom->addCallback = function($ch, $data) use ($dom) { @$dom->loadHTML($data); }; // Set your options and execute curl_setopt_array($ch, array( CURLOPT_URL => "http://www.example.com/", CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 2, CURLOPT_COOKIEFILE => "", CURLOPT_COOKIEJAR => "", CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux x86_64; en-US;

PHP
View
generate functionWed, 25 Jan 2023

uuid

function uuid() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

function month($m) { if ($m==1) return 'Январь'; if ($m==2) return 'Февраль'; if ($m==3) return 'Март'; if ($m==4) return 'Апрель'; if ($m==5) return 'Май'; if ($m==6) return 'Июнь'; if ($m==7) return 'Июль'; if ($m==8) return 'Август'; if ($m==9) return 'Сентябрь'; if ($m==10) return 'Октябрь'; if ($m==11) return 'Ноябрь'; if ($m==12) return 'Декабрь'; }

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function stream_gzencode($input) { $size = strlen($input); $crc = crc32($input); $gzdata = "\x1f\x8b\x08\x00\x00\x00\x00\x00".substr(gzcompress($input, 9), 0, -4).pack('V', $crc).pack('V', $size); header('Content-Encoding: gzip'); header('Content-Length: '.strlen($gzdata)); header('Content-type: application/x-gzip'); die($gzdata); }

PHP
View
regexFri, 24 Feb 2023

text validation

/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/

regex explanationThu, 23 Mar 2023

(?=.{5,32}$)(?!.*__)(?!^(telegram|admin|support))[a-z][a-z0-9_]*[a-z0-9]$

The regex matches words that are between 5 and 32 characters long. The regex rejects words that contain two consecutive underscores. The regex rejects words that start with "admin", "telegram", or "support". The regex matches words that begin with a letter. The regex matches words that end with a letter or number. The regex matches words that contain only letters, numbers, or underscores. The regex matches no uppercase letters.

generate functionFri, 17 Feb 2023

fullname month

$months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; function fullNameMonth($position) { global $months; echo $months[$position - 1]; } fullNameMonth(1);

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

function gzencode_stream($input, $level = -1, $mode = FORCE_GZIP) { $mode = in_array($mode, array(FORCE_GZIP, FORCE_DEFLATE, FORCE_DEFLATE), TRUE) ? $mode : FORCE_GZIP; $level = ($level = (int)$level) < 0 || $level > 9 ? -1 : $level; if (function_exists('gzdeflate')) { $mode = ($mode == FORCE_GZIP) ? FORCE_DEFLATE : $mode; } elseif (function_exists('gzencode') && $mode == FORCE_GZIP) { return gzencode($input, $level); } elseif (function_exists('gzcompress') && $mode == FORCE_DEFLATE) { return gzcompress($input, $level); } $flags = ($mode == FORCE_DEFLATE) ? FORCE_DEFLATE : 0

PHP
View
generate functionFri, 25 Nov 2022

svg to jpg

function svgToJpg($svgFile) { $svg = file_get_contents($svgFile); $png = new Imagick(); $png->setBackgroundColor(new ImagickPixel('transparent')); $png->setFormat("jpeg"); $png->readImageBlob($svg); $png->setImageFormat("jpeg"); $png->writeImage('test.jpg'); $png->clear(); $png->destroy(); }

PHP
View
generate functionThu, 22 Dec 2022

date to text

function dateToText(input) { var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var date = input.toString(); var year = date.slice(0, 4); var month = date.slice(4, 6); var day = date.slice(6, 8); return months[month - 1] + " " + day + ", " + year; } dateToText(20180822)

Javascript
View
generate functionTue, 14 Feb 2023

return month text

function getMonthName($month) { if($month == 1) return "Jan"; if($month == 2) return "Feb"; if($month == 3) return "Mar"; if($month == 4) return "Apr"; if($month == 5) return "May"; if($month == 6) return "Jun"; if($month == 7) return "Jul"; if($month == 8) return "Aug"; if($month == 9) return "Sep"; if($month == 10) return "Oct"; if($month == 11) return "Nov"; if($month == 12) return "Dec"; } echo getMonthName(1); // Jan

PHP
View
generate functionMon, 20 Feb 2023

copy text

function copyText() { var copyText = document.getElementById("copyText"); copyText.select(); document.execCommand("copy"); alert("Copied your text: " + copyText.value); }

Javascript
View
generate functionFri, 14 Apr 2023

search in array

function search(array, key){ let index = 0; while(index < array.length){ if(array[index] === key){ return index; } index = index + 1; } return -1; } search([1, 2, 3], 2);

Javascript
View
generate functionFri, 14 Apr 2023

search in array

var names = ["John", "Paul", "George", "Ringo"]; function searchInArray(name) { for (var i = 0; i < names.length; i++) { if (names[i] === name) { return true; } } return false; } searchInArray("John");

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

$pool = new AsyncPool(); for($i = 0; $i < 10; $i++) { $pool->add(function() { $ch = curl_init(); // set url curl_setopt($ch,CURLOPT_URL, "http://www.google.com"); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); // close curl resource to free up system resources curl_close($ch); return $output; }); } $result = $pool->execute(); print_r($result);

PHP
View
regex explanationThu, 23 Mar 2023

[A-Za-z0-9.]{5,}\/?(\?(\w+=\w+&?)*)?

The regex matches with URL's that start with letters and numbers, then followed by at least 5 characters containing letters, numbers and dots(.), then end with an optional slash(/) and optional parameters in the URL.

generate functionThu, 13 Apr 2023

curl asynchrone pool

<?php use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Promise; $client = new Client(); $promises = [ 'baidu' => $client->getAsync('http://www.baidu.com'), 'google' => $client->getAsync('http://www.google.com'), ]; $results = Promise\unwrap($promises); $results['baidu']->getBody(); $results['google']->getBody();

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream http archive

// // usage: curl http://localhost/gzencode.php/foo/bar // // flush gzip buffer to stream $gzip = function($data) { $flush = function() { global $gzip; $data = gzgetc(); if ($data === false) { return false; } echo $data; $gzip->flush(); return true; }; gzwrite($data); return $flush(); }; // setup gzip $gzip = gzopen('php://output', 'wb9'); // flush some data $gzip('foo'); // close stream gzclose($gzip);

PHP
View
generate functionSat, 15 Apr 2023

check proxy

function check_proxy($proxy) { $ch = curl_init(); curl_setopt($ch,CURLOPT_PROXY,$proxy); curl_setopt($ch,CURLOPT_URL,"http://www.google.com"); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $result = curl_exec($ch); $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); if ($http_code>=200 && $http_code<300) { return true; } else { return false; } }

PHP
View
generate functionSat, 07 Jan 2023

gzencode and save archive

function gzencode_and_save($archive_name, $data) { $file_path = $archive_name . '.gz'; $fp = gzopen($file_path, 'w9'); gzwrite($fp, $data); gzclose($fp); return $file_path; }

PHP
View
generate functionMon, 20 Feb 2023

copy to buffer

function copyToBuffer(a, b) { let buffer = []; for (let i = a; i <= b; i++) { buffer.push(i); } return buffer; } copyToBuffer(1, 10)

Javascript
View
generate functionFri, 10 Feb 2023

timeout 10 button active

window.setTimeout(function() { //Put All Your Code Here it Will Execute After some delay Time if (document.getElementById('time_up') != null) document.getElementById('time_up').click(); }, 10000);

Javascript
View
generate functionFri, 14 Apr 2023

pregmatch array in string

function preg_match(str, data){ // check if it is string if(typeof(str) !== 'string'){ console.error('type error, not a string'); return; } // check if it is array if(!Array.isArray(data)){ console.error('type error, not array'); return; } // check if it's a string in array data.forEach(function(item, index){ if(typeof(item) !== 'string'){ console.error('type error, not a string'); return; } }); // check if str match array var flag = 0; data.forEach(function(item, index){ if(str.indexOf(item) !== -1) flag++; }); if(flag == 0) { console.error('no match'); return; }else{ return flag; } } preg_match

Javascript
View
generate functionSat, 15 Apr 2023

get domain with url

function get_domain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } get_domain('http://foo.com/bar'); // returns foo.com

PHP
View
generate functionSat, 04 Feb 2023

ajax post this page

function ajax(url, type){ var xhr = new XMLHttpRequest(); xhr.open(type || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); } ajax('/posts') ajax('/posts', 'POST')

Javascript
View
generate functionThu, 16 Feb 2023

float to 5 symbolds

function float_to_string($float) { $float = strval($float); $float = explode(".", $float); if (count($float) == 1) { $float[1] = "00"; } if (count($float) > 1) { $float[1] = substr($float[1], 0, 2); } $float = $float[0] . "." . $float[1]; return $float; } float_to_string(12.34567) // 12.34

PHP
View
generate functionSat, 07 Jan 2023

return xml gz archive

function generate_sitemap() { //generate sitemap $sitemap = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />'); //add some urls $url = $sitemap->addChild('url'); $url->addChild('loc', 'http://www.url.com'); $url->addChild('lastmod', date('Y-m-d')); $url->addChild('changefreq', 'daily'); $url->addChild('priority', '1.0'); //save to disk $fp = fopen(__DIR__.'/sitemap.xml', 'wb'); fwrite($fp, $sitemap->asXML()); fclose($fp); //return sitemap as a string return $sitemap->asXML(); } ``

PHP
View
generate functionSat, 25 Mar 2023

table to array

var array = []; function pushToArray(element){ array.push(element); } pushToArray(1); pushToArray(2); pushToArray(3); console.log(array);

Javascript
View
generate functionTue, 21 Mar 2023

file to utf8

function convert_to_utf8($filename) { $contents = file_get_contents($filename); $contents = mb_convert_encoding($contents, 'UTF-8'); file_put_contents($filename, $contents); } convert_to_utf8('C:\Users\hch\Desktop\test.txt');

PHP
View
generate functionMon, 17 Apr 2023

Reply Keyboard Markup telegram

$keyboard = [["7", "8", "9"], ["4", "5", "6"], ["1", "2", "3"], ["0"]]; $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => true ]); $response = $telegram->sendMessage([ 'chat_id' => $update->message->chat->id, 'text' => "Hello {$update->message->from->first_name}", 'reply_markup' => $reply_markup ]);

PHP
View
regex explanationThu, 23 Mar 2023

(?=.{5,32}$)(?!.*__)(?!^(telegram|admin|support))[a-z][a-z0-9_]*[a-z0-9]$

(?=.{5,32}$) checks if the length of a username is greater than 5 and less than 32. (?!.*__) checks if the username does not contain two consecutive underscores. (?!^(telegram|admin|support)) checks if the username does not start with "telegram", "admin", or "support". [a-z][a-z0-9_]*[a-z0-9]$ checks if the username only contains lowercase alphanumeric characters and underscores and must begin and end with alphanumeric characters.

generate functionTue, 14 Feb 2023

русские месяцы склонения

function get_month_name($month_number, $case = 'nominative') { $months = array( 'nominative' => array(1 => 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'), 'genitive' => array(1 => 'Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', '

PHP
View
generate functionFri, 14 Apr 2023

test string

function testStr(str){ if(str.length > 10){ return str } else{ return "your string is too short" } } testStr("this is a test string")

Javascript
View
generate functionWed, 08 Feb 2023

$_REQUEST get code status

<?php function get_status_code($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); curl_close($ch); $status = explode(" ", $data); return $status[1]; } ?>

PHP
View
generate functionFri, 17 Feb 2023

fullname month ru

function fullname_month_ru($month_number) { $month_number = intval($month_number); $month_number = ($month_number == 0 ) ? date('n') : $month_number; $month_name = array("", "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"); return $month_name[$month_number]; }

PHP
View
regexFri, 24 Feb 2023

валидация текста в форме

<form action=""> <label for=""> Введите строку: <input type="text" name="str" value=""> </label> <button>Отправить</button> </form> <script> let input = document.querySelector('input'); let form = document.querySelector('form'); form.addEventListener('submit', (e) => { let value = input.value; let patt = /\w+/; if (patt.test(value)) { alert('Все ок'); } else { e.preventDefault(); // останавливаем отправку формы input.style.border = '2px solid red'; alert('Введите строку'); }

generate functionThu, 09 Feb 2023

shuffle string

function shuffle_string($string) { $len = strlen($string); for ($i = 0; $i < $len; $i++) { $pos = rand(0, $len - 1); $temp = $string[$i]; $string[$i] = $string[$pos]; $string[$pos] = $temp; } return $string; }

PHP
View
generate functionThu, 09 Feb 2023

shuffle string

<?php function shuffle($str) { $shuffled = ""; $l = strlen($str); for ($i = 0; $i < $l; $i++) { $ch = substr($str, $i, 1); if ($ch == ' ') continue; $shuffled .= $ch; } $shuffled = str_shuffle($shuffled); $i = 0; $shuffled_str = ''; for ($j = 0; $j < $l; $j++) { $ch = substr($str, $j, 1); if ($ch == ' ') $shuffled_str .= ' '; else $shuffled_str .= $shuffled[$i++]; } return $shuffled_str; } echo shuffle("This is a test"); ?>

PHP
View
generate functionWed, 08 Feb 2023

$_SERVER get code status

<?php function get_status($code) { switch ($code) { case 400: return "Bad Request"; case 403: return "Forbidden"; case 404: return "Not Found"; case 500: return "Internal Server Error"; case 503: return "Service Unavailable"; } } get_status(403); ?>

PHP
View
generate functionTue, 14 Feb 2023

return month text

function month($month) { $months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return $months[$month]; } month(1);

PHP
View
generate functionThu, 09 Feb 2023

разбить строку по 5 символов

function splitStringBy5Char($string) { $result = []; $currentString = ''; for ($i = 0; $i < strlen($string); $i++) { $currentString .= $string[$i]; if (strlen($currentString) >= 5) { $result[] = $currentString; $currentString = ''; } } if ($currentString) $result[] = $currentString; return $result; } print_r(splitStringBy5Char('1234567890'));

PHP
View
generate functionFri, 14 Apr 2023

pregmatch array in string

let languages = "Java, Python, Javascript, C#, C++"; let pattern = /C#|C\+\+|C++/; let result = pattern.test(languages); if(result) { console.log("Yes, it is in the list"); }

Javascript
View
generate functionSun, 19 Mar 2023

get tdl with domain

function get_tdl($domain) { $url = "https://www.whoisxmlapi.com/whoisserver/WhoisService?apiKey=at_n1RvT8WtFZzsE1fKiQ2k3qleoOiE3&domainName=" . $domain . "&outputFormat=json"; $data = file_get_contents($url); return $data; }

PHP
View
generate functionFri, 25 Nov 2022

base64 save to jpg

function base64_to_jpg($base64_string, $output_file) { $ifp = fopen($output_file, "wb"); fwrite($ifp, base64_decode($base64_string)); fclose($ifp); return $output_file; }

PHP
View
generate functionSat, 07 Jan 2023

gzencode and stream download archive

require_once('/path/to/gzencode.php'); function download_send_headers($filename) { // disable caching $now = gmdate("D, d M Y H:i:s"); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("Last-Modified: {$now} GMT"); // force download header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); // disposition / encoding on response body header("Content-Disposition: attachment;filename={$filename}"); header("Content-Transfer-Encoding: binary"); } download_send_headers("data_export_" . date("Y-m-d") . ".csv"); echo gzencode($data); die();

PHP
View
generate functionTue, 14 Feb 2023

русские месяцы склонения

function get_month($month) { $nominative = array("Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"); $accusative = array("Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октября", "Ноября", "Дека

PHP
View
generate functionThu, 01 Dec 2022

map

var map = function(f, l) { var ret = []; for (var i = 0; i < l.length; i++) { ret.push(f(l[i])); } return ret; } // example map(function(x){return x*x;}, [1, 2, 3, 4, 5])

Javascript
View
generate functionThu, 22 Dec 2022

get name day to date

function get_name_day(date){ var d = date.getDate() var m = date.getMonth() var y = date.getFullYear() var name_day = name_day_data[d][m] return name_day } const d = new Date() get_name_day(d)

Javascript
View
generate functionSat, 07 Jan 2023

return xml gz archive

function get_xml_file($name) { $url = 'http://' . $name . '.com/' . $name . '.xml.gz'; $content = file_get_contents($url); $file = download_file($content, $name . '.xml.gz'); return $file; }

PHP
View
generate functionSun, 19 Mar 2023

get tdl with domain

function get_tdl($url) { // strip http:// and www. $tld = preg_replace("/^(https?:\/\/)?(www\.)?/i", "", $url); // strip everything else $tld = preg_replace("/\/.*$/", "", $tld); // extract and return tld $tld = substr($tld, strrpos($tld, ".") + 1); return $tld; }

PHP
View
generate functionWed, 08 Feb 2023

$_SERVER get code status

function get_http_response_code($theURL) { $headers = get_headers($theURL); return substr($headers[0], 9, 3); } get_http_response_code('http://www.example.com');

PHP
View
regexFri, 07 Apr 2023

find url with html

/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/

generate functionTue, 14 Feb 2023

01 to 1

function change01($n): $arr01 = str_split($n); $arr1 = array(); foreach($arr01 as $num){ if($num==0){ $arr1[] = 1; }else{ $arr1[] = 0; } } $r = implode("", $arr1); return $r; change01("0100")

PHP
View
generate functionTue, 21 Mar 2023

convert file to utf8

function file_to_utf8($file) { $contents = file_get_contents($file); $contents = mb_convert_encoding($contents, 'UTF-8', mb_detect_encoding($contents, 'UTF-8, ISO-8859-1', true)); file_put_contents($file, $contents); } file_to_utf8("/path/to/file");

PHP
View
generate functionThu, 06 Apr 2023

get all links

function get_links() { var links = document.getElementsByTagName('a') for (var i = 0; i < links.length; i++) { console.log(links[i].href) } }

Javascript
View
generate functionThu, 06 Apr 2023

get html document

var request = require('request'); var getHtml = url => { var options = { url: url, headers: { 'User-Agent': 'request' } }; request(options, (err, res, body) => { if (err) { return console.log(err); } return body; }); }

Javascript
View
generate functionSun, 19 Mar 2023

get tdl with domain

<?php use GuzzleHttp\Client; $client = new Client(); $url = 'https://www.whoisxmlapi.com/whoisserver/DNSService?apiKey=at_O2QvL3qjzFwfI8O6W0YvY3hc9StL&domainName=google.com&type=_all'; $response = $client->request('GET', $url, [ 'verify' => false ]); $body = $response->getBody(); echo $body; ?>

PHP
View
generate functionTue, 14 Feb 2023

русские месяцы склонения

def month_case(month): if month = 1: return 'января' elif month = 2: return 'февраля' elif month = 3: return 'марта' elif month = 4: return 'апреля' elif month = 5: return 'мая' elif month = 6: return 'июня' elif month = 7: return 'июля' elif month = 8: return 'августа' elif month = 9: return 'сентября' elif month = 10: return 'октября' elif month = 11: return 'ноября' elif month = 12: return 'декабря' else: return

PHP
View
generate functionTue, 14 Feb 2023

return month text

function get_month(num): month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return month[num-1] get_month(1)

PHP
View
generate functionTue, 14 Feb 2023

русские месяцы

function month_ru($month) { $month = $month - 1; $months = ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь']; return $months[$month]; } month_ru(4);

PHP
View
generate functionSat, 07 Jan 2023

gzencode and save archive

<?php function gz_encode_save($path,$file){ $gz = gzencode(file_get_contents($file), 9); $fp = fopen($path, "w"); fwrite($fp, $gz); fclose($fp); } gz_encode_save('yourfile.gz','yourfile.txt'); ?>

PHP
View
generate functionTue, 24 Jan 2023

5 знаков после запятой

function number_format(number, decimals, dec_point, thousands_sep) { // discuss at: http://phpjs.org/functions/number_format/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: davook // improved by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) // improved by: Theriault // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Michael White (http://getsprink.com) // bugfixed by: Benjamin Lupton // bugfixed by: Allan Jensen (http://www.winternet.no) // bugfixed by: Howard Yeend // bugfixed by: Diogo Resende //

Javascript
View
generate functionFri, 25 Nov 2022

base64 save to jpg

$filename = "sample.txt"; // the name of the .txt file which contains the base64 encoded image $handle = fopen($filename, "r"); // file handler $contents = fread($handle, filesize($filename)); // read into $contents fclose($handle); // close file handler $im = imagecreatefromstring(base64_decode($contents)); // imagecreatefromstring creates an image from the string you feed it header('Content-Type: image/jpg'); // header is a function to send an HTTP header, in this case we set the Content-Type to image/jpg imagejpeg($im); // imagejpeg is a function to create a JPG file from the image created by imagecreatefromstring imagedestroy($im); // imagedestroy is a function to destroy the image, and reclaim the memory used by it

PHP
View
generate functionSat, 15 Apr 2023

get domain with url

function get_domain($url) { $pieces = parse_url($url); return isset($pieces['host']) ? $pieces['host'] : ''; } get_domain("https://www.google.com");

PHP
View
generate functionTue, 14 Feb 2023

01 to 1

function binarize($a) { return ($a == 0) ? 0 : 1; } binarize(0); binarize(1); binarize(2); binarize(3); binarize(4);

PHP
View
generate functionThu, 06 Apr 2023

get page html

const getPage = url => new Promise((resolve, reject) => { http.get(url, (res) => { if (res.statusCode === 200) { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => { resolve(data); }); } else { reject(new Error(`Status Code ${res.statusCode}`)); } }).on('error', err => { reject(new Error(err)); }); }); getPage(url).then(body => { console.log(body); }).catch(err => { console.error(err); });

Javascript
View
generate functionTue, 14 Feb 2023

time online

function time(hrs, mins) { let totalMins = hrs * 60 + mins; let totalDays = Math.floor(totalMins / (24*60)); let remainingMins = totalMins % (24*60); let remainingHrs = Math.floor(remainingMins / 60); return `${totalDays} day(s) and ${remainingHrs} hour(s)`; } time(10, 0)

Javascript
View
generate functionThu, 13 Apr 2023

curl asynchrone

curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); $data = curl_exec($curl); curl_close($curl); echo $data;

PHP
View
generate functionFri, 14 Apr 2023

search in array

nums = [1, 2, 3, 4] il = 0 ir = len(nums) - 1 while il <= ir: m = (il + ir) // 2 if target > nums[m]: il = m + 1 elif target < nums[m]: ir = m - 1 else: return m return -1

Javascript
View
generate functionSat, 15 Apr 2023

check proxy

function check_proxy($proxy){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); $curl_scraped_page = curl_exec($ch); curl_close($ch); return $curl_scraped_page; }

PHP
View
generate functionSun, 15 Jan 2023

done function async

function addAsync(a, b, callback) { setTimeout(() => { callback(a + b); }, 1000) } addAsync(1, 2, (result) => { console.log(result); });

Javascript
View
generate functionSat, 25 Mar 2023

table to array

function objToArray(obj){ var newArray =[]; for (var key in obj) { newArray.push(obj[key]); } return newArray; } objToArray({a: 1, b: 2});

Javascript
View
generate functionSat, 25 Mar 2023

table td to array

function tableToArray(table) { var data = []; for (var row = 0; row < table.rows.length; row++) { var tableRow = table.rows[row]; var rowData = {}; for (var col = 0; col < tableRow.cells.length; col++) { rowData[tableRow.cells[col].getAttribute('data-key')] = tableRow.cells[col].innerHTML; } data.push(rowData); } return data; }

Javascript
View
generate functionThu, 06 Apr 2023

get html document

function getHTML(url){ var req = new XMLHttpRequest(); req.open("GET", url, true); req.send(); req.onload = function(){ console.log(req.responseText); } } getHTML("https://google.com");

Javascript
View
generate functionTue, 21 Mar 2023

file to utf8

function readfile2utf8($filename) { $content = file_get_contents($filename); // return mb_convert_encoding($content, 'UTF-8', // mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); return iconv(mb_detect_encoding($content, mb_detect_order(), true), "UTF-8", $content); }

PHP
View
generate functionThu, 13 Apr 2023

curl asynchrone pool

$rand = rand(1, 10); $curl = new \Curl\Curl(); $curl->on('success', function ($instance) { echo 'call to "' . $instance->url . '" was successful.' . "\n"; }); $curl->on('error', function ($instance) { echo 'call to "' . $instance->url . '" was unsuccessful.' . "\n"; echo 'error code: ' . $instance->errorCode . "\n"; echo 'error message: ' . $instance->errorMessage . "\n"; }); $curl->on('complete', function ($instance) { echo 'call to "' . $instance->url . '" completed.' . "\n"; }); for ($i = 1; $i <= $rand; $i++) { $curl->get('http://www.example.com/'); } $curl->start();

PHP
View
generate functionSat, 07 Jan 2023

return xml gz archive

function getXmlGzArchive() { $xml = simplexml_load_file('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml'); $xml = $xml->xpath('//Cube[@currency][@rate]'); $archive = []; foreach ($xml as $node) { $archive[(string)$node['time']][(string)$node['currency']] = (float)$node['rate']; } return $archive; }

PHP
View
generate functionSat, 07 Jan 2023

gzencode and save archive

function gz_archive($file_path, $output_file, $level = 5) { $buffer = ''; $gz = gzopen($output_file, 'wb' . $level); $file = fopen($file_path, 'rb'); while (!feof($file)) { $buffer = fread($file, 10240); gzwrite($gz, $buffer); } gzclose($gz); fclose($file); }

PHP
View
generate functionMon, 17 Apr 2023

Reply Keyboard Markup telegram

$keyboard = [ ['One', 'Two', 'Three'], ['Four', 'Five', 'Six'], ['Seven', 'Eight', 'Nine'], ['🔙'], ]; $reply_markup = $this->telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => true ]); $response = $this->telegram->sendMessage([ 'chat_id' => 'CHAT_ID', 'text' => 'Hello World', 'reply_markup' => $reply_markup ]);

PHP
View
generate functionThu, 01 Dec 2022

find max array

function findMax(arr) { if (arr.length === 0) return 0; var max = arr[0]; for (var i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } findMax([1, 2, 3]);

Javascript
View
generate functionThu, 22 Dec 2022

full month names array

const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; console.log(months);

Javascript
View
generate functionMon, 26 Dec 2022

текущий месяц номер

function getMonthNumber(month){ month = month.toLowerCase(); let months = { "march": 3, "april": 4, "may": 5, "june": 6, "july": 7, "august": 8, "september": 9, "october": 10, "november": 11, "december": 12, "january": 1, "february": 2 } return months[month]; } getMonthNumber("january")

Javascript
View
regexFri, 07 Apr 2023

find url with html

/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/

generate functionMon, 17 Apr 2023

Reply Keyboard Markup telegram

$keyboard = [['text'=>'Функция 1'],['text'=>'Функция 2']]; $reply_markup = $telegram->replyKeyboardMarkup(['keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false, 'selective' => true] ); $response = $telegram->sendMessage([ 'chat_id' => '<CHAT_ID>', 'text' => 'Functions:', 'reply_markup' => $reply_markup ]); $messageId = $response->getMessageId();

PHP
View

Questions about programming?Chat with your personal AI assistant