/ Gists

Gists

On gists

Unique elements

JS oneliners

demo.js #

const getUnique = (arr) => [...new Set(arr)];
// Testing
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr));

On gists

Copy to clipboard

JS oneliners

demo.js #

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");

On gists

Shuffle array

JS oneliners

demo.js #

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
// Testing
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));

On gists

Query with variable in table name

MySql MySql tricks MySql - advanced

example.sql #

SET @newDomainTable := CONCAT('domains_', newDomain);
SET @SQL = CONCAT(
'CREATE TABLE ',@newDomainTable,' (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`domain` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `domain` (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;');
PREPARE sqlcmd from @SQL;
EXECUTE sqlcmd;
DEALLOCATE PREPARE sqlcmd;
END

On gists

FOREIGN KEY CHECKS

MySql

example.sql #

SET FOREIGN_KEY_CHECKS=0;

-- some standard SQL query ...

SET FOREIGN_KEY_CHECKS=1;

On gists

SFTP

PHP Libs

Sftp.php #

<?php
/**
 * Simple FTP Class
 * 
 * @package SFTP
 * @name SFTP
 * @version 1.0
 * @author Shay Anderson 05.11
 * @link shayanderson.com
 * @license http://www.gnu.org/licenses/gpl.html GPL License
 * SFTP is free software and is distributed WITHOUT ANY WARRANTY
 */
final class SFTP {
	/**
	 * FTP host
	 *
	 * @var string $_host
	 */
	private $_host;

	/**
	 * FTP port
	 *
	 * @var int $_port
	 */
	private $_port = 21;

	/**
	 * FTP password
	 *
	 * @var string $_pwd
	 */
	private $_pwd;
	
	/**
	 * FTP stream
	 *
	 * @var resource $_id
	 */
	private $_stream;

	/**
	 * FTP timeout
	 *
	 * @var int $_timeout
	 */
	private $_timeout = 90;

	/**
	 * FTP user
	 *
	 * @var string $_user
	 */
	private $_user;

	/**
	 * Last error
	 *
	 * @var string $error
	 */
	public $error;

	/**
	 * FTP passive mode flag
	 *
	 * @var bool $passive
	 */
	public $passive = false;

	/**
	 * SSL-FTP connection flag
	 *
	 * @var bool $ssl
	 */
	public $ssl = false;

	/**
	 * System type of FTP server
	 *
	 * @var string $system_type
	 */
	public $system_type;

	/**
	 * Initialize connection params
	 *
	 * @param string $host
	 * @param string $user
	 * @param string $password
	 * @param int $port
	 * @param int $timeout (seconds)
	 */
	public function  __construct($host = null, $user = null, $password = null, $port = 21, $timeout = 90) {
		$this->_host = $host;
		$this->_user = $user;
		$this->_pwd = $password;
		$this->_port = (int)$port;
		$this->_timeout = (int)$timeout;
	}

	/**
	 * Auto close connection
	 */
	public function  __destruct() {
		$this->close();
	}

	/**
	 * Change currect directory on FTP server
	 *
	 * @param string $directory
	 * @return bool
	 */
	public function cd($directory = null) {
		// attempt to change directory
		if(ftp_chdir($this->_stream, $directory)) {
			// success
			return true;
		// fail
		} else {
			$this->error = "Failed to change directory to \"{$directory}\"";
			return false;
		}
	}

	/**
	 * Set file permissions
	 *
	 * @param int $permissions (ex: 0644)
	 * @param string $remote_file
	 * @return false
	 */
	public function chmod($permissions = 0, $remote_file = null) {
		// attempt chmod
		if(ftp_chmod($this->_stream, $permissions, $remote_file)) {
			// success
			return true;
		// failed
		} else {
			$this->error = "Failed to set file permissions for \"{$remote_file}\"";
			return false;
		}
	}

	/**
	 * Close FTP connection
	 */
	public function close() {
		// check for valid FTP stream
		if($this->_stream) {
			// close FTP connection
			ftp_close($this->_stream);

			// reset stream
			$this->_stream = false;
		}
	}

	/**
	 * Connect to FTP server
	 *
	 * @return bool
	 */
	public function connect() {
		// check if non-SSL connection
		if(!$this->ssl) {
			// attempt connection
			if(!$this->_stream = ftp_connect($this->_host, $this->_port, $this->_timeout)) {
				// set last error
				$this->error = "Failed to connect to {$this->_host}";
				return false;
			}
		// SSL connection
		} elseif(function_exists("ftp_ssl_connect")) {
			// attempt SSL connection
			if(!$this->_stream = ftp_ssl_connect($this->_host, $this->_port, $this->_timeout)) {
				// set last error
				$this->error = "Failed to connect to {$this->_host} (SSL connection)";
				return false;
			}
		// invalid connection type
		} else {
			$this->error = "Failed to connect to {$this->_host} (invalid connection type)";
			return false;
		}

		// attempt login
		if(ftp_login($this->_stream, $this->_user, $this->_pwd)) {
			// set passive mode
			ftp_pasv($this->_stream, (bool)$this->passive);

			// set system type
			$this->system_type = ftp_systype($this->_stream);

			// connection successful
			return true;
		// login failed
		} else {
			$this->error = "Failed to connect to {$this->_host} (login failed)";
			return false;
		}
	}

	/**
	 * Delete file on FTP server
	 *
	 * @param string $remote_file
	 * @return bool
	 */
	public function delete($remote_file = null) {
		// attempt to delete file
		if(ftp_delete($this->_stream, $remote_file)) {
			// success
			return true;
		// fail
		} else {
			$this->error = "Failed to delete file \"{$remote_file}\"";
			return false;
		}
	}

	/**
	 * Download file from server
	 *
	 * @param string $remote_file
	 * @param string $local_file
	 * @param int $mode
	 * @return bool
	 */
	public function get($remote_file = null, $local_file = null, $mode = FTP_ASCII) {
		// attempt download
		if(ftp_get($this->_stream, $local_file, $remote_file, $mode)) {
			// success
			return true;
		// download failed
		} else {
			$this->error = "Failed to download file \"{$remote_file}\"";
			return false;
		}
	}

	/**
	 * Get list of files/directories in directory
	 *
	 * @param string $directory
	 * @return array
	 */
	public function ls($directory = null) {
		$list = array();

		// attempt to get list
		if($list = ftp_nlist($this->_stream, $directory)) {
			// success
			return $list;
		// fail
		} else {
			$this->error = "Failed to get directory list";
			return array();
		}
	}

	/**
	 * Create directory on FTP server
	 *
	 * @param string $directory
	 * @return bool
	 */
	public function mkdir($directory = null) {
		// attempt to create dir
		if(ftp_mkdir($this->_stream, $directory)) {
			// success
			return true;
		// fail
		} else {
			$this->error = "Failed to create directory \"{$directory}\"";
			return false;
		}
	}

	/**
	 * Upload file to server
	 *
	 * @param string $local_path
	 * @param string $remote_file_path
	 * @param int $mode
	 * @return bool
	 */
	public function put($local_file = null, $remote_file = null, $mode = FTP_ASCII) {
		// attempt to upload file
		if(ftp_put($this->_stream, $remote_file, $local_file, $mode)) {
			// success
			return true;
		// upload failed
		} else {
			$this->error = "Failed to upload file \"{$local_file}\"";
			return false;
		}
	}

	/**
	 * Get current directory
	 *
	 * @return string
	 */
	public function pwd() {
		return ftp_pwd($this->_stream);
	}

	/**
	 * Rename file on FTP server
	 *
	 * @param string $old_name
	 * @param string $new_name
	 * @return bool
	 */
	public function rename($old_name = null, $new_name = null) {
		// attempt rename
		if(ftp_rename($this->_stream, $old_name, $new_name)) {
			// success
			return true;
		// fail
		} else {
			$this->error = "Failed to rename file \"{$old_name}\"";
			return false;
		}
	}

	/**
	 * Remove directory on FTP server
	 *
	 * @param string $directory
	 * @return bool
	 */
	public function rmdir($directory = null) {
		// attempt remove dir
		if(ftp_rmdir($this->_stream, $directory)) {
			// success
			return true;
		// fail
		} else {
			$this->error = "Failed to remove directory \"{$directory}\"";
			return false;
		}
	}


	public function getStream()
	{
		return $this->_stream;
	}

	public function isDir($dir)
	{
		return in_array($dir, ftp_nlist($this->_stream, dirname($dir)));
	}

	public function isFile($file)
	{
		$res = ftp_size($this->_stream, $file);
		
		return $res != -1 ? TRUE : FALSE;
	}
}



On gists

Klogger

PHP Libs

Klogger.php #

<?php
	
	/* Finally, A light, permissions-checking logging class. 
	 * 
	 * Author	: Kenneth Katzgrau < katzgrau@gmail.com >
	 * Date	: July 26, 2008
	 * Comments	: Originally written for use with wpSearch
	 * Website	: http://codefury.net
	 * Version	: 1.0
	 *
	 * Usage: 
	 *		$log = new KLogger ( "log.txt" , KLogger::INFO );
	 *		$log->LogInfo("Returned a million search results");	//Prints to the log file
	 *		$log->LogFATAL("Oh dear.");				//Prints to the log file
	 *		$log->LogDebug("x = 5");					//Prints nothing due to priority setting
	*/
	
	class KLogger
	{
		
		const DEBUG 	= 1;	// Most Verbose
		const INFO 		= 2;	// ...
		const WARN 		= 3;	// ...
		const ERROR 	= 4;	// ...
		const FATAL 	= 5;	// Least Verbose
		const OFF 		= 6;	// Nothing at all.
		
		const LOG_OPEN 		= 1;
		const OPEN_FAILED 	= 2;
		const LOG_CLOSED 	= 3;
		
		/* Public members: Not so much of an example of encapsulation, but that's okay. */
		public $Log_Status 	= KLogger::LOG_CLOSED;
		public $DateFormat	= "Y-m-d G:i:s";
		public $MessageQueue;
	
		private $log_file;
		private $priority = KLogger::INFO;
		
		private $file_handle;
		
		public function __construct( $filepath , $priority )
		{
			if ( $priority == KLogger::OFF ) return;
			
			$this->log_file = $filepath;
			$this->MessageQueue = array();
			$this->priority = $priority;
			
			if ( file_exists( $this->log_file ) )
			{
				if ( !is_writable($this->log_file) )
				{
					$this->Log_Status = KLogger::OPEN_FAILED;
					$this->MessageQueue[] = "The file exists, but could not be opened for writing. Check that appropriate permissions have been set.";
					return;
				}
			}
			
			if ( $this->file_handle = fopen( $this->log_file , "a" ) )
			{
				$this->Log_Status = KLogger::LOG_OPEN;
				$this->MessageQueue[] = "The log file was opened successfully.";
			}
			else
			{
				$this->Log_Status = KLogger::OPEN_FAILED;
				$this->MessageQueue[] = "The file could not be opened. Check permissions.";
			}
			
			return;
		}
		
		public function __destruct()
		{
			if ( $this->file_handle )
				fclose( $this->file_handle );
		}
		
		public function LogInfo($line)
		{
			$this->Log( $line , KLogger::INFO );
		}
		
		public function LogDebug($line)
		{
			$this->Log( $line , KLogger::DEBUG );
		}
		
		public function LogWarn($line)
		{
			$this->Log( $line , KLogger::WARN );	
		}
		
		public function LogError($line)
		{
			$this->Log( $line , KLogger::ERROR );		
		}

		public function LogFatal($line)
		{
			$this->Log( $line , KLogger::FATAL );
		}
		
		public function Log($line, $priority)
		{
			if ( $this->priority <= $priority )
			{
				$status = $this->getTimeLine( $priority );
				$this->WriteFreeFormLine ( "$status $line \n" );
			}
		}
		
		public function WriteFreeFormLine( $line )
		{
			if ( $this->Log_Status == KLogger::LOG_OPEN && $this->priority != KLogger::OFF )
			{

			    if (fwrite( $this->file_handle , $line ) === false) {
			    	
			        $this->MessageQueue[] = "The file could not be written to. Check that appropriate permissions have been set.";
			    }
			}
		}
		
		private function getTimeLine( $level )
		{
			$time = date( $this->DateFormat );
		
			switch( $level )
			{
				case KLogger::INFO:
					return "$time - INFO  -->";
				case KLogger::WARN:
					return "$time - WARN  -->";				
				case KLogger::DEBUG:
					return "$time - DEBUG -->";				
				case KLogger::ERROR:
					return "$time - ERROR -->";
				case KLogger::FATAL:
					return "$time - FATAL -->";
				default:
					return "$time - LOG   -->";
			}
		}
		
	}


On gists

Exchange rates solution (AMI)

PHP Libs PHP

ExchangeRatesFetcher.php #

<?php
/**
 * Abstraktni trida pro stahovani kurzovnich listku ze stranek bank
 *
 * @date 25-02-2008
 * @version 1.0
 *
 */
abstract class ExchangeRatesFetcher
{
	/**
	 * URL, odkud se kurzy stahuji
	 * 
	 * @var string	 	 
	 */
	protected $url;
	
	/**
	 * kod banky 
	 * 
	 * @var string	 	 
	 */
	protected $bank_code;

	/**
	 * seznam kodu men, ktere chceme stahovat
	 * 
	 * @var array
	 */	 	 	 	
	protected $important_currencies = array('CAD', 'DKK', 'EUR', 'GBP', 'HUF', 'CHF', 'JPY', 'NOK', 'PLN', 'SEK', 'SKK', 'USD', 'RON', 'RUB', 'AUD');
	
	/**
	 * pole stazenych hodnot kurzu
	 * 
	 * @var array	 	 
	 */
	protected $exchange_rates = array();
	
	/**
	 * konstruktor - nastaveni vychozich hodnot
	 * 
	 * @param  string  URL, odkud se kurzy stahuji
	 */
	public function __construct($url)
	{
		$this->url = $url;
	}
	
	/**
	 * funkce vraci pole stazenych kurzu (vhodne napr. pro testovaci vypisy)
	 * 
	 * @return array/false pokud nejsou stazene kurzy vraci false, jinak vraci pole stazenych kurzu 
	 */	 	
	public function getExchangeRates()
	{
		if (is_array($this->exchange_rates)) {
			return $this->exchange_rates;
		}
		else {
			return false;
		}
	}

	/**
	 * funkce vraci kod banky
	 * 
	 * @return string 
	 */	 	
	public function getBankCode()
	{
		return $this->bank_code;
	}
	
	/**
	 * Funkce pro stahnuti kurzovniho listku
	 * 	 	
	 * Funkce stahne kurzovni listek a ulozi ho do interni promenne $exchange_rates
	 */	 	  	 	
	abstract public function fetch();
}

On gists

Elo rating

Formulas

elo.php #

<?php

session_start();
//$_SESSION['player_rating'] = 1000; //reset player to default

//get saved player rating
if(isset($_SESSION['player_rating'])){
	$player_rating	= $_SESSION['player_rating'];
} else {
	$player_rating	= 1000;
}
$opponent_rating = rand(0, 2000);	

echo "Player Ranking: ".$player_rating."<br>";
echo "Opponent Ranking: ".$opponent_rating."<br>";

//formula explained - http://forums.steampowered.com/forums/showthread.php?t=1220287
$chance_of_winning = abs((1 / ( 1 + pow(10, ( ($opponent_rating - $player_rating) / 400) ) )) * 100); //percentage
$chance_of_losing = abs(100 - $chance_of_winning); //percentage

//output chances
echo $chance_of_winning."% chance of winning.<br>";
echo $chance_of_losing."% chance of losing.<br>";

//evaluate and output win and lose points
$k_factor = 32; //a common k factor
$win_points = round($k_factor *  ($chance_of_losing/100)); //k_factor * decimal number
$lose_points = round($k_factor * ($chance_of_winning/100)); //k_factor * decimal number
echo '$win_points: '.$win_points.'<br>';
echo '$lose_points: '.$lose_points.'<br>';

//play game - even odds
if($chance_of_winning > 50){
	$player_rating = $player_rating + $win_points;
	echo "<br><strong>Player Wins</strong><br>";	
	echo "Player Earns $win_points points<br>";	
} else {
	$player_rating = $player_rating - $lose_points;
	$player_rating = ($player_rating < 0 ) ? 0 : $player_rating;
	echo "<br><strong>Player Loses</strong><br>";	
	echo "Player Loses $lose_points points<br>";	
}

//record player rating
$_SESSION['player_rating'] = $player_rating;

echo "Player Ranking: " . $player_rating . "<br>";

On gists

Function object with inside small functions

JavaScript-OOP JavaScript

example.js #

var Wrapper = (function () {
	this.A = () => {
		console.log('A');
	}
	this.B = () => {
		console.log('B');
	}
	
	return {
		A2: this.A,
		B2: this.B
	}

	// or return this
})();


Wrapper.B2(); // B