(☞ຈل͜ຈ)☞ Главная  Статьи  Загрузчик Домой

Ok!
Ok!
194
<url>(.*)([^/]+)</loc>(.*)</url>
regexp19010Заменить строки, где loc оканчивается без слэша в файле sitemap.xml
227
const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2); // [2, 4, 6]
map, js19800Метод map в javascript
212
$(document).ready(function(){
        
    let tilDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 5);    
    let tilDay = new Date(tilDate).getDate();
    let monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ];
    

    if($('[field="tn_text_1655377664248"]').length){
    new_text = tilDay + " " + monthNames[tilDate.getMonth()];
    $('[field="tn_text_1655377664248"] span').text(new_text);
    }

});
5 дней, JS20010Добавит 5 дней
223
public function convertImage(&$content)
    {
        if (defined('ADMIN_SECTION') || defined('WIZARD_SITE_ID')) {
            return;
        }

        preg_match_all('/"(/upload/[^"]*.(jpg|jpeg|png))"/i', $content, $matches1);
        self::convertImageToWebp($content, $matches1);
        preg_match_all("/'(/upload/[^']*.(jpg|jpeg|png))'/i", $content, $matches2);
        self::convertImageToWebp($content, $matches2);
    }

    private static function convertImageToWebp(&$content, $matches) {
        if (!empty($matches[1])) {
            foreach ($matches[1] as $i => $imageUrl) {
                $root = $_SERVER['DOCUMENT_ROOT'];
                $type = $matches[2][$i];
                $newName = str_replace($type, 'webp', $imageUrl);
                if (file_exists($root . $newName)) {
                    $content = str_replace($imageUrl, $newName, $content);
                    continue;
                }
                if (!file_exists($root . $imageUrl)) {
                    continue;
                }
                $type = strtolower($type);
                switch ($type) {
                    case 'jpeg':
                    case 'jpg':
                        $img = imagecreatefromjpeg($root . $imageUrl);
                        break;
                    case 'png':
                        $img = imagecreatefrompng($root . $imageUrl);
                        imagepalettetotruecolor($img);
                        imagealphablending($img, true);
                        imagesavealpha($img, true);
                        break;
                }
                if (isset($img)) {
                    $result = imagewebp($img, $root . $newName, 75);
					
					if (!$result) {
						continue;
					}

                    $content = str_replace($imageUrl, $newName, $content);
                    imagedestroy($img);
                    unset($img);
                }
            }
        }
    }
bitrix, webp, convert20030convert image to webp bitrix
210
return ($month === 12 && $day >= 15) || ($month === 1 && $day < 10);
новый год, php20090Вернёт true если новогодние праздники близко
234
pip install Flask
set FLASK_APP=main.py
flask --app main.py run
flask, запустить20090Запустить приложение python flask
80
<mytag>
    <![CDATA[Your text goes here. Btw: 5<6 and 6>5]]>
</mytag>
cdata, xml, wrong tags20300Если заполнение xml параметра выдает текстовую ошибку из-за несовместимого символа, то все символы прячутся в тег CDATA
213
$monthNames = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря" ];
    $tilDate = date("j", strtotime('last day of this month'));
    $tilMonth = date("n", strtotime('last day of this month'));
    $til = $tilDate . " " . $monthNames[$tilMonth - 1];
последний день месяца, php21090Последний день месяца PHP (напр. 31 мая)
219
/**
 * year start count from
 * input @string ('1987')
 * return years since @string
 */
function year_skils($Y) {
  $years = date("Y") - date("Y", strtotime($Y));
  $year_text = ($years%2==0|$years%3==0|$years%4==0)?"года":(($years%10==1&&$years!=11)?"год":"лет");
  return $years . "&nbsp;" . $year_text;
}
php, years, year, лет по-русски23090php сколько лет с тех пор по-русски
211
let worker = {
  slow(min, max) {
    alert(`Called with ${min},${max}`);
    return min + max;
  }
};

function cachingDecorator(func, hash) {
  let cache = new Map();
  return function() {
    let key = hash(arguments); // (*)
    if (cache.has(key)) {
      return cache.get(key);
    }

    let result = func.call(this, ...arguments); // (**)

    cache.set(key, result);
    return result;
  };
}

function hash(args) {
  return args[0] + ',' + args[1];
}

worker.slow = cachingDecorator(worker.slow, hash);

alert( worker.slow(3, 5) ); // работает
alert( "Again " + worker.slow(3, 5) ); // аналогично (из кеша)
caching decorator, js24600Кеширующая js функция
235
$to = '[email protected]'; 
$subject  = 'Сообщение с сайта' . $_SERVER['HTTP_HOST'];
$message = 'Заправлены в планшеты космические карты';


		$headers = 'MIME-Version: 1.0' . "
";
		$headers .= 'Content-type: text/html; charset=utf-8' . "
";
		$headers .= 'To: Admin <' . $to . '>' . "
";
		$headers .= 'From: Site <' . $to . '>' . "
";


mail( $to, $subject, $message, $headers );
mail, php30098Отправить письмо php
186
if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443){
		$protocol = 'https://';
	}else{
		$protocol = 'http://';
	}
	
	$url = $protocol.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	
	$urlend = strrpos($url, '?', -1); // Находим и удаляем все параметры (номер страницы, параметры фильтра и тд.)
	if($urlend != false){
		$url = substr($url, 0, $urlend);
	}
	
	
	if(mb_substr($url, -1) == '/'){ // Тут оставляем, если ссылки на сайте не заканчиваются на /, либо удаляем, если заканчиваются на /.
		$url = substr($url, 0, -1);
	}

    echo '<link rel="canonical" href="'.$url.'"/>';
php, canonical32090php link rel canonical
178
[checkbox* checkbox-41 id:agree-2 class:agree label_first use_label_element "Да"]
согласие, чекбокс34090Чекбокс согласия в contact forms 7
259
function readFileLineByLine($filename) {
    $file = fopen($filename, 'r');
    while (!feof($file)) {
        yield fgets($file);
    }
    fclose($file);
}
foreach (readFileLineByLine('large_file.txt') as $line) {
    echo $line . "<br>";
}
генератор, php40010Генераторы особенно полезны в сценариях обработки больших файлов или потоков данных, например при построчном считывании большого файла
260
Рейтинг рассчитывается по формуле Экслера:
рейтинг = (сумма всех оценок + 31,25) / (число проголосовавших + 10)
рейтинг43590Как считать рейтинг
177
<script type="text/javascript">$(document).ready(function () {
                var div = $("#rec241218811").find(".t-video-lazyload");
                var iframe = div.find('iframe');
                var height = div.width() * 0.5625;
                div.height(height);
                iframe.height(height);
                $('.t223').bind('displayChanged', function () {
                    height = div.width() * 0.5625;
                    div.height(height);
                    iframe.height(height);
                });
                $(window).bind('scroll', t_throttle(function () {
                    height = div.width() * 0.5625;
                    div.height(height);
                    iframe.height(height);
                }, 200));
            });</script>
lazyload, youtube90890Лэйзилоуд для ютьюб роликов на страницу
162
li:not(:last-child):not(:first-child)
ни первый ни послеадний, css 100200ни первый ни послеадний из скписка
226
var player = {score: 1, name: 'Jeff'};
var newPlayer = Object.assign({}, player, {score: 2}); 
// or var newPlayer = {...player, score: 2};

create new object, js100300Создать новый объект из старого в Javascript
224
&#8381;
рубль, html100500символ рубля в html
176
В htaccess добавить 
<IfModule mod_headers.c>
  <FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>
cors, allow origin100600No Access-Control-Allow-Origin header при подключении шрифтов
1 2 3 4 5 6 7 8 9 10 11 12 13 14