воскресенье, 25 марта 2012 г.

Доступ на ssh в Ubuntu

Чтобы просмотреть текущий публичный ключ
vi ~/.ssh/id_rsa.pub

Чтобы зайти на ssh под пользователем
ssh -v user@host

понедельник, 12 марта 2012 г.

Работа с git. Создание и удаление веток

1) Посмотреть все ветки
  • git branch
  • git branch -r

2) Удалить ветку на сервере
  • git push origin :crincum_poi

3) Удалить ветку локально
  • git branch -D crincum_poi

4) Создать ветку на сервере
  • git push origin master:crincum_poi
5)  Смерджить ветку таска MAP-23 в текущую ветку проекта crincum
  • git checkout master
  • git merge experimental

6) Процесс создания веток под таск

  • git checkout -b MAP-186  - создаем локальную ветку
  • git branch - проверяем, что переключились на текущую ветку
  • git push origin MAP-186:MAP-186 - пушим origin в новую удаленную ветку. Тем самым создаем ее.
  • Проверяем наличие удаленной ветки git branch -r и Работаем:) 
7) Ошибка refusing to pull with rebase: your working tree is not up-to-date
    .gitignore.: needs update.
     Решение жестко сменить HEAD ветки. Правда могут потеряться какие то изменения, зато pull заработает:)

  • git reset --hard origin/master

    Add arrows to OpenLayers layer.

    I have a task to render a traffic vectors on top map using OpenLayes API.

    As I noticed Yandex maps uses pregenerated tiles and just render png images on top of the base layer.


    The OpenStreetMap based on OpenLayers uses svg (vector graphic) (or canvas) to draw tracks and roads on top of the map. As well as Google Maps.

    To render  arrows firstly we need to find out the direction of arrows. I calculate it at frontend using function calculateAngle. To find out direction we need to have a vector (two points A[x1,y1], B[x2,y2]).

    function calculateAngle(x1, y1, x2, y2){
         var dx = x2 - x1;
         var dy = y2 - y2;
         // Calculates angle between vector and x axis
         var angle2  = Math.atan(dy/dx)*180/Math.PI;

         // Rotates angle according to vector direction
         var angle = getQuadrantAngle(angle, dx, dy);
         return (angle);
    }

    function getQuadrantAngle(angle, dx, dy)
    {
            var qAngle = [-1, 90, -90, 270, 90];
            var Quadrant = 0;
            if(dx>=0 && dy>=0)
                Quadrant = 1;
            else if(dx>=0 && dy<0)
                Quadrant = 4;
            else if(dx<=0 && dy>=0)
                Quadrant = 2;
            else if(dx<=0 && dy<0)
                Quadrant = 3;

            return (-angle + qAngle[Quadrant]);
    }


    After, you need to add arrow image to layer style

    var myMapStyle = {
            cursor     : 'pointer',
            strokeColor: color,
            fillColor  : color,
            fillOpacity: 1,
            rotation:"${angle}", // we take it from feature attribute
            externalGraphic: arrow_url,
            graphicWidth:15,
            graphicHeight: 15,
            graphicYOffset:"${getYOffset}",
            strokeWidth: this.defaults.traffic.strokeWidth
        }


    So the function for adding arrows to layer linesLayer

    /*
     *  Добавляем слой стрелок для дорог
     * @params position - позиция стрелки на сегменте дороги
     * @params uri - адрес файла со списком узлов сегментов разбиения дороги в geojson, тип данных Point
     * */
    Traffic.addArrows = function (linesLayer, param)
    {
        var features = [];

        if(this.utils.isset(param.uri)){
            var geojson = this.getGeoJsonData(param.uri);
            var format = new OpenLayers.Format.GeoJSON({
                'internalProjection': new OpenLayers.Projection("EPSG:900913"),
                'externalProjection': new OpenLayers.Projection("EPSG:4326")
            });

            $(geojson.features).each(function(i,item){
                if(item.properties.arrow == 't')
                {
                    /*dataLayer.addFeatures(format.read(item));*/

                    var ft = format.read(item);
                    var pt = {x1:ft[0].geometry.components[0].x, y1:ft[0].geometry.components[0].y,x2:ft[0].geometry.components[1].x, y2:ft[0].geometry.components[1].y};
                    // Вычисляем положение стрелки на сегменте
                    if(param.position == 'center'){
                        var xm = (pt.x2 + pt.x1)/2;
                        var ym = (pt.y2 + pt.y1)/2;
                    }
                    else{
                        var xm = pt.x1;
                        var ym = pt.y1;
                    }
                    // Вычисляем угол поворота стрелки
                    var dx = pt.x2 - pt.x1;
                    var dy = pt.y2 - pt.y1;
                    var angle  = Math.atan(dy/dx)*180/Math.PI;
                    var angle2 = getQuadrantAngle(angle, dx, dy); // формула angle < 0 ? ((-1)*angle+180) : ((-1)*angle+90);

                    var ftGeomColl = new OpenLayers.Geometry.Collection();

                    // Добавляем вывод стрелок
                    ftGeomColl.addComponent(new OpenLayers.Geometry.Point(xm, ym));

                    var ftColl = new OpenLayers.Feature.Vector();
                    ftColl.geometry = ftGeomColl;
                    ftColl.attributes = {};
                    ftColl.attributes["angle"] = angle2;
                    features.push(ftColl);
                }
            });
        }
        linesLayer.addFeatures(features);
    }



    понедельник, 27 февраля 2012 г.

    PostgreSQL timestamp comparison (сравнение времени)

    The main difference with mySQL is that quotes and double quotes have different meaning. It is very important to put timestamp variable into single quotes. As well as all variables.

    This won't work:
    SELECT *  FROM test WHERE timestamp  < "2012-02-28 10:39:07";


    This will do:
    SELECT *  FROM test WHERE timestamp  < '2012-02-28 10:39:07';

    The rest of comparison syntax is the same as is in mysql.

    среда, 8 февраля 2012 г.

    Настройка push доступа к git (gitorious) по ssh (fatal: protocol error: expected sha/ref)

    Столкнулась с тем, что не смотря на то что спокойно склонировала проект с git'а - сделать push не получалось.

    ssh ключ создала, проверила и добавила на удаленный сервер гита.

    При попытке выполнить push выдавалась ошибка
    sudo@test:/# git push origin my_brunch



    fatal: protocol error: expected sha/ref, got '
    ----------------------------------------------
    The git:// url is read-only. Please see http://git.../project/ for the push url, if you're a committer.
    ----------------------------------------------

    чтобы решить проблему нужно проверить push и fetch urls для удаленного сервера

    sudo@test:/# git remote show origin
    * remote origin
      Fetch URL: git://gitorious.../project/project.git
      Push  URL: git://gitorious.../project/project.git
      HEAD branch: master
      Remote branches:
        my_brunch tracked
        master  tracked
       ....

    "Push  URL: git://g..." - по гит протоколу нет доступа на Push - для этого нужен ssh. Изменим Push  URL c http на ssh (ssh адрес можно посмотреть на удаленном сервере в "Clone & push urls")

    sudo@test:/# git remote set-url origin git@gitorious...:project/project.git

    Проверим, что все заработало

    sudo@test:/# git pull
    ...
    sudo@test:/# git st
    sudo@test:/# git push origin my_brunch

    пятница, 3 июня 2011 г.

    Проверка на главной странице

    is_home() || is_front_page()

    Вставка картинок в wordpress

    // Check if this is a post or page, if it has a thumbnail, and if it's a big one
        if ( is_singular() && current_theme_supports( 'post-thumbnails' ) && has_post_thumbnail( $post->ID ) &&
       ( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&  $image[1] >= HEADER_IMAGE_WIDTH ) :
                            // Houston, we have a new header image!
                            echo get_the_post_thumbnail( $post->ID );
                        elseif ( get_header_image() ) : ?>
                            <img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
                        <?php endif; ?>