SEEyp

SEEyp is a free collection of code snippets (PHP, Java, JavaScript, CSS) and useful tool (you can easily build up your personal collection of code snippet). Free for personal and commercial use.

Download (version 14.6.22) Screenshot Readme (RU)

Disclaimer

The www.kalinin84.info and all contents of the www.kalinin84.info are provided on an "as is" basis without warranties of any kind, either expressed or implied, including without limitation warranties of title or implied warranties of merchantability or fitness for a particular purpose.

GIT (new branch)

git status
git checkout master
git fetch
git pull
git reset --hard origin/master
git checkout -b ID0001

GIT (commit and merge)

git status
git add .
git commit -a -m "About ..."
git fetch
git merge origin/master

GIT (diff and push)

git diff --color-words origin/master
git push origin ID0001

robots.txt

User-Agent: *
Disallow:
Allow: /
Host: www.localhost.localhost
Sitemap: http://www.localhost.localhost/sitemap.xml

.htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^http://test\.test/$ [NC]
RewriteRule ^(.*)$ http://www.test.test/$1 [R=301,L]

ErrorDocument 404 http://www.test.test/
ErrorDocument 403 http://www.test.test/
ErrorDocument 401 http://www.test.test/
ErrorDocument 500 http://www.test.test/

sitemap.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
	http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
	
	<url>
		<loc>http://www.localhost.localhost/</loc>
		<lastmod>2014-02-16T07:57:39+00:00</lastmod>
		<priority>1.00</priority>
	</url>
	
</urlset>

MySQL (Table definition)

CREATE TABLE `site_content` (
	`id` INT(11) NOT NULL AUTO_INCREMENT, 
	`alias` VARCHAR(150) NOT NULL, 
	`title` VARCHAR(200) NOT NULL, 
	`h1` VARCHAR(200) NOT NULL, 
	`content` MEDIUMTEXT, 
	`user_id` INT(11) NOT NULL, 
	`info_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
	PRIMARY KEY (`id`),
	UNIQUE KEY `id` (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

PHP (PDO, singleton)

/**
 * @author Kalinin Alexandr
 * @see http://www.kalinin84.info/
 * @since 2008-01-05 19:10:00 (last modify: 2014-03-05 21:34:12)
 */
class SingletonPDOExample {

	private static $_instance;
	private $_pdo;
	private $_conf = array("mysql:host=localhost;dbname=t1;charset=utf8", "root", "");
	private $_prm = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

	/**
	* Constructor
	*/
	private function __construct() {
	
		$this->_pdo = new PDO($this->_conf[0], $this->_conf[1], $this->_conf[2], $this->_prm);
	}
	
	/**
	* Singleton
	*/
	private function __clone() {}
	private function __wakeup() {} 
	public static function getInstance() {
	
		if (self::$_instance === null) {
		
			self::$_instance = new self;  
		}
 
		return self::$_instance;
	}
	
	/**
	* Get connection
	*/
	public function getConnection() {

		return $this->_pdo;
	}
}

PHP (CRUD)

/**
* DELETE
*/
public function deleteEvent($id) {

	$stm = $this->_pdo->prepare("DELETE FROM `events` WHERE id = ?;");
	$stm->bindParam(1, $id, PDO::PARAM_INT);
	$stm->execute();
}

/**
* FIND
*/
public function findEvent($id) {

	$stm = $this->_pdo->prepare("SELECT * FROM `events` WHERE id = ?;");
	$stm->bindParam(1, $id, PDO::PARAM_INT);
	$stm->execute();

	return $stm->fetchAll();
}

/**
* UPDATE
*/
public function updateEvent($id, $name, $value) {

	$stm = $this->_pdo->prepare("UPDATE `events` SET `name`= ?, `value`= ? WHERE `id` = ?;");
	$stm->bindParam(1, $name, PDO::PARAM_STR);
	$stm->bindParam(2, $value, PDO::PARAM_STR);
	$stm->bindParam(3, $id, PDO::PARAM_INT);
	$stm->execute();
}

/**
* INSERT
*/
public function insertEvent($name, $value) {

	$stm = $this->_pdo->prepare("INSERT INTO `events` (`name`, `value`) VALUES (?, ?);");
	$stm->bindParam(1, $name, PDO::PARAM_STR);
	$stm->bindParam(2, $value, PDO::PARAM_STR);
	$stm->execute();
}

WordPress (plugin)

// \wordpress\wp-content\plugins\kalinin\test.php
<?php

/*
Plugin Name: 1
Plugin URI: 2
Description: 3
Author: 4
Version: 5
Author URI: 6
*/

class ExampleWP {

	private static $_instance;

	/**
	* Singleton
	*/
	private function __clone() {}
	private function __wakeup() {} 
	private function __construct() {}
	public static function getInstance() {
	
		if (self::$_instance === null) {
		
			self::$_instance = new self;  
		}
 
		return self::$_instance;
	}
	
	/**
	* Example
	*/
	public function getInfo($content) {

		return $content . '<hr>Example!';
	}
}

add_filter('the_content', array( ExampleWP::getInstance(), 'getInfo' ));


add_filter('the_title', function($title) use ($wpdb) { 

	$sql = "SELECT `name` FROM `wp_terms` WHERE `term_id` = %d";
	$stm = $wpdb->prepare($sql, 1);
	$result = $wpdb->get_var($stm);

	return str_replace('123', $result, $title);
});

WordPress (theme)

// \wordpress\wp-content\themes\kalinin\style.css
body { padding: 50px; margin: 0; border-left: 10px solid #bebebe; }


// \wordpress\wp-content\themes\kalinin\index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
<title><?php bloginfo('name'); ?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
</head>
<body>
	<div class="content">
	<h1><?php the_title(); ?></h1>
	
	<?php while ( have_posts() ) : the_post() ?>
	<?php the_content(); ?>
	<?php endwhile; ?>
	
	<hr />
	
	<ul >
		<?php wp_list_pages(array('title_li' => '')); ?>
	</ul>

	</div>
</body>
</html>

Drupal (module)

/**
* \drupal-7.27\sites\all\modules\kalinin\kalinin.info
*/
name = Test
description = By Kalinin
core = 7.x


/**
* \drupal-7.27\sites\all\modules\kalinin\kalinin.module
*/
<?php

function helloDrupal($id) { 

	return db_query('SELECT title FROM {node} WHERE nid = :id', array(':id' => $id))->fetchField();
};

Drupal (theme)

/**
* \drupal-7.27\sites\all\themes\kalinin\kalinin.info
*/
name = Test
description = by Kalinin
core = 7.x
stylesheets[all][] = css/test.css


/**
* \drupal-7.27\sites\all\themes\kalinin\page.tpl.php
*/
<?php 

if($is_admin) {

	var_export(helloDrupal(1));
}

print $title;

print render($page['content']); 

print render($page['user_menu']);

print render($page['main_menu']);

?>

PHP (Slim, microframework, Medoo, database framework)

// CONFIG

require_once 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();
$app->config('debug', true);
$app->config(['templates.path' => './']);

require_once 'medoo.min.php';

$medooConfig = [
	'database_type' => 'mysql',
	'database_name' => 't1',
	'server' => 'localhost',
	'username' => 'root',
	'password' => '',
	'charset' => 'utf8',
];

$database = new medoo($medooConfig);


// MODEL

class Example {
	private $_database;
	
	public function __construct($_database) {
	
		$this->_database = $_database;
	}
	
	public function getContentByAlias($alias) {
	
		$data = ["title", "h1", "content"];
		return $this->_database->get("pages", $data, ["alias" => $alias]);
	}
}


// CONTROLLER

$app->get('/sasha/:alias', function ($alias) use ($app, $database) {

	$model = new Example($database);
	$content = $model->getContentByAlias($alias);
	
	if(empty($content)) {
	
		header('Location: http://127.0.0.1:8098/1/');
		exit();
	}

	$app->render('test.php', $content);
});

$app->notFound(function () use ($app) {

	$app->render('404.html');
});

$app->run();

PHP (Flight, microframework)

<?php

// MODEL
class foo {
	private $_pdo;
	
	public function __construct($_pdo) {
	
		$this->_pdo = $_pdo;
	}
	
	public function alias($alias) {
	
		$stm = $this->_pdo->prepare("SELECT * FROM `site_contents` WHERE alias = ? LIMIT 1;");
		$stm->bindParam(1, $alias, PDO::PARAM_STR);
		$stm->execute();
	
		return $stm->fetch();
	}
}


// CONFIG 
require_once 'flight/Flight.php';

Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=t1','root',''));
$db = Flight::db();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Flight::register('model', 'foo', array($db));
$model = Flight::model();


// CONTROLLER
Flight::route('/portal/@alias', function($alias) use ($model) {
	
	$content = $model->alias($alias);
	
	if(empty($content)) {
	
		Flight::redirect('http://127.0.0.1:8098/1/portal/1');
	}

	Flight::render('test.php', $content);
});

Flight::map('notFound', function() {

	Flight::redirect('http://127.0.0.1:8098/1/portal/1');
});

Flight::start();

PHP (Silex, Smarty, template engine, microframework)

require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../libs/Smarty.class.php';

$model = new SilexExample();

$app = new Silex\Application();
$app['debug'] = true;

$smarty = new Smarty;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;


$app->get('/my-simple-site/{alias}', function ($alias) use ($model, $smarty) {

	$output = var_export($model->findEvent($alias), true);
	$smarty->assign("test", $output);
	
	return $smarty->fetch('index.tpl');
});

$app->run();

PHP (Silex, Twig, template engine, microframework)

require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app['debug'] = true;
$appConf = ['twig.path' => __DIR__.'/views'];
$app->register(new Silex\Provider\TwigServiceProvider(), $appConf);


$app->get('/site/{alias}', function ($alias) use ($app) {

	return $app['twig']->render('hello.twig', ['test' => $alias]);
});

$app->run();

Yii 2.0 Beta (Model)

namespace app\models;

use Yii;

class Portal extends \yii\db\ActiveRecord
{
	/**
	* @inheritdoc
	*/
	public static function tableName()
	{
		return 'site_content';
	}
}

Yii 2.0 Beta (Controller)

namespace app\controllers;

use Yii;
use app\models\Portal;
use yii\web\NotFoundHttpException;

class NewController extends \yii\web\Controller
{
	public function actionIndex()
	{
		// only for example!
		$alias = Yii::$app->request->get('alias');
		
		if(empty($alias))
		{
			throw new NotFoundHttpException();
		}

		$page = Portal::find()->where(['alias' => $alias])->one();
		
		if (!$page) 
		{
			throw new NotFoundHttpException();
		}
		
		return $this->render('view', ['page' => $page]);
	}
}

CakePHP (add TinyMCE)

<script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script>
        tinymce.init({selector:'#SiteContentContent'});
</script>
<div class="siteContents form">
<?php echo $this->Form->create('SiteContent'); ?>
	<fieldset>
		<legend><?php echo __('Edit Site Content'); ?></legend>
	<?php
		echo $this->Form->input('id');
		echo $this->Form->input('alias');
		echo $this->Form->input('title');
		echo $this->Form->input('content');
	?>
	</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
	<h3><?php echo __('Actions'); ?></h3>
	<ul>

		<li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('SiteContent.id')), array(), __('Are you sure you want to delete # %s?', $this->Form->value('SiteContent.id'))); ?></li>
		<li><?php echo $this->Html->link(__('List Site Contents'), array('action' => 'index')); ?></li>
	</ul>
</div>

PHP (Logger)

	public function logFile($file, $log) {
	
		$now = date("Y-m-d H:i:s");  
		$logData = "[{$now}] {$log}\n";
	
		file_put_contents($file, $logData, FILE_APPEND | LOCK_EX);
	}

PHP (curl)

	public function getContentByURL($url) {

		$curl = curl_init();

		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($curl, CURLOPT_AUTOREFERER, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_URL, $url);

		$siteContent = curl_exec($curl);
		
		curl_close($curl);

		return $siteContent;
	}

PHP (XML)

$result = simplexml_load_string($xml);
var_dump($result);

PHP (DOM, XML)

$xmlDoc = new DOMDocument();

$xmlDoc->load("file.xml");
$xml = $xmlDoc->documentElement;

foreach ($xml->childNodes AS $item) {

	echo $item->nodeValue . "\n\n";
}

PHP (Controller)

$showStaticPage = function($url, $view) {

	if($_SERVER['REQUEST_URI'] == $url) {
	
		echo file_get_contents($view);
		exit();
	}
};

$showStaticPage('/web/1', '1.html');
$showStaticPage('/web/2', '2.html');

PHP (Controller)

require_once 'db/SingletonPDOExample.php';

$content = array();

if (isset($_GET['alias'])) {

	$content = SingletonPDOExample::getInstance()->getContentByAlias($_GET['alias']);
} 

if(empty($content)) {
	
	header('Location: http://localhost/');
	exit();
}

var_dump($content);

PHP (translit)

$ru = ["А"=>"a","Б"=>"b","В"=>"v","Г"=>"g","Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
	"Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n","О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
	"У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch","Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
	"Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b","в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
	"з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l","м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
	"с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h","ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
	"ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"," "=>"-","*"=>"-","."=>"","/"=>""];

$translitUrl = function($in) use ($ru) { 

	return preg_replace('/[^A-Za-z0-9_\-]/', '', strtr($in, $ru));
};

echo $translitUrl('Уникальных ситуаций нет. Уникальных людей нет. Все проблемы очень типичны.');

PHP (dump)

$dump = function($data) { 

	echo '<pre>';
	var_dump($data);
	exit();
};

PHP (Search, list, file)

	public function findInList($file, $obj) {
	
		$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
		
		if (in_array($obj, $lines)) {
		
			return $obj;
		} else {
		
			return false;
		}
	}

PHP (Search, file, CSV)

	public function findInCsvFile($file, $obj, $dlm) {
	
		$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
		$result = array();
		
		foreach($lines AS $val) {
		
			if(stristr($val, $obj)) {
			
				$result[] = explode($dlm, $val);
			}
		}
		
		return $result;
	}

PHP (validate, url)

if(!filter_var($data['url'], FILTER_VALIDATE_URL)) {
	exit('AJAX=ERROR=FILTER=url');
}

PHP (validate, email)

	// if(!filter_var($email, FILTER_VALIDATE_EMAIL)) 
	
	public function validateEmail($email) {

		$result = false;
		$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'; 

		if (preg_match($regex, $email)) {
		
			$result = true;
		}
		
		return $result;
	}

PHP (validate, letters)

	public function validateOnlyLetters($str) {
	
		$result = false;
		$regex = '/^[a-zA-Z ]*$/'; 

		if (preg_match($regex, $str)) {
		
			$result = true;
		}
		
		return $result;
	}

PHP (validate, number)

	// if(!filter_var($number, FILTER_VALIDATE_INT))
	
	public function validateOnlyNumber($number) {
	
		$result = false;
		$regex = '/^[0-9]+$/'; 

		if (preg_match($regex, $number)) {
		
			$result = true;
		}
		
		return $result;
	}

PHP (upload file)

<?php

$result = '';

if(isset($_POST['run'])) {

	if(!preg_match('/^[a-z0-9-]+\.(jpe?g|png|csv|pdf|zip|gif)$/', basename($_FILES['file']['name']))) {
		$result = "Error! #0017";
	} else {
	
		if(!move_uploaded_file($_FILES['file']['tmp_name'], './' . basename($_FILES['file']['name']))) {
			$result = "Error! #0014";
		} else {
			$result = "OK! --- (Size: " . $_FILES['file']['size'] . ")";
		}
	}
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload</title>
</head>
<body>	
<form method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="hidden" name="run" value="1">
	<button type="submit">Upload</button>
	<h3><?= $result; ?></h3>
</form>
</body>
</html>

PHP (PDF)

require('fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();

$pdf->SetFont('Arial','B',32);
$pdf->Cell(50,20,'REPORT');

$pdf->Output();

PHP (Test)

class SimpleTest {
	
	/**
	* Singleton
	*/
	private static $_instance;
	private function __clone() {}
	private function __wakeup() {} 
	private function __construct() {}
	public static function getInstance() {
		if (self::$_instance === null) {
			self::$_instance = new self;  
		}
		return self::$_instance;
	}
	
	/**
	* Scanner
	*/
	public function scann($url) {
		if (false !== ($content = @file_get_contents($url))) {
			$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
			if(preg_match_all("/$regexp/siU", $content, $matches)) {
				return $matches[2];
			}
		} else {
			echo "[ERROR!!!] = {$url} <br />";
			exit();
		}
	}
	
	/**
	* Test
	*/
	public function test($url) {
		$start = microtime(true);
		if (false !== ($content = @file_get_contents($url))) {
			$len = strlen($content);
			$md5 = md5($content);
		} else {
			return "[ERROR!!!] = {$url} <br />";
		}
		$time = microtime(true) - $start;
		return "{$time} = {$len} = {$md5} = {$url} <br />";
	}
	
	/**
	* Controller
	*/
	public function run($url) {
		foreach($this->scann($url) AS $link) {
			if($link != "#") {
				if(stristr($link, "http:")) {
					echo $this->test($link) . "<br/>";
				} else {
					echo $this->test($url.$link) . "<br/>";
				}
			}
		}
	}
}

SimpleTest::getInstance()->run('http://127.0.0.1:8098/');

JavaScript (JQuery, AJAX, POST)

$(document).ready(function() {

	$("#button_id").click(function() {
	
		$.post('api.php', $('#form_id').serialize(true)).done(function(data) {
			
			$('#result_id').html(data);
		}).fail(function() {
		
			$('#result_id').html("Error message...");
		});
	});
});

JavaScript (foreach)

function nextAlert(element, index, array) {

	alert(element);
}

['One', 'Two'].forEach(nextAlert);

JavaScript (DOM, JSON, XHTML forms)

var auth = {

	login: {
		id: 'auth_login',
		value: 'Sasha'
	},
	
	password: {
		id: 'auth_password',
		value: 'admin'
	}
};

document.getElementById(auth.login.id).value = auth.login.value;
document.getElementById(auth.password.id).value = auth.password.value;

XHTML, CSS (Document)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
<title>Document</title>
<style type="text/css">
html { 

	margin: 0; 
	padding: 0; 
	border: 0; 
}  

body { 

	margin: 0; 
	padding: 60px 0 30px 0; 
	height: 100%;
	background-color: #bebebe;
	background: linear-gradient(to left, #8C8C8C 0%, #F0F0F0 100%);
	font-family: Arial,Verdana,sans-serif; 
}

a { 

	color: #003399; 
}  

h1 { 

	font-size: 36pt; 
	font-weight: 100; 
	color: #000; 
	margin: 5px; 
	padding: 2px; 
} 

h2 { 

	font-size: 12pt; 
	font-weight: 100; 
	color: #000; 
	margin: 5px; 
	padding: 2px; 
} 

h3 { 

	font-size: 18pt; 
	font-weight: 100; 
	color: #000; 
	margin: 30px 5px 5px 5px; 
	padding: 2px; 
} 

p { 

	font-size: 10pt; 
	line-height: 190%; 
	color: #333333; 
	margin: 5px 5px 5px 45px;  
	padding: 2px;
}

em { 

	font-size: 12pt; 
	line-height: 190%; 
	color: #177245; 
	margin: 0;  
	padding: 2px;
}

pre { 

	font-size: 10pt; 
	line-height: 150%; 
	color: #0d1140; 
	background-color: #f5f8e7;
	margin: 5px 5px 5px 45px;
	padding: 20px;
	font-family: Arial,Verdana,sans-serif; 
	-moz-border-radius: 18px;
	-webkit-border-radius: 18px;
	border-radius: 18px; 
	border-left: 5px solid #aac23c; 
}

.content {

	width: 800px; 
	margin: 0 auto; 
	padding: 30px; 
	background-color: #fff;
	-webkit-box-shadow:0 1px 7px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
	-moz-box-shadow:0 1px 7px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
	box-shadow:0 1px 7px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
	-moz-border-radius: 6px;
	-webkit-border-radius: 6px;
	border-radius: 6px; 
}
</style>
</head>
<body>
	<div class="content"> 

	</div>
</body>
</html>

jQuery Mobile (Report, login form)

<?php

$user = ['login' => 'admin', 'password' => '123456'];

$is_admin = false;
$error = false;

if(isset($_POST['login']) && isset($_POST['password'])) {

	if($_POST['login'] == $user['login'] && $_POST['password'] == $user['password']) {
	
		$is_admin = true;
	} else {
	
		$error = true;
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
<title>Document</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<div data-role="header">
    <h1>Page Title</h1>
</div>

<?php if($is_admin) { ?>

<div style="width: 1000px; margin: 0 auto;"> 
	<div data-role="collapsible" data-collapsed="false">
		<h4>Heading</h4>
		<p>Text ...</p>
	</div>
</div>

<?php } else { ?>

<div style="width: 500px; margin: 0 auto;"> 
	<div data-role="collapsible" data-collapsed="false">
		<h4>Login</h4>
		<form action="login.php" method="POST">
		<label for="login">Login:</label>
		<input name="login" id="text-basic" pattern="[a-z]*" value="" type="text">
		
		<label for="password">Password:</label>
		<input name="password" id="password" value="" autocomplete="off" type="password">
		
		<?php if($error) { ?> 
			<h4>You have specified an incorrect password.</h4>
		<?php } ?>

		<button class="ui-btn ui-shadow" type="submit">Login</button>
		</form>
	</div>
</div>

<?php } ?>

</body>
</html>

Bootstrap 3 (Report, login form)

<?php

$user = ['email' => 'admin@admin.admin', 'password' => 'admin@admin.admin'];

$is_admin = false;
$error = false;

if(isset($_POST['email']) && isset($_POST['password'])) {

	if($_POST['email'] == $user['email'] && $_POST['password'] == $user['password']) {
	
		$is_admin = true;
	} else {
	
		$error = true;
	}
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Report</title>

<!-- Bootstrap -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
	<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
	
	<?php if($is_admin) { ?>
	
		<div class="container">
		
			<div class="page-header">
				<h1>Report</h1>
			</div>
			
			<div class="panel panel-default">
			<div class="panel-heading">
				<h3 class="panel-title">Panel title</h3>
			</div>
			<div class="panel-body">
				<h3>Text</h3>
				<p>Text text text text text</p>
				
				<hr />
				
				<h3>Text</h3>
				<p>Text text text text text</p>
				
				<hr />
				
				<h3>Text text</h3>
				<p>Text text text text text text text text text text text text text</p>
				<div class="progress">
					<div class="progress-bar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%;">75%</div>
				</div>
				
				<hr />

			</div>
			</div>
		</div>

	<?php } else { ?>

		<div class="container">
			<div class="page-header">
				<h1>Sign in</h1>
			</div>
			
			<form class="form-horizontal" role="form" method="post">
				<div class="form-group <?php if($error) { ?>has-error<?php } ?>">
					<label for="inputEmail" class="col-sm-2 control-label">Email</label>
					<div class="col-sm-10">
					  <input type="email" name="email" class="form-control" id="inputEmail" placeholder="Email">
					</div>
					</div>
				<div class="form-group <?php if($error) { ?>has-error<?php } ?>">
					<label for="inputPassword" class="col-sm-2 control-label">Password</label>
					<div class="col-sm-10">
					  <input type="password" name="password" class="form-control" id="inputPassword" placeholder="Password">
					</div>
				</div>
				<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						<?php if($error) { ?> 
							<div class="alert alert-danger">You have specified an incorrect password.</div>
						<?php } ?>
					</div>
				</div>
				<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						<button type="submit" class="btn btn-primary btn-lg">Sign in</button>
					</div>
				</div>
			</form>
		</div>


	<?php } ?>

	<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</body>
</html>

XML

<?xml version="1.0" encoding="UTF-8" ?>
<root>
	<report>
		<id>1</id>
		<visits>10</visits>
		<pageviews>100</pageviews>
		<timeOnSite>72.4</timeOnSite>
		<bounces>17.31</bounces>
	</report>
	
	<report>
		<id>2</id>
		<visits>100</visits>
		<pageviews>1000</pageviews>
		<timeOnSite>50.51</timeOnSite>
		<bounces>20.36</bounces>
	</report>
</root>

Java (XML)

List<Report> report = new ArrayList<Report>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
try {

	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(new File("C:\\example\\1.xml"));
	doc.getDocumentElement().normalize();
	NodeList nl = doc.getElementsByTagName("report");

	for (int temp = 0; temp < nl.getLength(); temp++) {

		Node n = nl.item(temp);
		if (n.getNodeType() == Node.ELEMENT_NODE) {
			Element e = (Element) n;
			report.add(new Report(
					Integer.valueOf(e.getElementsByTagName("id").item(0).getTextContent()),
					Double.parseDouble(e.getElementsByTagName("visits").item(0).getTextContent()), 
					Double.parseDouble(e.getElementsByTagName("pageviews").item(0).getTextContent()),
					Double.parseDouble(e.getElementsByTagName("timeOnSite").item(0).getTextContent()),
					Double.parseDouble(e.getElementsByTagName("bounces").item(0).getTextContent())
					)
				);
		}
	}
} catch (Exception e) {
	
	e.printStackTrace();
}

/**
 * TEST!
 */
for (Report result : report) {
	System.out.println(result);
}

Java (Report.java)

public class Report {
	
	private Integer id;
	private Double visits;
	private Double pageviews;
	private Double timeOnSite;
	private Double bounces;
	
	public Report(Integer id, Double visits, Double pageviews,
			Double timeOnSite, Double bounces) {

		this.id = id;
		this.visits = visits;
		this.pageviews = pageviews;
		this.timeOnSite = timeOnSite;
		this.bounces = bounces;
	}
	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	/**
	 * @return the visits
	 */
	public Double getVisits() {
		return visits;
	}
	/**
	 * @param visits the visits to set
	 */
	public void setVisits(Double visits) {
		this.visits = visits;
	}
	/**
	 * @return the pageviews
	 */
	public Double getPageviews() {
		return pageviews;
	}
	/**
	 * @param pageviews the pageviews to set
	 */
	public void setPageviews(Double pageviews) {
		this.pageviews = pageviews;
	}
	/**
	 * @return the timeOnSite
	 */
	public Double getTimeOnSite() {
		return timeOnSite;
	}
	/**
	 * @param timeOnSite the timeOnSite to set
	 */
	public void setTimeOnSite(Double timeOnSite) {
		this.timeOnSite = timeOnSite;
	}
	/**
	 * @return the bounces
	 */
	public Double getBounces() {
		return bounces;
	}
	/**
	 * @param bounces the bounces to set
	 */
	public void setBounces(Double bounces) {
		this.bounces = bounces;
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((bounces == null) ? 0 : bounces.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result
				+ ((pageviews == null) ? 0 : pageviews.hashCode());
		result = prime * result
				+ ((timeOnSite == null) ? 0 : timeOnSite.hashCode());
		result = prime * result + ((visits == null) ? 0 : visits.hashCode());
		return result;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Report)) {
			return false;
		}
		Report other = (Report) obj;
		if (bounces == null) {
			if (other.bounces != null) {
				return false;
			}
		} else if (!bounces.equals(other.bounces)) {
			return false;
		}
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		if (pageviews == null) {
			if (other.pageviews != null) {
				return false;
			}
		} else if (!pageviews.equals(other.pageviews)) {
			return false;
		}
		if (timeOnSite == null) {
			if (other.timeOnSite != null) {
				return false;
			}
		} else if (!timeOnSite.equals(other.timeOnSite)) {
			return false;
		}
		if (visits == null) {
			if (other.visits != null) {
				return false;
			}
		} else if (!visits.equals(other.visits)) {
			return false;
		}
		return true;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Report [id=" + id + ", visits=" + visits + ", pageviews="
				+ pageviews + ", timeOnSite=" + timeOnSite + ", bounces="
				+ bounces + "]";
	}
}

Java (Read a file into string)

	public String fileToString(String fileName) {
		String output = null;
		
		try {
			output = new Scanner(new File(getPath() + fileName)).useDelimiter("\\Z").next();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return output;
	}

Java (Save a string to a file)

	public void saveStringToFile(String fileName, String content) {
		PrintWriter out = null;
		
		try {
			out = new PrintWriter(new FileWriter(getPath() + fileName));
			out.print(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
			if(out != null) {
				out.close();
			}
		}
	}

Java (Read a CSV file)

BufferedReader in = null;
HashMap<Integer, String> ga = new HashMap<Integer, String>();

try {
	in = new BufferedReader(new FileReader("C:\\test\\backup\\1.csv"));
	while (in.ready()) {
		String[] result = in.readLine().split(";");
		ga.put(Integer.parseInt(result[0]), result[1]);
	}
} catch (IOException e) {
	e.printStackTrace();
} finally {
	if(in != null) {
		
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

for (Entry<Integer, String> entry : ga.entrySet()) {
	System.out.println(entry.getKey() + " === " + entry.getValue());
}

Java (Connector)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Connector {

	private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/";
	private static final String DB_USER = "root";
	private static final String DB_PASSWORD = "";
	private static final String EVENT_SELECT = "SELECT * FROM t1.portals LIMIT 10;";
	private Connection connect = null;

	/**
	 * Constructor
	 */
	public Connector() {

		try {
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			connect = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
		} catch (SQLException e) {
			System.out.println(e); // LOG.fatal(e);
		}
	}

	/**
	 * Get the connect
	 */
	public Connection getConnect() {

		return connect;
	}

	/**
	 * Test!
	 */
	public void testConnect() {

		java.sql.PreparedStatement st = null;
		ResultSet rs = null;

		try {
			st = connect.prepareStatement(EVENT_SELECT);
			rs = st.executeQuery();

			while (rs.next()) {
				System.out.println(rs.getString(2));
			}
		} catch (SQLException e) {
			System.out.println(e); // LOG.fatal(e);
		} finally {
			closeConnect();
		}
	}

	/**
	 * Close the connect
	 */
	public void closeConnect() {

		if (connect != null) {
			try {
				connect.close();
			} catch (SQLException e) {
				System.out.println(e); // LOG.fatal(e);
			}
		}
	}
}

Java (Date)

	public String dateToString(String format) {
	
		DateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(new Date());
	}

Java (Downloading a file)

	public static void getContentByURL(String url, String fileName) {
		
		FileOutputStream contentForFile = null;
		try {
			
			URL website = new URL(url);
			ReadableByteChannel channel = Channels.newChannel(website.openStream());
			contentForFile = new FileOutputStream(fileName);
			contentForFile.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);

		} catch (Exception ex) {      
			
			ex.printStackTrace();
		} finally {
			
			try {
				contentForFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

Java (validate, email)

	public static boolean validEmail(String email) {

		boolean result = true;
		try {
			
			InternetAddress ia = new InternetAddress(email);
			ia.validate();
		} catch (AddressException ex) {
			
			result = false;
		}
		
		return result;
	}

Java (parse)

	public static String getTitle(String html) {
		
		return html.replaceAll("(?i)(<title.*?>)(.+?)(</title>)", "$2");
	}

Java (Sort)

	public static int[] sortBbl(int[] in) {
		
		for (int i = in.length - 1; i >= 2; i--) {
			
			boolean s = true;
			
			for (int h = 0;h < i; h++) {
			
				if (in[h] > in[h+1]) {
					
					int k = in[h];
					in[h] = in[h+1];
					in[h+1] = k;
					s = false;
				}
			}
	
			if(s) {
				
				break;
			}
		}
		
		return in;
	}

Java (Summ and avg.)

	public static double vSumm(double[] v) {

		double aSumm = 0;
		
		for (int i = 0; i < v.length ; i++) {
			
			aSumm += v[i];
		}
		
		return aSumm;
	}

	public static double vAvg(double[] am) {

		return vSumm(am) / am.length;
	}

SEEyp

SEEyp is a free collection of code snippets (PHP, Java, JavaScript, CSS) and useful tool (you can easily build up your personal collection of code snippet). Free for personal and commercial use. For more information see readme_ru.html.

// Create a new file (file name: main.txt) and add the following content to it
// The file main.txt can be located in the directory with seeyp.exe
// After the create is complete, you have to run seeyp.exe and click Run

// Set a title of document
# Title

// Add a note to your personal collection
= Sub-heading
Text

// Add a code snippet to your personal collection
%^
Code. Escape character (circumflex): &#94;
^

// As is
!^
<h3>Text</h3>
<p>Text text <em>text</em> text text</p>
^

Copyright © 1999 — 2014, Kalinin Alexandr. // f121h@yandex.ru, www.kalinin84.info and vk.com/aik84