Thursday, November 9, 2017

MongoDB Search Collections

Document:
{
    "_id" : ObjectId("5a046e1151c456a18a6146f5"),
    "name" : [ 
        "bmw", 
        "bav motor wagen"
    ],
    "class" : {
        "usa" : "suv",
        "europe" : "compact"
    },
    "speed" : [ 
        {"mph" : 100}, 
        {"kph" : 120}
    ]
}
search query width and criteria, array match, object match
db.getCollection('cars').find({
    "name":"bmw",
    "class.usa": "suv",
    $and :[ 
        {"speed.0.mph": { $eq:100 }}, 
        {"speed.1.kph": { $eq:120 }} 
   ]
}
)

Friday, November 3, 2017

Install and Test Symfony Application with Node.JS

This will automate the process. You only need to enter passwords for mysql root or other mysql user and database name in install node.
To speed up symfony instalation and testing use package.json
{
  "scripts":{
    "install":"git clone https://github.com/nikola-bodrozic/sym28-patterns sym28 && cd sym28 && composer install && mysql -u root -p test < database.sql",
    "test":"cd sym28 && php phpunit-5.7.phar -c app/"
  }
}

in console run

npm install
npm test

Saturday, October 21, 2017

Run Local Node.JS Dependancies

From Command Line


Install dependency locally

npm install live-server

Create folder public with index.html and file called run-server.js. Here's the structure:

node_modules/
public/
   index.html
run-server.js

Content of run-server.js:

var liveServer = require("live-server");

var params = {
 port: 8181, // Set the server port. Defaults to 8080.
 host: "0.0.0.0", // Set the address to bind to
 root: "./public", // Set root directory that's being served. Defaults to cwd.
 open: true, // When false, it won't load your browser by default.
 logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
};

liveServer.start(params);

in console run live-server

node run-server.js
or on Linux
node node_modules/.bin/live-server --open=public/

Using package.json

in console
npm init
npm install -D live-server
npm install --save cowsay

this will generate file package.json:
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cowsay -b mooooooooo >> index.html && live-server --port=8085"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "live-server": "^1.2.0"
  },
  "dependencies": {
    "cowsay": "^1.2.1"
  }
}

to create index.html and run server
npm test

if you want to do clone a git repo and run in in live-server replace yellow line with:

"test": "git clone https://github.com/nikola-bodrozic/Bootstrap-Boilerplate-v3.3.7.git tb337 && live-server --watch=tb337 --open=tb337 --ignore=tb337/.git"

this will watch for file changes in tb337 folder but not in tb337/.git folder

another example
{
  "scripts": {
    "less-gen": "lessc -l public/css/style.less && lessc public/css/style.less public/css/style.css && exit 0",
    "lint-css": "csslint --ignore=ids,order-alphabetical  public/css && exit 0",
    "lint-js": "eslint public/js && exit 0",
    "test": "node run-w3cvalid.js && npm run less-gen && npm run lint-css && npm run lint-js && echo \"Tests finished\" && exit 0",
    "start": "node run-server.js"
  },
  "dependencies": {
    "csslint": "^1.0.5",
    "html-validator": "^2.2.3",
    "less": "^3.0.0-alpha.3",
    "live-server": "^1.2.0"
  },
  "devDependencies": {
    "eslint": "^4.10.0"
  }
}
Inside script.test and script.start we can run js files.

Friday, October 13, 2017

Usefull Shell Commands

Pack folder and backup database

Backup folder. Run as sudo, other users will change the original permissions
tar -zcf wp03.tar.gz wp03/
Backup database
mysqldump -u root -p -C albert > albert.sql.tgz

Create user with home folder, shell & password

sudo useradd -m -d /home/mike -s /bin/bash -c "Mike" -U mike
sudo passwd mike
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully

Numeric permissions in console

$ ls -la | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o ",k);print}'
775 drwxrwxr-x  9 3173 3173   4096 Oct 12 20:01 .
755 drwxr-xr-x  4 3173 3173   4096 Oct 12 21:54 ..
755 drwxr-xr-x  6 3173 3173   4096 Oct 12 19:08 app
755 drwxr-xr-x  2 3173 3173   4096 Oct  9 15:46 bin
644 -rw-r--r--  1 3173 3173   2111 Mar 11  2017 composer.json
664 -rw-rw-r--  1 3173 3173 102342 Oct 12 19:08 composer.lock

Search file names and file content

find file that begins with example case insensitive search
find . -iname "example*" -print

finds string `getcol` in js files in current folder and it`s subfolders, print file name, line number and the line
find . -type f -name "*.js" -exec grep -in --with-filename getcol {} \;

Set permissions for files and folders

sudo find /var/www -type d -exec chmod 775 {} \;  # rwxrwxr-x
sudo find /var/www -type f -exec chmod 664 {} \;  # rw-rw-r--

Saturday, October 7, 2017

Symfony 3 run console commands from controller

On shared hosting you don't have access to command line so you can use following script to clear cache:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

// Import the required classed
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;


class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        $kernel = $this->get('kernel');
        $application = new Application($kernel);
        $application->setAutoExit(false);
       
        /*
        // php bin/console doctrine:generate:entities AppBundle:Task
        $input = new ArrayInput(array(
            'command' => 'doctrine:generate:entities',
            'name' => 'AppBundle:Task'
        ));
        */
       
        // php bin/console cache:clear --env=prod --no-warmup
        $input = new ArrayInput(array(
            'command' => 'cache:clear',
            '--env' => 'prod',
            '--no-warmup' => null
        ));
       
        $output = new BufferedOutput();

        $application->run($input, $output);

        // return the output
        $content = $output->fetch();

        // Send the output of the console command as response
        return new Response($content);
    }
}

Thursday, September 21, 2017

Symfony migrations

This short tutorial show how to migrate model and the database in Symfony.

Add property in AppBundle/Entity/User.php

/**
 * @ORM\Column(name="message", type="string", nullable=true)
 */
protected $message;

then in console

php bin/console doctrine:migrations:diff

this will generate file app/DoctrineMigrations/Version20170921225541.php
at this point you still don't have getter and setter for $message nor column message in table.

php bin/console doctrine:migrations:execute 20170921225541 --up

now you have message column in table, but not getter and setter for $message

php bin/console doctrine:generate:entities AppBundle:User

this will create the getter and setter.

The reverse process is:

php bin/console doctrine:migrations:execute 20170921225541 --down

this reverts database table. Remove message property and it's getter and setter. And your code and database are in sync.

Wednesday, June 7, 2017

Post installation tasks on development machine

Compiled Git from source
wget https://github.com/git/git/archive/v2.13.3.zip
unzip v2.13.3.zip
cd git-2.13.3
yum install gcc perl-ExtUtils-MakeMaker
yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
make configure
./configure -prefix=/usr/local
make -prefix=/usr/local install
git --version
yum install git-gui

Git GUI shortcut
[Desktop Entry]
Version=1.0
Type=Application
Name=Git GUI
Comment=A graphical interface to Git
Exec=git gui
Icon=/usr/share/git-gui/lib/git-gui.ico
Path=
Terminal=false
StartupNotify=false

Git branch name in terminal https://goo.gl/cfLRiE

Sublime 3 - TypeScript

Double commander from official package manager

Node & NPM https://goo.gl/UeB8r1

LAMP
sudo apt-get install tasksel
sudo tasksel --new-install

PHP 7 extensions:
search sudo apt-cache search php

Install extensions sudo apt install php7.1-cgi php7.1-cli php7.1-common php7.1-curl php7.1-gd php7.1-json php7.1-opcache php7.1-sqlite3 php7.1-xml

PHPUnit download phar file from official site and run php phpunit-version.phar

grunt npm install -g grunt-cli

bower sudo npm install -g bower

yarn https://yarnpkg.com/lang/en/docs/install/#linux-tab

sudo apt install composer

live-server live reload and file monitoring
  • npm install -g live-server
  • live-server --open=PATH --watch=PATH --ignore=PATH

plain http-server
  • npm install http-server -g
  • http-server -a 127.0.0.1 -p 9001

PHP Built in server
  • php -S localhost:port_number

Selenium IDE for firefox

vscode extensions
  • Angular Essentials - Extension Pack for VS Code by John Papa

Angular CLI -
npm install -g @angular/cli
set as package manager
ng set --global packageManager=yarn

Apache's mod_rewrite on Ubuntu 16.04  https://goo.gl/wp3WBx

Adminer
sudo mkdir /usr/share/adminer
sudo wget "https://github.com/vrana/adminer/releases/download/v4.6.2/adminer-4.6.2-mysql-en.php" -O /usr/share/adminer/latest.php
sudo ln -s /usr/share/adminer/latest.php /usr/share/adminer/adminer.php
echo "Alias /adminer.php /usr/share/adminer/adminer.php" | sudo tee /etc/apache2/conf-available/adminer.conf
sudo a2enconf adminer.conf
sudo service apache2 restart

FTP
yum -y install filezilla

NeteBeans for PHP



Tuesday, May 23, 2017

jQuery AJAX call with JSON

Make AJAX call with jQuery and then receive and parse JSON string.


<html>
<head>
    <title>Making AJAX call with jQuery 3+</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        makeAJAX();

        function makeAJAX() {
            var request = $.ajax({
                url: '/ajax.php',
                method: "GET",
                data: {
                    id: 21,
                    minprice: 10,
                    maxprice: 1000
                },
                beforeSend: function(xhr) {
                    // set security token in AJAX request header
                    // xhr.setRequestHeader('X-Sec-Header','<?php echo $_SESSION["sectok"]; ?>');

                    // show loader
                    //$("#imgload").show();
                }
            });

            request.done(function(msg) {
                console.log(msg.films[0]);
                alert("name " + msg.films[0].name);
            });

            request.fail(function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            });

            request.always(function() {
                // hide loader
                //$("#imgload").hide();
            });
        }
    </script>
</head>
<body>
    <h1>Making AJAX call with jQuery 3+</h1>
    <div id="response"></div>
</body>
</html>


and here's the ajax.php:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json');

$data = array(
 array("id"=>1,"name"=>"Brendan","year"=>1992),
 array("id"=>2,"name"=>"Thane","year"=>1997),
 array("id"=>3,"name"=>"Hoyt","year"=>1994),
 array("id"=>4,"name"=>"Xanthus","year"=>1991),
 array("id"=>5,"name"=>"Francis","year"=>1991),
 array("id"=>6,"name"=>"Plato","year"=>1998),
 array("id"=>7,"name"=>"Sylvester","year"=>1998)
);

 $rarray = array(); 
 $rarray['films'] = $data;
 echo json_encode($rarray);

Sunday, April 23, 2017

Bower workflow

To create bower.json file and place dependencies in it:
bower init 
bower install bootstrap --save
bower install bootstrap-select --save
bower list -p
Push to (remote) repository and make sure that you place bower_components in your .gitignore file.

after checkout on other machine
cd project_name/
bower install
this will download bower components to your working folder