Skip to content

Instantly share code, notes, and snippets.

View brainwire's full-sized avatar

Vadim Gorbunov brainwire

View GitHub Profile
# позволяет получить процентное соотношение для чисел в массиве
# percents [1,2,3] => [0.16666666666666666, 0.3333333333333333, 0.5]
def percents(numbers)
total = numbers.inject(:+).to_f
numbers.map {|it| it / total }
end
# позволяет получить процентное распределение для чисел в массиве
# требуется чтобы генерировать рендомное число с заданными вероятностями
# distribution [1,2,3] => [0.16666666666666666, 0.5, 1.0]
100 = :continue
101 = :switching_protocols
102 = :processing
200 = :ok
201 = :created
202 = :accepted
203 = :non_authoritative_information
204 = :no_content
205 = :reset_content
206 = :partial_content
http://tweaked.io/guide/kernel/
В настройках ядра ОС (/etc/sysctl.conf) особое внимание нужно обратить на:
kernel.shmmax = 8000234752 // Это для PostgreSQL, чтоб можно было выставлять большой shared_buffers (6 - 8GB)
fs.file-max = 99999999 // Это для Nginx, без него можно получить "Too many open files"
net.ipv4.tcp_max_syn_backlog=524288 // Максимальное число запоминаемых запросов на соединение
net.ipv4.tcp_max_orphans=262144 // Максимальное число допустимых в системе сокетов TCP
net.core.somaxconn=65535 // Максимальное число открытых сокетов
net.ipv4.tcp_mem=1572864 1835008 2097152 // Потребление памяти для протокола TCP
net.ipv4.tcp_rmem=4096 16384 16777216 // Размер приемного буфера сокетов TCP
@brainwire
brainwire / gist:a8ae7f3fb152f3a3187b
Created February 8, 2015 07:02
Coocon: Allow to use with simple arrays without AR
I'm using my branch now in the project which works perfectly fine so far.
The only additional glue to use it with fully transient models are those few methods: new_record?, marked_for_destruction? and _destroy.
I'm not sure why cocoon touches the _destroy method.
The example above allows using fully transient models (non-ActiveRecord) with cocoon and any form builder.
I'll put everything together for a comprehensive example:
@brainwire
brainwire / gist:8a73d0174be0f1409fda
Created December 22, 2014 09:54
Rails auto-assigning id that already exists
ActiveRecord::Base.connection.tables.each { |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) }
task :name, [:first_param, :second_param]
task :name, [:first_param, :second_param] do |t, args|
  args.with_defaults(:first_param => "John", :second_param => "Dough")
  puts "First is #{args.first_param}"
  puts "Second is #{args.second_param}"
end
task :name, [:first_param, :second_param] => [:pre_task] do |t, args|
  args.with_defaults(:first_param => "John", :second_param => "Dough")
@brainwire
brainwire / partition_magic.sql
Created November 17, 2014 05:25
partition_magic
CREATE OR REPLACE FUNCTION _2gis_partition_magic_before_insert_trigger() RETURNS trigger AS $$
DECLARE
hasMeta boolean;
meta RECORD;
partition_id integer;
itable text;
partitionRes boolean;
BEGIN
hasMeta := false;
FOR meta IN SELECT * FROM _2gis_partition_magic_meta m WHERE m.table_name = TG_TABLE_NAME
@brainwire
brainwire / desc
Last active August 29, 2015 14:09
Postgres. Выборка N случайных записей
{table} — название таблицы;
{pk} — имя PrimaryKey-поля;
{fields} — список полей для выборки (можно указать и "*");
{exclude} — условие (набор условий) для исключения записей из выборки. Например «t.id NOT IN (1,2,3,4)»;
{limit} — количество записей в финальной выборке
=Navigating=
visit('/projects')
visit(post_comments_path(post))
=Clicking links and buttons=
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click('Link Text') # Click either a link or a button
click('Button Value')
@brainwire
brainwire / Querying
Created October 30, 2014 11:47
using Arrays in Rails with PostgreSQL
2.1.2 :026 > Book.where("'history' = ANY (subjects)")
Book Load (0.5ms) SELECT "books".* FROM "books" WHERE ('history' = ANY (subjects))
=> #<ActiveRecord::Relation [#<Book id: "39abef75-56af-4ad5-8065-6b4d58729ee0", title: nil, created_at: "2014-10-17 08:21:17", updated_at: "2014-10-17 19:21:25", description: {}, metadata: {}, subjects: ["education", "business", "history", "finances"]>]>
2.1.2 :027 > Book.where("subjects @> ?", '{finances}')
Book Load (0.5ms) SELECT "books".* FROM "books" WHERE (subjects @> '{finances}')
=> #<ActiveRecord::Relation [#<Book id: "39abef75-56af-4ad5-8065-6b4d58729ee0", title: nil, created_at: "2014-10-17 08:21:17", updated_at: "2014-10-17 19:21:25", description: {}, metadata: {}, subjects: ["education", "business", "history", "finances"]>]>