Thursday, December 5, 2013

Без автора "Одиноким людям не спится..."

Одиноким людям не спится.
Им до жути скучно ночами.
Таким людям однажды не спиться бы,
Вы по ним
Никогда
Не скучали.

Они сходят с ума ежедневно.
Одиночки
От жизни устали.
Они пишут стихи, но, наверное,
Вы Такое
Читать бы
Не стали.

Они замкнуты,
Словом ранены.
Им страшно кого-то любить.
Они чешут душевные ссадины.
Они жаждут
Кого-то
Забыть.

Saturday, November 23, 2013

LAMP: Creating virtual hosts and resolving 500 Internal server error

This guide expects, that you already have web server on your machine.

1. Copy file /etc/apache2/sites-available/default and rename it to your host name. (for example testweb.net. Also your web application must be in /var/www/testweb.net/ directory.) Dont forget to add permissions to your web application directory using
sudo chmod -R 755 /var/www/testweb.net/ For development you can use 777, but it is still not the best practice.
sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/testweb.net

2. Configure testweb.net file
gksudo gedit /etc/apache2/sites-available/testweb.net

This command will open testweb.net file in gedit text editor.

ServerName testweb.net
<VirtualHost *:80>
 ServerAdmin admin@mail.com
 ServerName testweb.net
 ServerAlias www.testweb.net
 [...]

DocumentRoot /var/www/testweb.net
I'm using my own hosts configuration file:
    ServerNametestweb.net
    ServerAlias www.testweb.net

    DocumentRoot /var/www/testweb.net
    <Directory /var/www/testweb.net>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>

3. Activate your host

sudo a2ensite testweb.net

4. Edit /etc/hosts
gksudo gedit /etc/hosts
Add this line to hosts file:

127.0.0.1    testweb.net

5. Now you need to restart your apache service.
sudo service apache2 restart
Voila, your virtual host is now available!

What should you do, if you have 500 Internal Server Error? 

This problem might be caused by .htaccess file in your project root dir. First of all, check your logs (/var/log/apache2/) and try to access your site by this link: localhost/testweb.net. But for me it was not enough, so I found this solution (not sure what this command do, so run it on your own risk T_T)

sudo a2enmod rewrite
sudo service apache2 restart

Here you can read about 500 error solving: http://askubuntu.com/questions/148246/apache2-htaccess

This resource was really helpful: https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

P.S. YEAH, I know, there are LOTS of english mistakes, sorry for that :(

Thursday, November 14, 2013

SVN resolving problem: "containing working copy admin area is missing"

For an instance, we're having this error: "some/folder/.svn containing working copy admin area is missing".

There are lots of solutions here: http://stackoverflow.com/questions/1394076/how-to-fix-containing-working-copy-admin-area-is-missing-in-svn, but here's the one, that worked for me (not the most elegant, I suppose, but it worked):

1. Remove the conflicted folder (if there are some uncommited files, we need to back them up)
cd /your/project/root
sudo rm -rf some/folder
svn up
2. Commit your changes!

Wednesday, November 13, 2013

Setting up permissions on Ubuntu for /var/www (web server)

In ubuntu all web projects are in /var/www folder, so you need to set up permissions on writing files, as by default this folder belongs to root user.

1. First of all you need to ensure, that your current user belongs to www-data group. Adding user to www-data group:

sudo adduser username www-data

You can find your username by typing this command:

whoami

2. Next we need to change /var/www folder owner and owner group:

sudo chown username:www-data -R /var/www

3. Next we need to change /var/www permissions to 755 (777 not recommended due security reasons)

sudo chmod 755 -R /var/www
sudo chmod g+s -R /var/www

Information from: http://askubuntu.com/questions/162866/correct-permissions-for-var-www-and-wordpress

Wednesday, November 6, 2013

Ruby: exceptions

raise "Exception message" // this will throw RuntimeError exception with message "Exception message"

begin
  10/0 // This will raise an DivisionByZero exception
rescue DivisionByZero
  puts "Devision by zero exception"
end
Creating custom exception:
class CustomException > StandardError
end

Ruby: OOP (privacy)

Methods are public by default in Ruby.

class Test

  def public_m
  end

  private
  def private_m
  end

  // Again private method, because all methods after private keyword will be private
  def private_m_2
  end

end
Modules are containers for methods and constants.

module MyModule
  // Call it: MyModule::MOD_CONSTANT
  MOD_CONSTANT = "Module constat"

  // Call it: MyModule.my_method
  def my_method
  end
end
Require module by typing require 'MyModule', so it will be available in whole file (Module.my_method)

Include module to class, so it will be available inside class and all the methods can be called without module name:


class SimpleClass
  include MyModule // Without '
  def m
    my_method
  end
end
Infromation from: www.codeacademy.com

Ruby: OOP (Basic)

class Person
  // This is a variable, that belongs to class
  // Like static variable in PHP
  @@class_variable = 0

  // This is a global variable
  $global_var

  // This is a constructor
  def initialize(name)
    // @name - class variable, name - local variable
    // @name will be available in whole class
    @name = name
    @class_variable += 1
  end

  // This is method, that belongs to class not to instance!
  // Like static method in PHP
  def self.class_method
  end
end

// This will create 2 instances of a Person class
andy = Person.new("Andy")
marrel = Person.new("Marrel")
// @@class_variable on this step will be equals to 2

Inheritance
// Class andy inherits all from class Person
class Andy < Person
  def initialize(name)
    // This will call parent initialize method
    super(name)
  end
end 

Infromation from: www.codeacademy.com 

Ruby: procs and lambdas

Procs:
Sometimes you need to pass block to your method. The problem is that you cant save block to variable, because it is not an object. If you need to pass one block to many methods, there's no need to the same block over and over again, because you can make Proc. Proc saves your block to variable, and gives you an opportunity to manipulate with it like with object.

proc_name = Proc.new { your block here }

func1(&proc_name)
func2 &proc_name
You must pass proc to method with & symbol.

Also you can convert symbols to procs using magic & symbol:
(function .map and .collect runs through all the elements in array)
number = [0,1,2]
number.map(&:to_s) // This will convert 0,1,2 to strings
Lambda:Lambdas are almost the same as procs, with the exception of syntax and few behavioral features.

Proc.new { puts "Hello" }
same as
lambda { puts "Hello!" }
Differencies between lambdas and procs:
1. Lambda checks the number of arguments passed to it, while a proc does not. Lambda will throw an error, proc will assign nil to all unassigned arguments.
2.When a lambda returns, it passes control back to the calling method; when a proc returns, it returns immediately, whithout passing control back.

// Outputs "Hello world!"
def A
  h = Proc.new { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

// Outputs "Hello galaxy!"
def B
  h = lambda { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

Infromation from: www.codeacademy.com

Tuesday, November 5, 2013

Ruby interesting things

puts "Hello" if statement == true // This construction works fine, and puts "Hello" if statement equals to true, but construction if statement == true puts "Hello" will cause an error.

26.respond_to?(:next)   // .next() method will return next value to 26. This contruction will return true, because method next can be applied to 26 (.next method will return 27, by the way)

5.times {} // Will run block 5 times

5.upto(10) { |num| puts num } // Will return 5 6 7 8 9 10 on each line (.downto(n) works other way round)

[1,2,3]  << 4 // Will return [1,2,3,4] also works on strings "Andy" << " Marrel" -> "Andy Marrel"

"String " + 26 // Will cause error, because you neet to cast 26 to string, but you can apply string interpolation, so the string will be ok -> "String #{26}"

Information from: www.codeacademy.com

Friday, October 25, 2013

Github cheat sheet

HEAD - pointer to latest commit
git diff <source_branch> <target_branch> - changes between 2 branches
git diff HEAD - changes with latest commit
git diff --staged - diff with staged files
git reset <file> - unstage <file>

Branch - the copy of project
git branch <branch_name> - creates branch <branch_name>
git checkout <branch_name> - switch branch to <branch_name>
git branch -d <branch_name> - delete <branch_name> branch

Merge - copy changes to current branch
git checkout <branch_name> - now we'r in the <branch name>
git merge <other_branch_name> - merge <other_branch_name> changes into <branch_name>

Update your local copy to latest:
git pull
Creating tag:
Tag is a software release (like in SVN)
git tag 1.0.0 b01a419cff
The b01a419cff is a commit id.

If something went wrong, and you need to replace changes:
git checkout -- <file_name> - replaces changes with the last content in HEAD.

If you want to drop all local changes and commits:
You need to fetch the latest history from remote repo and point local master branch at it
git fetch origin
git --hard origin/master

How git works:
1. Changes in local repo
git add --all
2. Changes in Index (staged)
git commit -m "Adding all files"
3. Changes in HEAD (commited, but still not in remote repo)
git push origin <branch_name> (git push origin master)
4. Now changes pushed to remote repository (master or other branch)

Usefull commands: 
Launches git GUI:

gitk

Information from:
http://try.github.io
http://rogerdudler.github.io/git-guide/

Wednesday, October 23, 2013

CSS only for IE 10/11

http://artkiev.com/blog/hacks-for-ie10-ie11.htm - вот до чего приходится извращаться в борьбе против маразма Майкрософта!

Раньше было проще - http://polezniy.com/2011/02/25/kak-pisat-sss-dlya-ie-ili-boremsya-s-gavnobrauzerom/ - можно было легко задать стили только для Интернет Эксплорера. Но с 10-й версии они там, видите ли, решили не давать больше разработчикам возможности делать свои сайты так, чтобы они во всех браузерах смотрелись адекватно. Возомнили себя богами - типа, у нас самый правильный браузер, и нехай другие браузеростроители подгоняют свои творения (Гугл Хром, Мозиллуа, Оперу и т.д.) под то, что вытворяет Интернет Эксплорер. Во наглость!

Но, как говорится, на всякий хитрый болт завсегда найдётся не менее хитрая гайка, и умельцы придумали даже несколько хаков, как обойти защиту и всё-таки иметь возможность прописывать для IE10 и IE11 свои собственные стили. О чём и написано по первой приведённой мною ссылке. Во как!
Текст не мой :)

Tuesday, October 22, 2013

Regular expression: password

 Password 8-16 characters words and number required!

/(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,16})$/

Saturday, October 12, 2013

Symfony 2 - Работа с ресурсами (CSS, JS, картинки)

UPDATE 3
Assetic manager очень глючно работает под виндоус. То генерирует файлы, то перестаёт это делать.


UPDATE Symfony 2.3

Добавляем ресурсы используя ассетик мэнеджер.
1. Ложим необходимые файлы в наш бандл (прим. AmAppBundle) по адресу: AmAppBundle/resources/public/css|js
2. Меняем в app/config.yml следующую строку:
assetic:
    bundles:        [ AmAppBundle ]
3. В шаблоне прописываем наши ксс/йс файлы:
        {% javascripts
            '@AMAppBundle/Resources/public/js/jquery-2.0.3.min.js'
            '@AMAppBundle/Resources/public/js/bootstrap.min.js'
        %}
            <script type="text/javascript" src="{{ asset_url }}"></script>
        {% endjavascripts %}
        {% stylesheets filter='cssrewrite'
            '@AMAppBundle/Resources/public/css/bootstrap.min.css'
            '@AMAppBundle/Resources/public/css/bootstrap-theme.min.css'
        %}
            <link rel="stylesheet" href="{{ asset_url }}" />
        {% endstylesheets %}
4. Пишем в cmd команду: php app/console assetic:dump --env=prod --no-debug (При добавлении новых файлов всегда следует применять эту команду. Как я понял, она генерит файлы для продакшена. Все скрипты генерятся в один файл (сжимаются для повышения производительности). Тоже самое проихсодит с ксс файлами.)
5. Пишем в cmd команду: php app/console cache:clear --env=prod --no-debug

У меня то работало, то не работало. Иногда всё было впорядке на деве, но продакшн отказывался генерить ксс и/или джс файлы.

Старый пост:

Ложим все необходимые ресурсы в папку бандла:
Symfony\src\bundlenamespace\bundlename\Resources\public\
 После выполяем команду, чтобы ресурсы были скопированы в директорию веб (к чему все эти трудности?) web - директория
$ php app/console assets:install web
Далее непосредственно в представлениях можно будет получить доступ к ресурсу следующим образом:
Twig:
<script src="{{ asset('bundles/bundlename/js/jquery.js') }}">

Также можно ложить фаилы в директорию Symfony/web/, откуда через команду {{ asset('file.css') }} можно получить к ним доступ.

Wednesday, October 2, 2013

Ruby first

Before i'll start learning ruby on rails framework, i'm going to learn some basics of ruby language.

Variables:

hello_world = "";
variable = 10;

Methods:

def method_name
  return "Something";
end

def method_name(arg1, arg2)
  puts arg1.to_s + " " + arg2.to_s;
end

Classes:

class ClassName
  // Constructor
  def initialize
    @price = 30
  end

  // Variable @price and getter of price
  def price
    @price
  end

  // Setter of price.
  def price=(value)
    @price = value
  end
end

vari = ClassName.new;
puts vari.price; // Prints 30
vari.price = 10; // Same as vari.price=(10)
puts vari.price; // Prints 10

class ClassName
  attr_reader :price; // Same as getter. attr_reader :price, :weight, :lol;
  attr_writer :price;  // Same as setter
  //attr_accessor :price; // This method creates getters and setters together.
end

Anonymous functions (blocks)

yield :)

Tuesday, October 1, 2013

Ruby on Rails (novice)

Установить ноде.жиесть т.к. могут возникнуть ошибки.
Создание каркаса (модель вид и контроллер) одной командой:  rails generate scaffold Product title:string description:string price:decimal image_url:string

Данная команда создаёт модель, различные виды, контроллер, миграцию и т.д. Далее можно отредактировать миграцию (db/migrate/TIMESTAMP_migration.rb), которая впоследствии внесёт изменения в нашу бд через команду (rake db:migrate - вносит изменения в бд из миграций, которые ещё не были задействованы)

Удалить каркас можно командой: rails destroy scaffold Product

Sunday, September 29, 2013

Installing Ruby + Rails on Windows 8 x64

1. Download and install Rubyinstaller (Ruby 2.0.0-p247 (x64) for me, you can try another version) from http://rubyinstaller.org/downloads/
2. Download and install Ruby Dev Kit (DevKit-mingw64-64-4.7.2-20130224-1432-sfx.exe for me) from http://rubyinstaller.org/downloads/

You can type in cmd or in cmd for ruby command "ruby --version" to check your ruby version.
Also you can check already installed gems by typing: "gem list --local" or "gem list --local rails" to check if rails already installed (for me it wasn't).

NB! You may need to configure your RubyDevKit to run "gem install rails". First of all you need to cd in command prompt to your rubydevkit root; then you need to run those cmds:
ruby dk.rb init
ruby dk.rb install

3. In cmd (or cmd for ruby) type "gem install rails"

After rails was installed, we need to install Sqlite 3 (the most difficult part of installation ^^), because rails use it as a default db engine. The problem is that we need to compile sqlite from source codes manually.
Now we will be using instructions, that was written by "paulwis" in this topic  https://github.com/luislavena/sqlite3-ruby/issues/82.
Also thanks to this topic: http://stackoverflow.com/questions/15480381/how-do-i-install-sqlite3-for-ruby-on-windows

4. Download source files of SQLite (sqlite-autoconf-3080002.tar.gz) and extract it somwhere ("C:/Sqlite/src/" for example.)
5. Open msys.bat file from RubyDevKit folder and change location using "cd" command to your sqlite source dir (for me it was "cd /C:/Sqlite/src/")
6. Run command "./configure"
7. Run command "make"
8. Run command "make install"
9. Now you need to install sqlite gem. Run command
"gem install sqlite3 --platform=ruby -- --with-sqlite3-include=[path\to\sqlite3.h] --with-sqlite3-lib=[path\to\sqlite3.o]"
for me it was:
"gem install sqlite3 --platform=ruby -- --with-sqlite3-include=/C:/Sqlite/src --with-sqlite3-lib=/C:/Sqlite/src/.libs/"
10. By the end you can check Gemfile.lock (in your rails application), if your version is correct. Make sure, that sqlite points to right version of ruby. Sometimes it needs to be changed for example from "sqlite3 (1.3.7-x86-mingw32)" to "sqlite3 (1.3.7-x64-mingw32)" or "sqlite3 (1.3.7)".

Now we can check our rails application. If it was not created yet, open command prompt or cmd for ruby, run "cd" to your applications folder (it can be any folder you prefer, f.e. "C:/MyRailsApps/" so you will run in cmd "cd C:/MyRailsApps/"). After run "rails new Hello_world" to create your Hello_world app. Than "cd Hello_world" and run "rails server". If all was ok, you can look at your app here: http://localhost:3000

Wednesday, September 18, 2013

MySQL некоторые правила оптимизации

Engine:
InnoDB / XtraDB
Настройки:
  • query_cache_size = Размер кэша для запросов. Дать как можно больше оперативной памяти (серверные машины 50-75%, обычные компьютеры 25-50%)
  • innodb_log_file_size = 128/256Mb
  • innodb_log_buffer_suze = 4Mb
  • innodb_flush_log_at_trx_commit = 2 (Данные пишутся в буфер и записываются каждую секунду на диск.)
  • innodb_thread_concurrency=8
  • innodb_flush_method=O_DIRECT (Avoid double buffering)
  • innodb_file_per_table (Не ставить, если очень много таблиц)
http://mysql-tuner.pl
http://tuning-primer.sh
http://maatkit.org

link: http://www.youtube.com/watch?v=2FPvuhRGKV0

Sunday, September 15, 2013

Linux Apache Mysql Php (LAMP) + phpmyadmin

sudo apt-get update
sudo apt-get install apache2
sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
sudo mysql_install_db -> activate mysql
sudo /usr/bin/mysql_secure_installation -> installation of mysql
sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
sudo vim /etc/apache2/mods-enabled/dir.conf -> add index.php after DirectoryIndex
apt-cache search php5- -> all php5 extensions
sudo apt-get install php5-curl php5-gd -> install extensions

sudo apt-get install phpmyadmiin
sudo vim /etc/apache2/apache2.conf -> add line Include /etc/phpmyadmin/apache.conf
sudo service apache2 restart


source files: /var/www

Friday, September 13, 2013

Ubuntu server terminal cmds

ls / ll - list
pwd - current directory
cd ~ ; cd / change dir to root or home
cp <file> <new_file> - copy file
mv <file> <new_file_name> - rename file
rm <file> remove (rm -Rf *)

скрытые файлы в линукс - это файлы, которые начинаются с точки(.)
--help флаг документации
Короткие флаги устанавливаются с одной чертой и могут ставится под ряд (-l, -la)
Длинные флаги (более 1 символа) устанавливаются с двумя черточками --help

-rwxrwxrwx root root = -rwx / rwx / rwx root (владелец) root (группа)
1-ые 3 rwx- права для владельца фаила
2-ые 3 rwx- права для пользователей группы
3-ие 3 rwx- права для всех остальных польз.

r - читать
w - удалять, переименовать и т.д.
x - запустить фаил

  1. 4 = r (Read)
  2. 2 = w (Write)
  3. 1 = x (eXecute)

sudo su root - сменить пользователя на root

cat ~/.bashrc - vyvodit ves' fail bashrc v terminal
cat ~/.bashrc | grep "alias" - vyvodit tolko stroki, svjazannye so slovom "alias"
cat ~/.bashrc |
vim ~/.bashrc - otkryvaet fail v tekstovom redaktore vim
vim: :q! - vyxod bez soxranenija, :wq vqxod s soxraneniem
source ~/.bashrc - perezagruzka faila (chtoby deistvija vstupili v silu)

http://oliverdavies.co.uk/blog/2011/10/install-and-configure-subversion-svn-server-ubuntu

Wednesday, September 11, 2013

SVN

svn commit --message "Message"

svn revert <file> - Возвращает фаил к исходному состоянию текущей ревизии.

svn status

svn diff

{

svn diff — сравнить рабочие файлы с последней ревизией,

svn diff index.html — сравнить локальный файл index.html с последней ревизией этого файла в репозитории,

svn diff -r 9 — сравнить все локальные файлы с ревизией номер 9,

svn diff -r 9 index.html — сравнить локальный файл index.html с ревизией номер 9,

svn diff -r 8:9 index.html — сравнить файл index.html ревизии 9 с этим же файлом, но ревизии 8 в репозитории.

}

svn log -r 1:5

" -r == --revision "

svn add --force <directory>

svn update


Trunk - девелопмент, обычная полоса разработки.
Branch - ответвление, точная копия проекта на момент ревизии Н, поддаётся изменениям как и транк.
Tag - ответвление, точная копия проекта на момент ревизии Н, НЕ поддаётся изменениям.


svn copy (URL сервера)/(имя проекта)/trunk (URL сервера)/(имя проекта)/branches/(имя ветки) -m "Комментарий"
svn copy (URL сервера)/(имя проекта)/trunk (URL сервера)/(имя проекта)/tags/(имя тега) -m "Комментарий"


cd .../branches/r001/

svn diff -r 11:12 https://subversion.assembla.com/svn/andys-project/trunk -> 11 rev. брэнч (сравниваем брэнч с последним коммитом на транке)

svn merge -r 11:12 https://subversion.assembla.com/svn/andys-project/trunk -> Вносим изменения в ветку, соответствующие последней ревизии транка

svn commit -m "Merge"





https://subversion.assembla.com/svn/andys-project/

Источник: http://svnhowto.com

Wednesday, September 4, 2013

Starting selenium server

1. Download latest Java SE from http://java.sun.com/ and install
2. Download latest version of Selenium RC from and extract
3. Create a folder named Selenium at C:\Program Files\Java\jdk1.6.0_03\bin
4. Copy all files under Selenium-server-0.9.2 which you will find in the extracted folder and paste in the newly created folder
5. From Command prompt run the following commands:
cd \
cd C:\PROGRA~1\Java\jdk1.7.0_21\bin
java -jar .\Selenium\selenium-server-standalone-2.35.0.jar -interactive
 
If you see the following messages at the end of the console, you are quite confirm that the Selenium server is running fine:
Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http:/
/www.yahoo.com)

Monday, June 17, 2013

Symfony 2 - Doctrine

Создаётся БД с названием из файла настроек параметров (Symfony/app/config/parameters.yml). В этом же файле необходимо настроить параметры подключения к БД
$ php app/console doctrine:database:create
Создаём класс-сущность для работы с БД. Поле id(AI) создаётся автоматически
$ php app/console doctrine:generate:entity --entity="AcmeStoreBundle:Product" --fields="name:string(255) price:float description:text"
Продолжение позже ...

Wednesday, June 12, 2013

Symfony 2 - Начало

Диплом защитил и впереди у меня целое лето, которое я как всегда могу полностью, пардон, потратить. Технология серверного яваскрипта (ноде) мне понравилась, но углублятся в неё я пока не вижу смысла. В сентябре я уже не поеду в свой колледж, соответственно нужно думать где и как заработать себе на жизнь. Мне нравится веб программирование и я люблю ЯП ПХП, даже не смотря на мнение "элитных" программистов.

Настраиваем хост в апаче (httpd.conf)
<VirtualHost 127.0.0.1:80>
  DocumentRoot "Y:/home/andymarrel.ee/www/Symfony/web" 
  ServerName "andymarrel.ee"
  ServerAlias "andymarrel.ee" "www.andymarrel.ee"
  ScriptAlias /cgi/ "/home/andymarrel.ee/cgi/"
  ScriptAlias /cgi-bin/ "/home/andymarrel.ee/cgi-bin/"
</VirtualHost>


Настраиваем переменные среды виндоус для работы с PHP:
Computer->properties->advanced->env. variables->(System variables/Path)edit->C:\xampp\php (директория с пхп)

Создаём бандл из папки .../www/Symfony/:
$ php app/console generate:bundle --namespace=Acme/HelloBundle --format=yml

Очищаем кэш если не удалось запустить приложение в режиме "продакшн":
$ php app/console cache:clear --env=prod --no-debug

Saturday, June 1, 2013

Я рыцарь без королевства.
Я смерть и гроза драконов.
С оставленным мне в наследство
Ворохом старых законов.

Без замка и без именья.
Коня, что как сажа чёрен.
Такое моё поколенье. *
Наш мир неизбежно болен...

Мы ищем принцесс в подвалах,
Под рокот кислотных песен.
Мечтая с тоской о балах.
Но бал им не интересен.

Не битв, не знамён, не маршей.
Не преданности короне.
Мы просто становимся старше,
Смирясь с пустотой на троне.

Ведь в мире, где правит скупость,
Где похотью выжгли чувства,
Быть рыцарем - это глупость.
А выжить таким, - искусство.

Здесь подлость считают нормой.
А зависть ключом к успеху.
Весь мир стал циничной формой,
Где всё предаётся смеху...

Тут ржут над больным и бедным,
Хромым, стариком, идиотом.
Над чёрным, а так же бледным,
Над храмами, армией, флотом.

Вокруг одни смех и визги!
И лица в оскале злобы.
Слюны ядовитой брызги.
И смайлов кривые скобы...

И только во сне мы видим
Глаза глубиною в море.
Отчаянно смотрят в небо,
Роняя слезу от горя.

В них столько любви и веры,
Что щимит в груди от боли...
И рвутся как струны нервы
От жажды борьбы и воли!

Ты всё бы отдал за имя,
Которым её назвали.
Весь мир бы разрушил, лишь бы
Вы ближе немного стали.

Но утро рывком жестоким
Тебя заберёт обратно...
Вновь делая одиноким.
Так было неоднократно.

Но что-то зажжется в месте,
Где сердце давно стучало.
Багровое пламя чести.
И ты всё начнёшь сначала.

А значит плевать на хохот.
На свист и жестокость слова.
В*доспехи ударов грохот
Тебе принимать не ново.

Лишь крепче ногами в землю!
И щит подними повыше!
Ведь с каждым ударом в сердце
Победа немного ближе.

Так пусть всё вокруг сгорает,
Толпе и врагам в угоду.
Кто многое потеряет,
Взамен обретёт свободу.

Важна лишь любовь и вера!
А их не отнять руками.
И рыцари непобедимы,
Пока не сдадутся сами.

Ещё есть так много мельниц,
Принцесс, заточённых в башнях.
Драконов на горных пиках
И пугал на старых пашнях! *

А значит, вперёд, смелее!
Кто верит, пойдёт с тобою.
Знамёна как пламя реют
В строю за твоей спиною.

...Я рыцарь без королевства.
Не помнящий их законов.
И вместо продажных армий
Я лучше возьму драконов!

(с) Ники.

Украл у DD

Tuesday, May 28, 2013

Node.JS часть 2 - Socket.IO

Пока пишу дипломную работу - нет времени на серьёзное изучение какой-либо области, вот меня и бросает из крайности в крайность. Не успев освоить азы node.js (да чего уж там, не успев освоить даже яваскрипт) я бросился разбираться с сокетами. До этого, кстати, никогда с ними не встречался. Немного кода с комментариями чтобы не забыть:

server.js
// Подключаем модуль сокетов (предварительно скачав необходимый пакет через npm install     // socket.io)
var io = require('socket.io').listen(8080, '127.0.0.1');

// Массив, где будут храниться все текущие сокет соединения.
var sockets = [];

// Отключаем вывод полного лога - пригодится в production'е
io.set('log level', 1);

io.sockets.on('connection', function (socket) {
    sockets.push(socket);
    socket.json.send({'id': socket.id.toString()});
});

client.js
var name;
window.onload = function(){
    socket = io.connect('http://127.0.0.1:8080');

    socket.on('connect', function(){
        socket.on('message', function(msg){
            name = msg.id;
            alert(name);
        })
    });
}

http://hashcode.ru/questions/79766/socket-io-node-js-%D0%BF%D0%B0%D1%80%D1%83-%D0%B2%D0%BE%D0%BF%D1%80%D0%BE%D1%81%D0%BE%D0%B2 

http://socket.io/#how-to-use

Monday, May 27, 2013

Node.JS часть 1 - Знакомство

Впервые скачал и поставил node.js на свой компьютер под win 7 х64. После программирования на PHP чувства неопределённые. В одном, правда, я уверен на все 100 - javascript нужно срочно подтянуть.

Заметки по Node.js:

Подключаем модуль:
require('./module');
Делаем обЬекты модуля видимыми в родительском фаиле:
module.exports = object || exports.object = object || this.object = object
Запускаем веб-сервер:
require('http');
var port = 1337,
      host = '127.0.0.1';
var server = http.createServer(function(request, response){
    console.log('Recieved request: ' + request.url);
    fs.readFile('.' + request.url + '.html', function(error, data){
        if (error){
            fs.readFile('./404.html', function(error, data){
                response.writeHead(404);
                response.end(data);
            })
        } else {
            response.writeHead(200);
            response.end(data);
        }
    });
});
server.listen(port, host, function(){
    console.log("Listening" + host + ":" + port);
});
Установка модуля из менеджера пакетов:
Посмотреть все модули можно на странице: https://npmjs.org
win -> cmd -> cd ./nodeapp -> npm install modulename (установит модуль в папку node_modules)
/.../ -> npm install modulename -g (установит модуль в папку ./nodeapp)
 /.../ -> npm update modulename (обновит модуль до последней версии)