Skip to content

Instantly share code, notes, and snippets.

View SergSlon's full-sized avatar
😀

Liamin Serhii SergSlon

😀
View GitHub Profile
@SergSlon
SergSlon / slice_concatenate.js
Created September 23, 2015 06:26
Вывод больших чисел для удобства чтения
function slice_concatenate(i){
var s = i.toString();
var l = s.length;
var result = '';
if (l > 15) result += s.slice(-18, -15) + "'";
if (l > 12) result += s.slice(-15, -12) + "'";
if (l > 9) result += s.slice(-12, -9) + "'";
if (l > 6) result += s.slice(-9, -6) + "'";
if (l > 3) result += s.slice(-6, -3) + "'";
@SergSlon
SergSlon / session-life-cycle.md
Last active September 21, 2015 06:31 — forked from mindplay-dk/session-life-cycle.md
Complete overview of the PHP SessionHandler life-cycle

This page provides a full overview of PHP's SessionHandler life-cycle - this was generated by a set of test-scripts, in order to provide an exact overview of when and what you can expect will be called in your custom SessionHandler implementation.

Each example is a separate script being run by a client with cookies enabled.

To the left, you can see the function being called in your script, and to the right, you can see the resulting calls being made to a custom session-handler registed using session_set_save_handler().

@SergSlon
SergSlon / IoC.md
Last active August 29, 2015 14:23 — forked from greabock/IoC.md

Инверсия управления (англ. Inversion of Control, IoC) — важный принцип объектно-ориентированного программирования, используемый для уменьшения зацепления в компьютерных программах. Также архитектурное решение интеграции, упрощающее расширение возможностей системы, при котором контроль над потоком управления программы остаётся за каркасом - ru.wikipedia.org


Сегодня хотелось бы поговорить о реализации инверсии управления в Laravel. Это один из самых важных аспектов организации слабой связанности компонентов в любимом нами фреймворке, и его понимание играет ключевую роль при создании качественных пакетов и приложений.

Когда мы говорим об IoC в Laravel, то следует знать, что он стоит на трех китах:

  1. Внедрение зависимостей (Dependency Injection)
@SergSlon
SergSlon / main.js
Created May 27, 2015 11:43
serializeFormToObject
$.fn.serializeFormToObject = function()
{
var obj = {};
var serializedArr = this.serializeArray();
$.each(serializedArr, function() {
if (obj[this.name] !== undefined) {
if (!obj[this.name].push) {
obj[this.name] = [obj[this.name]];
}
obj[this.name].push(this.value || '');
@SergSlon
SergSlon / gist:8e25c99aee163d7eb197
Created April 28, 2015 08:45
Создание модуля JS
(function(root, factory) {
// это для загрузчика модуля АМД
if (typeof define === 'function' && define.amd) { // то есть, если можем дотянуться до define с amd,
define(['underscore', 'jquery', 'exports'], function(_, $, exports) { // то им модуль и создадим
// а вдруг кто-то ждет бэкбон еще и в глобальном объекте
root.Backbone = factory(root, exports, _, $);
});
// это для Node, где jQuery не нужен
@SergSlon
SergSlon / phpd
Last active August 29, 2015 14:16
phpstorm debug with cli scripts
#!/bin/bash
export PHP_IDE_CONFIG="serverName=site.com"
php \
-d xdebug.remote_autostart=1 \
-d xdebug.remote_enable=1 \
-d xdebug.idekey=PHPSTORM \
-d xdebug.remote_host=123.45.6.78 \
"$@"
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText("Here is the body of my message")
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
p.communicate(msg.as_string())

Transforming Code into Beautiful, Idiomatic Python

Notes from Raymond Hettinger's talk at pycon US 2013 video, slides.

The code examples and direct quotes are all from Raymond's talk. I've reproduced them here for my own edification and the hopes that others will find them as handy as I have!

Looping over a range of numbers

for i in [0, 1, 2, 3, 4, 5]:
@SergSlon
SergSlon / gist:5a2e7f692ca376507b43
Last active August 29, 2015 14:11
Принципы написания качественных тестов - F.I.R.S.T.
Принципы написания качественных тестов - F.I.R.S.T.
F.I.R.S.T.:
Fast (Быстрота),
Independent (Независимость),
Repeatable (Повторяемость),
Self-Validating (Очевидность) (*),
Timely (Своевременность)
Быстрота (Fast). Тесты должны выполняться быстро. Все мы знаем, что разработчики люди, а люди ленивы, поскольку эти выражения являются “транзитивными”, то можно сделать вывод, что люди тоже ленивы. А ленивый человек не захочет запускать тесты при каждом изменении кода, если они будут долго выполняться.