Code Snippets Library

A collection of useful code snippets and solutions

This snippet creates a pagination UI using Smarty templating syntax. It displays previous/next links, highlights the current page, and adds ellipsis if there are many pages.

                    <div class="row">
  {if isset($pages) && $pages>1}
    <nav style=" text-align: center; ">
      <ul class="pagination">
        {if ((int)$page+1)-1 > 0}<li class="page-item"><a class="page-link" href="?pagina={$page-1}">← <span>Precedente</span></a></li>{/if}

        {assign var="foo" value=1}
        {for $foo=max(1, $page-5) to min($pages, $page+5)}
          <li class="page-item {if ($foo-1)==(int)$page}active{/if}"><a class="page-link" href="?pagina={$foo-1}">{$foo}</a></li>
        {/for}

        {if $foo<($pages)}
          <li class="page-item"><a class="page-link disabled" href="#">...</a></li>
          <li class="page-item"><a class="page-link" href="?pagina={$pages-1}">{$pages}</a></li>
        {/if}

        {if ((int)$page+1)+1 <= $pages}<li class="page-item"><a class="page-link" href="?pagina={(int)$page+1}"><span>Successivo</span> → </a></li>{/if}
      </ul>
    </nav>
  {/if}
</div>
                  

This PHP function calculates the distance between two geographical coordinates using the Haversine formula and supports kilometers, nautical miles, and miles.

                    function distance_between_two_points($lat1, $lon1, $lat2, $lon2, $unit) {
  if (($lat1 == $lat2) && ($lon1 == $lon2)) {
    return 0;
  }
  else {
    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
      return ($miles * 1.609344);
    } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
      return $miles;
    }
  }
}
                  

This command generates a tree-like structure of directories using `ls`, `grep`, and `sed`, visually representing folder hierarchy in the terminal.

                    ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*/--/g' -e 's/^/   /' -e 's/-/|/'
                  

This command displays the size of each folder (in kilobytes by default) within the current directory, limited to one level deep.

                    du --max-depth=1 -hx
                  

This script kills all processes matching the name 'stats_snapshot' using `pkill`, and then checks if any matching processes are still running using `ps` and `grep`.

                    pkill -f 'stats_snapshot'
ps -aux | grep 'stats_snapshot'
                  

This command removes carriage return (`\r`) characters from a file (typically from Windows-formatted files) and writes the cleaned content to a new file. Useful when converting Windows line endings to Unix format.

                    sed 's/\r$//' docker/docker-compose.yml > docker/docker-compose2.yml
                  

This command recursively searches for files that contain a specific word ('article' in this case) and lists their paths. It's useful for quickly locating where a word appears in a codebase or document directory.

                    grep -rln article
                  

This PHP snippet checks if a 'query' parameter is present in the request and initializes a search criteria array using the `$or` operator. This setup allows for flexible querying across multiple fields and can be extended to support special characters or advanced search patterns.

                    if(!empty($_REQUEST['query'])){
			$criteria['$or'] = [];
			$testRegex = $_REQUEST['query'];
			$diacriticMap = [
				'A'=>'AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ',
				'AA'=>'Ꜳ',
				'AE'=>'ÆǼǢ',
				'AO'=>'Ꜵ',
				'AU'=>'Ꜷ',
				'AV'=>'ꜸꜺ',
				'AY'=>'Ꜽ',
				'B'=>'BⒷBḂḄḆɃƂƁ',
				'C'=>'CⒸCĆĈĊČÇḈƇȻꜾ',
				'D'=>'DⒹDḊĎḌḐḒḎĐƋƊƉꝹ',
				'DZ'=>'DZDŽ',
				'Dz'=>'DzDž',
				'E'=>'EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ',
				'F'=>'FⒻFḞƑꝻ',
				'G'=>'GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ',
				'H'=>'HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ',
				'I'=>'IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ',
				'J'=>'JⒿJĴɈ',
				'K'=>'KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ',
				'L'=>'LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ',
				'LJ'=>'LJ',
				'Lj'=>'Lj',
				'M'=>'MⓂMḾṀṂⱮƜ',
				'N'=>'NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ',
				'NJ'=>'NJ',
				'Nj'=>'Nj',
				'O'=>'OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ',
				'OI'=>'Ƣ',
				'OO'=>'Ꝏ',
				'OU'=>'Ȣ',
				'P'=>'PⓅPṔṖƤⱣꝐꝒꝔ',
				'Q'=>'QⓆQꝖꝘɊ',
				'R'=>'RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ',
				'S'=>'SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ',
				'T'=>'TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ',
				'TZ'=>'Ꜩ',
				'U'=>'UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ',
				'V'=>'VⓋVṼṾƲꝞɅ',
				'VY'=>'Ꝡ',
				'W'=>'WⓌWẀẂŴẆẄẈⱲ',
				'X'=>'XⓍXẊẌ',
				'Y'=>'YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ',
				'Z'=>'ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ',
				'a'=>'aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ',
				'aa'=>'ꜳ',
				'ae'=>'æǽǣ',
				'ao'=>'ꜵ',
				'au'=>'ꜷ',
				'av'=>'ꜹꜻ',
				'ay'=>'ꜽ',
				'b'=>'bⓑbḃḅḇƀƃɓ',
				'c'=>'cⓒcćĉċčçḉƈȼꜿↄ',
				'd'=>'dⓓdḋďḍḑḓḏđƌɖɗꝺ',
				'dz'=>'dzdž',
				'e'=>'eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ',
				'f'=>'fⓕfḟƒꝼ',
				'g'=>'gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ',
				'h'=>'hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ',
				'hv'=>'ƕ',
				'i'=>'iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı',
				'j'=>'jⓙjĵǰɉ',
				'k'=>'kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ',
				'l'=>'lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ',
				'lj'=>'lj',
				'm'=>'mⓜmḿṁṃɱɯ',
				'n'=>'nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ',
				'nj'=>'nj',
				'o'=>'oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ',
				'oi'=>'ƣ',
				'ou'=>'ȣ',
				'oo'=>'ꝏ',
				'p'=>'pⓟpṕṗƥᵽꝑꝓꝕ',
				'q'=>'qⓠqɋꝗꝙ',
				'r'=>'rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ',
				's'=>'sⓢsßśṥŝṡšṧṣṩșşȿꞩꞅẛ',
				't'=>'tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ',
				'tz'=>'ꜩ',
				'u'=>'uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ',
				'v'=>'vⓥvṽṿʋꝟʌ',
				'vy'=>'ꝡ',
				'w'=>'wⓦwẁẃŵẇẅẘẉⱳ',
				'x'=>'xⓧxẋẍ',
				'y'=>'yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ',
				'z'=>'zⓩzźẑżžẓẕƶȥɀⱬꝣ'
			];
			foreach($diacriticMap as $kk=>$vv){
				$testRegex = str_replace($kk,"[$vv]",$testRegex);
			}
			/*print_r($testRegex);
			exit;*/
			$criteria['$or'][0]['email'] = new MongoRegex($_REQUEST['query'],'i');
			$criteria['$or'][1]['name'] = new MongoRegex($testRegex,'i');
			$criteria['$or'][2]['surname'] = new MongoRegex($testRegex,'i');
                  

This Docker command clears the log file of a running container (e.g., `photoprism`) by redirecting an empty input (`:`) to the log path retrieved via `docker inspect`. It's a quick way to reduce disk usage without stopping the container, but use with caution to avoid losing important logs.

                    : > $(docker inspect --format='{{.LogPath}}' photoprism)
                  

This command forcefully terminates all running processes with a specific name—in this case, `rsync`—using `kill -9` and `pidof`. It's useful for stopping multiple instances at once, but `-9` sends SIGKILL, which immediately stops the process without cleanup, so use it carefully.

                    kill -9 $(pidof rsync)
                  

This command uses `du` to calculate the disk usage of items in the current directory (non-recursively), displaying sizes in megabytes. It then pipes the output to `sort` to list them in descending order by size. Useful for identifying space hogs.

                    du --max-depth=1 -h -BM | sort -hr
                  

This command inspects a Docker container and filters the output using `grep` to show the `working_dir` label. It tells you the directory on the host machine from which the container was launched. Useful for debugging container origins in Docker Compose setups.

                    docker inspect nginxphpfpm | grep "com.docker.compose.project.working_dir"
                  

This Bash script automates the process of creating a monorepo by combining multiple existing repositories. It creates a main directory, initializes Git, clones each repo, moves contents into separate subfolders, renames tags, merges everything into the monorepo while preserving Git history, and updates a README with links to each merged repo.

                    #!/bin/bash

# List of repository names (update with actual repository names)
repos=("repo-1" "repo-2" "repo-3" "repo-4" "repo-5" "repo-6" "repo-7" "repo-8" "repo-9" "repo-11" "repo-12" "repo-13" "repo-14" "repo-15" "repo-16" "repo-17" "repo-18" "repo-19" "repo-20" "repo-21" "repo-22" "repo-23" "repo-24" "repo-25" "repo-26" "repo-27")

# Step 1: Create the monorepo
mkdir monorepo
cd monorepo
git init

echo "# Monorepo" > README.md
echo -e "\n## Included Repositories\n" >> README.md
git add README.md
git commit -m "Initial commit with README.md structure"

cd ..
mkdir repos

# Step 2: Clone each repo, move files into its own folder, and rename tags
for reponame in "${repos[@]}"; do
    cd repos
    git clone https://github.com/yourgithubaccount/$reponame.git
    cd $reponame
    mkdir -p $reponame
    find . -maxdepth 1 ! -name .git ! -name . -exec mv {} $reponame/ \;
    git add .
    git commit -m "Moved repo content into folder $reponame"
    git tag -l | xargs -I {} git tag "$reponame-{}"
    cd ..
    cd ..
done

# Step 3: Add each repository as a remote, merge into the monorepo, and update README.md
cd monorepo
count=1
for reponame in "${repos[@]}"; do
    git remote add -f $reponame ../repos/$reponame
    git merge $reponame/master --allow-unrelated-histories --no-edit
    echo "$count. [$reponame](./$reponame)" >> README.md
    ((count++))
done

git add README.md
git commit -m "Updated README.md with links to merged repositories"