/ Gists

Gists

On gists

Private members and prototypes

JavaScript-OOP JavaScript

example.js #

function Dog(name, color) {
    //private members
    var name = name,
        color = color;

    //public method
    this.getColor = function () {
        return color;
    }
    //public method
    this.getName = function () {
        return name;
    }
}
Dog.prototype = (function () {
    //private member
    var breed = 'French Bulldog',
    
    //private method
    getBreed = function () {
        return breed;
    };
    
    //public interface
    return {
        getBreed: function () {
            return breed;
        },
        getMessage: function () {
            return this.getColor() + ' dog, ' + 
                getBreed() + ' breed, named ' + 
                this.getName() + ' is missing';
        }
    }
})();

On gists

Maximum value by each row

Popular ⭐ MySql MySql - advanced Nette-Tricks

structure.sql #


CREATE TABLE shop (
    article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
    dealer  CHAR(20)                 DEFAULT ''     NOT NULL,
    price   DOUBLE(16,2)             DEFAULT '0.00' NOT NULL,
    PRIMARY KEY(article, dealer));
INSERT INTO shop VALUES
    (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
    (3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
    
    

    
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | A      |  3.45 |
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | B      |  1.45 |
|    0003 | C      |  1.69 |
|    0003 | D      |  1.25 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

On gists

PHP array sorting

PHP

ways.php #

  <?php
  $array = [
              [
                ['name'=>'John B'],
                ['age'=>30],
                ['sizes'=>
                          [
                          'weight'=>80, 
                          'height'=>120
                          ]
                ]
              ],
              [
                ['name'=>'Marie B'],
                ['age'=>31],
                ['sizes'=>
                          [
                          'weight'=>60, 
                          'height'=>110
                          ]
                ]
              ],
              [
                ['name'=>'Carl M'],
                ['age'=>12],
                ['sizes'=>
                          [
                          'weight'=>70, 
                          'height'=>100
                          ]
                ]
              ],
              [
                ['name'=>'Mike N'],
                ['age'=>19],
                ['sizes'=>
                          [
                          'weight'=>70, 
                          'height'=>150
                          ]
                ]
              ],
              [
                ['name'=>'Nancy N'],
                ['age'=>15],
                ['sizes'=>
                          [
                          'weight'=>60, 
                          'height'=>150
                          ]
                ]
              ],
              [
                ['name'=>'Cory X'],
                ['age'=>15],
                ['sizes'=>
                          [
                          'weight'=>44, 
                          'height'=>150
                          ]
                ]
              ]
  ];

  

   //Method1: sorting the array using the usort function and a "callback that you define"
   function method1($a,$b) 
   {
     return ($a[2]["sizes"]["weight"] <= $b[2]["sizes"]["weight"]) ? -1 : 1;
   }
   usort($array, "method1");
   print_r($array);




//Method 2: The bubble method
$j=0;
$flag = true;
$temp=0;

while ( $flag )
{
  $flag = false;
  for( $j=0;  $j < count($array)-1; $j++)
  {
    if ( $array[$j][2]["sizes"]["weight"] > $array[$j+1][2]["sizes"]["weight"] )
    {
      $temp = $array[$j];
      //swap the two between each other
      $array[$j] = $array[$j+1];
      $array[$j+1]=$temp;
      $flag = true; //show that a swap occurred
    }
  }
}
print_r($array);



  //Method3: DIY 
  $temp = [];
  foreach ($array as $key => $value)
    $temp[$value[2]["sizes"]["weight"] . "oldkey" . $key] = $value; //concatenate something unique to make sure two equal weights don't overwrite each other
  ksort($temp); // or ksort($temp, SORT_NATURAL); see paragraph above to understand why
  $array = array_values($temp);
  unset($temp);
  print_r($array);



  // Method 4
  array_multisort(array_map(function($element) {
    return $element[2]['sizes']['weight'];
}, $array), SORT_ASC, $array);


print_r($array);

On gists

Prev / Next row - mysql select - variables, corelated subquery

MySql MySql tricks

scheme.sql #

create table example(
  id int not null primary key,
  value varchar(50)
);

insert into example
values (0,100),(2,150),(3,200),(6,250),(7,300)

On gists

Remove diacritics - strtr

PHP

rem-dia.php #

<?php

    private function removeDiacritics($str)
    {
        return strtr($str, "ÁÄČÇĎÉĚËÍŇÓÖŘŠŤÚŮÜÝŽáäčçďéěëíňóöřšťúůüýž", "AACCDEEEINOORSTUUUYZaaccdeeeinoorstuuuyz");
    }

On gists

Procedury - MIX

MySql MySql - advanced

poradi-tymu.sql #

CREATE PROCEDURE SP_poradi()
BEGIN
 
DECLARE s_poradi INT(5);
DECLARE s_body INT(5);
DECLARE temp_body INT(5) DEFAULT 0;
DECLARE s_tym VARCHAR(50);
DECLARE my_rank INT(5) DEFAULT 0;
DECLARE done TINYINT(1) DEFAULT 0;
 
DECLARE i INT;
 
DECLARE rank CURSOR FOR
SELECT tym, body, poradi FROM poradi
ORDER BY body DESC;
 
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
 
SET i = 0;
OPEN rank;
rank_loop:  LOOP
 
FETCH rank INTO s_tym, s_body, s_poradi;
IF done THEN LEAVE rank_loop; END IF;

 
IF (temp_body <> s_body)
  THEN UPDATE poradi SET poradi = i + 1 WHERE tym = s_tym;
ELSE
  UPDATE poradi SET poradi = i + 0 WHERE tym = s_tym;
END IF;
 
SET i=i+1;
SET temp_body = s_body;  
 
 
END LOOP rank_loop;
CLOSE rank;
 
END;

On gists

Nette own storage via Session - wrapper

Nette PHP

Storage.php #

<?php

namespace Model;

use Nette;

class DemandStorage extends Nette\Object
{
    protected $session;
    public function __construct(Nette\Http\Session $session)
    {
        $this->session = $session->getSection('demandForm');    
    }

    public function flush()
    {
        $this->session->remove();
    }

    public function getRawData()
    {
        return isset($this->session['formData']) ? $this->session['formData'] : array();
    }

    public function getStepNumber()
    {
        return isset($this->session['step']) ? $this->session['step'] : 1;
    }

    public function setRawData($data)
    {
        $this->session['formData'] = $data;
        return $this;
    }

    public function addRawData($data)
    {
        $originalData = $this->getRawData();
        $data = array_merge($originalData, $data);
        $this->setRawData($data);
        return $this;
    }

    public function setStepNumber($step = 1)
    {
        $this->session['step'] = $step;
        return $this;
    }

    public function getValue($name, $default = NULL)
    {
        $data = $this->getRawData();
        return Nette\Utils\Arrays::get($data, $name, $default);
    }

    public function setValue($name, $value)
    {
        $data = $this->getRawData();
        $data[$name] = $value;
        $this->setRawData($data);
        return $this;
    }

    public function unsetValue($name)
    {
        $data = $this->getRawData();
        if(isset($data[$name]))
            unset($data[$name]);
        $this->setRawData($data);
        return $this;
    }

    public function issetValue($name)
    {
        $data = $this->getRawData();
            return isset($data[$name]);
    }

}

On gists

IE 11 - CSS Grid - SASS mixins

SCSS CSS CSS trick

mixins.scss #

// Ensure CSS grid works with IE 11 spec.
// https://css-tricks.com/browser-compatibility-css-grid-layouts-simple-sass-mixins/
// sass-lint:disable no-vendor-prefixes, no-duplicate-properties
@mixin display-grid {
  display: -ms-grid;
  display: grid;
}

// $columns values should be delimited by a space
@mixin grid-template-columns($columns...) {
  -ms-grid-columns: $columns;
  grid-template-columns: $columns;
}

// $rows values should be delimited by a space
@mixin grid-template-rows($rows...) {
  -ms-grid-rows: $rows;
  grid-template-rows: $rows;
}

// Can be used in combination with above grid-template-X mixins.
// These result in the same output:
// @include grid-template-columns(10px grid-repeat(4, 20px) 30px);
// @include grid-template-columns(10px 20px 20px 20px 20px 30px);
@function grid-repeat($repeat, $stuff: 1fr) {
  $list: ();
  @for $i from 1 through $repeat {
    $list: append($list, $stuff, space);
  }
  @return $list;
}

@mixin grid-column($col-start, $col-end) {
  -ms-grid-column: $col-start;
  -ms-grid-column-span: $col-end - $col-start;
  grid-column: #{$col-start} / #{$col-end};
}

@mixin grid-row($row-start, $row-end) {
  -ms-grid-row: $row-start;
  -ms-grid-row-span: $row-end - $row-start;
  grid-row: #{$row-start} / #{$row-end};
}

@mixin grid-align-self($value) {
  -ms-grid-row-align: $value;
  align-self: $value;
}

@mixin grid-justify-self($value) {
  -ms-grid-column-align: $value;
  justify-self: $value;
}

On gists

Easy slider

jQuery jQuery-plugins

slider.js #

/**
 * Easy slider plug-in pro jQuery
 * 
 * (c) 2012 Drahomír Hanák
 */

(function( $ ) {

	var inited = false;

	// Volatelné funkce
	var methods = {
	
		// Funkce nastaví aktivní slide (Index od 0 do počtu obrázků v galerii) -
		active: function( index, direction ) {
			// Nastavíme rychlost
			speed = $(this).data('speed') || 800;
			// Nastavíme směry efektů
			directionHide = direction || 'left';
			directionShow = directionHide == 'left' ? 'right' : 'left';
			// Skryjeme aktivní položku
			$(this).find('li.active').hide('slide', { direction: directionHide }, speed);
			// Všem položkám odstraníme třídu .active
			$(this).find('li').removeClass('active');	
			// Načteme activní slide
			var slide = $(this).find('li').get(index) || false;
			// Zobrazíme ho
			$(slide).addClass('active').show('slide', { direction: directionShow }, speed);
			// Vrátíme aktivní element 
			return $(this).find('li').get(index) || false;
		},
		
		// Přesune se na další slide
		next: function() {
			// Najdeme další element a zjistíme jeho index, ke kterému přičteme +1
			var index = ($(this).find('li.active').index()+1);
			
			// nebo = imho cistci zpusob
			//methods.active.call(this, $(this).find('li').get(index) ? index : 0);
			
			// zpusob autora viz nizie ani ten return tam byt nemusi ...
			//$(this).easySlider("active", ($(this).find('li').get(index) ? index : 0));
			
			// Aktivujeme tento slide, pokud existuje. Pokud ne, automaticky se přesuneme na první (nultý)
			return $(this).easySlider("active", ($(this).find('li').get(index) ? index : 0));
		},
		
		// Přesune se na předchozí slide
		prev: function() {
			var index = $(this).find('li.active').index()-1 < 0 ? $(this).find('li').length-1 : $(this).find('li.active').index()-1;
			// Aktivujeme slide s títo indexem
			return $(this).easySlider("active", index, 'right');	
		},
		
		// Vstupní funkce plug-inu
		init: function( o ) {
			// Získáme nastavené volby plug-inu
			o = $.extend({}, $.fn.easySlider.defaults, o);
			// Uložíme si aktuální kontext funkce (element plug-inu)
			var $that = $(this);
			
			// Pokud už jsme jednou inicializovali element, nebudeme to přece dělat znova
			if ( inited ) return false; 
			
			// Funkce po kliknutí na šipky
			var left_click = function( e ) {
				e = $.event.fix(e);
				e.preventDefault();
				$that.easySlider("prev");
			}, right_click = function( e ) {
				e = $.event.fix(e);
				e.preventDefault();
				$that.easySlider("next");
			};
			
			// Projdeme a vrátíme všechny elementy, kterým bylo předáno zpracování plug-inu
			return this.each(function() {
				// Najdeme všechny obrázky ve slideru
				var $items = $(this).find('li'), 
					count = $items.length,
					$self = $(this);
					
				// Všechny je skryjeme a pozicujeme absolutně
				$items.css({ display: 'none', position: 'absolute' });
				
				// Vložíme seznamu třídu pro přístupnější manipulování v CSS
				$self.addClass('easySlider-content').data('speed', o.speed); 
				
				// Aktivujeme první element
				$($items.get(o.active)).addClass("active");
				
				// Vytvoříme si postraní šipky pro posun slideru
				var $arrowLeft = $('<a />').attr('href', '#left').addClass('arrowLeft');
				var $arrowRight = $('<a />').attr('href', '#right').addClass('arrowRight');
				// Nastavíme callback na kliknutí
				$arrowLeft.bind('click', left_click);
				$arrowRight.bind('click', right_click);
				// Vložíme je před seznam slidů
				$self.before( $arrowRight );
				$self.before( $arrowLeft );
			});
		}	
	};

	// Vstupní funkce plug-inu
	$.fn.easySlider = function( method ) {
		// Pokud máme jméno funkce, kterou chceme zavolat
		if ( methods[method] ) {
			// Zavoláme danou funkci se všemi ostatními předanými argumenty plug-inu
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));	
		} else if ( typeof method == 'object' || !method ) {
			// Pokud ne, zavoláme inicializační metodu
			return methods.init.apply(this, arguments);
		} else {
			// Pokud metoda neexistuje, vypíšeme chybu
			$.error('Metoda ' + method + ' neexistuje v plug-inu jQuery.easySlider');
		}
	}; 
	
	
	// Defaultní nastavení
	$.fn.easySlider.defaults = {
		// Index prvního aktivního prvku slideru
		active: 1,
		// Rychlost přechodu v milisekundách
		speed: 500 	
	};

})( jQuery );

On gists

Refresh Nette Ajax - live

Nette

netteext.js #

$.nette.ext('load_nette_after_snippets', {
    init: function() {
        this.ext('snippets').after(function() {
            $.nette.load();
        });
    }
});

$.nette.init();