Tuesday, June 7, 2016

Setting up Ubuntu 15.04 + PHP5.6 + Nginx + MySQL + Laravel 5 + npm + Bower + Gulp

  1. install a brand new Ubuntu 15.04 amd64 version
  2. uname -a

     Linux jasler 3.19.0-15-generic #15-Ubuntu SMP Thu Apr 16 23:32:37 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
  3. Setting root password

     sudo passwd root
     >> root
  1. check if apache2 is installed and port 80 is being used

     ps -A | grep apache
     sudo netstat -nlp  | grep 80

remove if installed:

    sudo killall apache2
    sudo apt-get remove apache2
  1. Install Nginx

     sudo apt-get install nginx
     nginx -v
         nginx version: nginx/1.6.2 (Ubuntu)
  2. Install MySQL

     sudo apt-get install mysql-server

It will also install mysql-client and other dependencies in the meantime.

Press Enter on seeing a blank terminal to proceed.

Set the root password root for this time.

  1. Install PHP5 and its extensions

     sudo apt-get install php5 php5-mcrypt php5-gd php5-mysql php5-fpm php5-curl

It also installs apache2 automatically, if it conflicts with nginx, we recommend to remove it.

Check the php and mysql version:

    php -v
    PHP 5.6.4-4ubuntu6.4 (cli) (built: Oct 28 2015 01:21:29) 
    Copyright (c) 1997-2014 The PHP Group
    Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
        with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
 
 
    mysql -p -uroot -v
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 4
    Server version: 5.6.28-0ubuntu0.15.04.1 (Ubuntu)
  1. Install npm

    sudo apt-get install npm
    npm -v
    1.4.21

update within it self:

    sudo npm install -g npm
    /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
    npm@3.8.3 /usr/local/lib/node_modules/npm

Or install this way:

    sudo apt-get install curl
    curl -sL https://deb.nodesource.com/setup > install.sh
    sudo chmod +x install.sh
    sudo ./install.sh
    sudo apt-get install nodejs
    sudo npm install -g npm
  1. Install git

    sudo apt-get install git
  2. Creating dev folder:

change usr to your account

    sudo mkdir /home/wwwroot/
    sudo chown -R [usr].[usr] /home/wwwroot
  • Cloning repo:

    cd /home/wwwroot/
    git clone ssh://git@yourrepo.com:/home/git/yourrepo.git
  • npm install (within vpn)

    sudo npm install
  • Install composer

    cd ~
    php -r "readfile('https://getcomposer.org/installer');" > composer-setup.php
    php composer-setup.php
    sudo mv composer.phar /etc/php5/composer.phar
    sudo chmod +x /etc/php5/composer.phar
    sudo ln -s /etc/php5/composer.phar /usr/bin/composer
  • Install dependencies (vpn):

    cd /home/wwwroot/wwwroot
    composer install
  • Create Database and user, privileges:

    mysql -p -u root
     
    > create database yourdb;
    > create user 'you'@'localhost';
    > set password for you@localhost = PASSWORD('yourpasswd');
    > grant all privileges on yourdb.* to you@localhost;
    > show grants for you@localhost;
    > flush privileges;
  • reset config for environment

    cp .env.example .env
     
    vi .env
     
    DB_HOST=127.0.0.1
    DB_DATABASE=yourdb
    DB_USERNAME=yourame
    DB_PASSWORD=yourpasswd
  • Database migration

    php artisan key:generate
        Application key [s1ZYF0BZydwbRRcrNc58crIC20uwBRzT] set successfully.
    php artisan migrate
    php artisan db:seed
  • Install bower, gulp

    sudo npm install bower -g
    sudo npm install gulp -g
  • Bower install dependencies (no-VPN prefered)

    bower install
  • Generate css, js etc. frontend files

    gulp
     
    gulp watch
  • Make a directory for log files,

    sudo mkdir /home/wwwlogs
    sudo chown www-data.www-data /home/wwwlogs
    1. Reload Nginx

      sudo nginx -s reload

    Check the status:

        sudo service nginx status
    1. Restart Nginx

      sudo service nginx restart

    sudo mv yoursite.conf sites-available/

    C: char* conversion to LPCWSTR

    #include <string.h>
    #include <strlib.h>
    
    LPCWSTR c2ws(const char* s){
     int len;
     int slength = strlen(s)+1;
     len = MultiByteToWideChar(CP_ACP, 0, s, slength, 0, 0);
     wchar_t* buf = new wchar_t[len];
     MultiByteToWideChar(CP_ACP, 0, s, slength, buf, len);
     LPCWSTR r(buf);
     delete[] buf;
     return r;
    }
    

    Friday, May 20, 2016

    Install Pygame for Python 2.7 on Windows 64bit

    Check here for pygame wheel.

    My config goes like C:\WinPython-64bit-2.7.10.3\python-2.7.10.amd64, so it is a pre-compiled python bundle. The official site lists release only for 32-bit. But it gives the link to a wheel link.

    Basically, this is a personal managed wheel list. Choose the follow wheel and install through pip command

    pip install pygame-1.9.2a0-cp27-none-win_amd64.whl

    Refs

    Sunday, April 17, 2016

    Install Intel Dual Band Wireless-AC 3165 wireless driver on Ubuntu 15.04

    Check your wireless card shipped

    sudo update-pciids
    lspci
    

    I have,

    ...
    07:00.0 Network controller: Intel Corporation Intel Dual Band Wireless-AC 3165 Plus Bluetooth (rev 99)
    

    Copy firmware files

    Clone all intel firmwares from OpenELEC repository,

    git clone https://github.com/OpenELEC/iwlwifi-firmware
    cd iwlwifi-firmware/firmware
    sudo cp iwlwifi-7265*  /lib/firmware
    

    Installing Driver

    sudo apt-get install build-essential
    git clone https://git.kernel.org/pub/scm/linux/kernel/git/iwlwifi/backport-iwlwifi.git -b release/LinuxCore14
    cd backport-iwlwifi
    make defconfig-iwlwifi-public
    sed -i 's/CPTCFG_IWLMVM_VENDOR_CMDS=y/# CPTCFG_IWLMVM_VENDOR_CMDS is not set/' .config
    make -j4
    sudo make install
    

    It will output the following,

      Building modules, stage 2.
      MODPOST 6 modules
      INSTALL /home/jasler/backport-iwlwifi/compat/compat.ko
    Can't read private key
      INSTALL /home/jasler/backport-iwlwifi/drivers/net/wireless/iwlwifi/iwlwifi.ko
    Can't read private key
      INSTALL /home/jasler/backport-iwlwifi/drivers/net/wireless/iwlwifi/mvm/iwlmvm.ko
    Can't read private key
      INSTALL /home/jasler/backport-iwlwifi/drivers/net/wireless/iwlwifi/xvt/iwlxvt.ko
    Can't read private key
      INSTALL /home/jasler/backport-iwlwifi/net/mac80211/mac80211.ko
    Can't read private key
      INSTALL /home/jasler/backport-iwlwifi/net/wireless/cfg80211.ko
    Can't read private key
      DEPMOD  3.19.0-58-generic
    depmod will prefer updates/ over kernel/ -- OK!
    Note:
    You may or may not need to update your initramfs, you should if
    any of the modules installed are part of your initramfs. To add
    support for your distribution to do this automatically send a
    patch against "update-initramfs.sh". If your distribution does not
    require this send a patch with the '/usr/bin/lsb_release -i -s'
    ("Ubuntu") tag for your distribution to avoid this warning.
    
    Your backported driver modules should be installed now.
    Reboot.
    

    Links

    1. list of intel linux wireless drivers
    2. How can I install intel dual band wireless-ac 3165 drivers
    3. iwlwifi core release
    4. iwlwifi community

    Wednesday, February 17, 2016

    PyInstaller: Tweaking spec file

    Install PyInstaller

    pip install pyinstaller
    

    Generate spec file

    pyinstaller --onefile foo.py
    

    Tweak spec file

                 datas=[("myfile.txt", "."),
                        ("mydb.db", ".")
                 ],
                 hiddenimports=["packaging", "packaging.version", "packaging.specifiers"],
    

    In one-file mode, no COLLECT is called within spec file, so finally there will be only one exe file generated.

    Generate one-file exe

    pyinstaller foo.spec
    

    Saturday, December 26, 2015

    Python, OpenCV: Video Capture and Display

    OpenCV: Video Capture

    import time
    import cv2
    
    video_capture = cv2.VideoCapture(0)
    while True:
        t0=time.time()
        ret, frame = video_capture.read()
        t1=time.time()
        print "passed ", t1-t0, "s"
    
        cv2.imshow('Video', frame)
        #on pressing "q" exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
            
    video_capture.release()
    cv2.destroyAllWindows()  
    

    Frames Per Second Counter

    #test how many frames per second for a webcam
    import time
    import cv2
    
    video_capture = cv2.VideoCapture(1)
    t0 = time.time()
    i=0
    while True:
        ret, frame = video_capture.read()
        print frame.shape
        t = time.time()
        if t-t0 > 1:
            t0=t
            print "frames ",i
            i=0
            
        i+=1    
                        
        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
            
    video_capture.release()
    cv2.destroyAllWindows()   
    

    Wednesday, December 23, 2015

    Python: JSON socket - Server/Client Structure

    JSON Socket Library

    #file:jsonsocket.py
    #https://github.com/mdebbar/jsonsocket
    import json, socket
    
    class Server(object):
      """
      A JSON socket server used to communicate with a JSON socket client. All the
      data is serialized in JSON. How to use it:
    
      server = Server(host, port)
      while True:
        server.accept()
        data = server.recv()
        # shortcut: data = server.accept().recv()
        server.send({'status': 'ok'})
      """
    
      backlog = 5
      client = None
    
      def __init__(self, host, port):
        self.socket = socket.socket()
        self.socket.bind((host, port))
        self.socket.listen(self.backlog)
    
      def __del__(self):
        self.close()
    
      def accept(self):
        # if a client is already connected, disconnect it
        if self.client:
          self.client.close()
        self.client, self.client_addr = self.socket.accept()
        return self
    
      def send(self, data):
        if not self.client:
          raise Exception('Cannot send data, no client is connected')
        _send(self.client, data)
        return self
    
      def recv(self):
        if not self.client:
          raise Exception('Cannot receive data, no client is connected')
        return _recv(self.client)
    
      def close(self):
        if self.client:
          self.client.close()
          self.client = None
        if self.socket:
          self.socket.close()
          self.socket = None
    
    
    class Client(object):
      """
      A JSON socket client used to communicate with a JSON socket server. All the
      data is serialized in JSON. How to use it:
    
      data = {
        'name': 'Patrick Jane',
        'age': 45,
        'children': ['Susie', 'Mike', 'Philip']
      }
      client = Client()
      client.connect(host, port)
      client.send(data)
      response = client.recv()
      # or in one line:
      response = Client().connect(host, port).send(data).recv()
      """
    
      socket = None
    
      def __del__(self):
        self.close()
    
      def connect(self, host, port):
        self.socket = socket.socket()
        self.socket.connect((host, port))
        return self
    
      def send(self, data):
        if not self.socket:
          raise Exception('You have to connect first before sending data')
        _send(self.socket, data)
        return self
    
      def recv(self):
        if not self.socket:
          raise Exception('You have to connect first before receiving data')
        return _recv(self.socket)
    
      def recv_and_close(self):
        data = self.recv()
        self.close()
        return data
    
      def close(self):
        if self.socket:
          self.socket.close()
          self.socket = None
    
    ## helper functions ##
    
    def _send(socket, data):
      try:
        serialized = json.dumps(data)
      except (TypeError, ValueError), e:
        raise Exception('You can only send JSON-serializable data')
      # send the length of the serialized data first
      socket.send('%d\n' % len(serialized))
      # send the serialized data
      socket.sendall(serialized)
    
    def _recv(socket):
      # read the length of the data, letter by letter until we reach EOL
      length_str = ''
      char = socket.recv(1)
      while char != '\n':
        length_str += char
        char = socket.recv(1)
      total = int(length_str)
      # use a memoryview to receive the data chunk by chunk efficiently
      view = memoryview(bytearray(total))
      next_offset = 0
      while total - next_offset > 0:
        recv_size = socket.recv_into(view[next_offset:], total - next_offset)
        next_offset += recv_size
      try:
        deserialized = json.loads(view.tobytes())
      except (TypeError, ValueError), e:
        raise Exception('Data received was not in JSON format')
      return deserialized
    

    Server

    #file:server.py
    from jsonsocket import Server
    
    host = 'LOCALHOST'
    port = 8080
    
    server = Server(host, port)
    
    while True:
        server.accept()
        data = server.recv()
        server.send({"response":data})
    
    server.close()
    

    Client

    #file:client.py
    from jsonsocket import Client
    import time
    
    host = 'LOCALHOST'
    port = 8080
    
    i=1
    while True:
        client = Client()
        client.connect(host, port).send({'test':i})
        i+=1
        response = client.recv()
        print response
        client.close()
        time.sleep(1)