Qt & Python

PyQt Startup

Brief
  • PyQt is a GUI widgets toolkit, a python interface for Qt.
  • Qt is cross-platform GUI library
Instalations

First, Make sure python is installed on your system.
Then install pyqt as follows,

$ sudo apt-get install python-qt4

It’s better to use

$ sudo apt-get install pyqt4-dev-tools

which include pyuic4, as needed later on.

Also we need qt4-designer to design interface, (as of now, we will create just a simple window). Install it using..

$ sudo apt-get install qt4-designer
What to do…

Open qt4-designer from dash or from terminal by typing qt4-designer.
Create a simple main window and save the ui with the name ui.ui
Now in terminal use the following command in the same dir as of ui.ui file.

$ pyuic4 -x ui.ui -o ui.py

As a result a file named ui.py will be generated which can be executed.

Execute
$ python3 ui.py
Result

And you should see a window.

Python tkinter

Python with tkinter – Startup

Env : Linux

Install python3
$ sudo apt-get install python3
$ sudo apt-get install python3-pip
Code

hello.py

#!usr/bin/env python3

from tkinter import *
def main():
    window = Tk()
    window.title("welcome")
    window.minsize(width=300, height=300)
    button = Button(window,text="Click Me!")
    button.pack()
    window.mainloop()
if __name__ == "__main__":
    main()
Execute
$ python3 hello.py

Kernel in brief

Kernel

  • is a piece of software that, roughly speaking, provides a layer b/w hardware and the application programs running on a computer.

Usage of kernel

User space Kernel space
(the system calls) fork(),wait(), exit()
socket(),bind(),connect(),accept(),listen() The sockets interface -> network card
open(),close(),read(),write() -> disc drive, pen drive, harddrive

The kernel uses system calls such as ‘read’ and ‘write’ to provide abstraction of your hardware.

Here’s a short program in c that opens a file and copies its content to standard output.

#include <fcntl.h>
int main(){
    int fd,count; char buf[1000];
    fd = open("mydata", O_RDONLY);
    count = read(fd,buf,1000);
    write(1,buf,count);
    close(fd);
}

Three Js Startup

Three.js first example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Screen</title>
    https://cdnjs.cloudflare.com/ajax/libs/three.js/r79/three.min.js
</head>
<style>
    body { margin: 0; }
    canvas { width: 100%; height: 100% }
</style>

window.document.onreadystatechange = function(){

    //renderer just like projector
    var renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myCanvas'),antialias:true});
    renderer.setClearColor(0x00ff00);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth,window.innerHeight);

    //camera
    var camera = new THREE.PerspectiveCamera(35,window.innerWidth/window.innerHeight,0.1,3000);

    //the actual scene
    var scene = new THREE.Scene();

    var light = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(light);
    var light1 = new THREE.PointLight(0xffffff, 0.5);
    scene.add(light1);

    var geometry = new THREE.CubeGeometry(100,100,100);
    var material = new THREE.MeshLambertMaterial({color : 0xfff3ff});
    var mesh = new THREE.Mesh(geometry,material);

    mesh.position.set(0,0,-1000);
    scene.add(mesh);

    requestAnimationFrame(render);

    function render(){
        mesh.rotation.x += 0.01;
        mesh.rotation.y += 0.01;
        renderer.render(scene,camera);  
        requestAnimationFrame(render);
    }
}

<body>
    <canvas id="myCanvas"></canvas>
</body>
</html>

 

Yii2 Startup

Yii2 startup

Phase#1

Here we are getting started with yii2 framework which is exciting to learn and implement. Lets get started with it. First thing is to prepare our local environment to use yii2.

  • Download the advanced template from here yii. (currently : yii-advanced-app-2.0.9.tar)
  • After download extract it in the document root of your server. For eg. htdocs of your apache server.
  • After extraction go to the terminal (ctrl alt t (ubuntu) ) and navigate to the root directory of the project ( i.e advanced) and execute the init file like this : sudo ./init
  • Chose the development environment which will set the permission of the files/folder accordingly.
  • There are two modules : frontend and backend, frontend used for normal user and backend used for admin users. Each of these has their own mvc functionality separated from each other.
  • If we look in backend directory we will find the following directories :
    • assets : this contains web accessible source files like css,js,images etc
    • config : this contains configuration files
    • controllers : contains controller part of backend mvc module
    • models : contains model part of backend mvc module
    • runtime : contains debuging data and log
    • views : contains views part of backend mvc module
    • web : contains public files accessible on web

Above similar directories are also present in frontend module.

Static application structure is illustrated by following image

There’s another folder which is common module also named common which contains following directories :

  • config : contains common config files
  • mail : contains mail layouts etc
  • modles: contains common modles
  • widgets: contains application widgets (related to views)

    Another folder which is entirely dedicated to console applications and terminal application of yii. These contains migrations, models, runtime and config directories. Other folders like vendor, environments etc are supporting part of yii framework.

Phase#2

Basic Route

Simple route in yii for controller to its action is given by (for eg) :
//localhost/advanced/frontend/web/index.php?r=site/index
This will redirect to SiteController then its action actionIndex() defined as function.

Gii

If we are in development environment we can use yii’s gii tool to create controllers, controllers with CRUD, models and other supported entities with its gui interface.
This tool can be access by using following url :
//localhost/advanced/frontend/web/index.php?r=gii

If it is not installed in yii2 then you might have to get it through composer install and update commands.

CMD Tools

We can also use yii’s command line tool to generate migrations, models and controllers along with cache management, assets compression etc functionalties.
To see the command help use the following in the project directory in relation to the contextual command like,
~/advanced> php yii help migrate

Phase#3

Active Records

link

Read

Find one record

    $id = 1;
    $user = User::findOne($id);

Get All records

    $user = User::find()->all();

Get record on condition

    $user = User::find()
            ->where([
                    'name' => 'User1'
                    ])->all();

Save

$user = new User(['name' => 'User1']);
$user->save();

Phase#4

Models

link

Model Relations

User has one Place

User.php

public function getPlaces(){
    return $this->has(Place::className(),['id' => 'place_id']);
}

Place.php

public function getUser(){
    return $this->hasOne(User::className(),['id' => 'user_id']);
}

User has place through user_place table

user

id name
1 tester

user_table

user_id place_id
1 2

place

id place_name
1 place1
2 place2
public function getPlaces(){
    return $this->hasMany(Place::className(),['id' => 'place_id'])
    ->viaTable('user_place', ['user_id' => 'id']);
}

Misc

Creating new migration

> php yii migrate/create create_tester_table

Using global transaction
    <?php
        //....        
        $transaction = Yii::$app->db->beginTransaction();

try{
//save data here
//case : succeed
$transaction->commit();
} catch (e){
//case : failed
$transaction->rollback();
}
//….

?>

Using Url helper
    <?= \yii\helpers\Url::toRoute('site/index') ?>
    //or
    <?= \yii\helpers\Url::to('site/index') ?>
Routing in case of camelCase actions

Suppose we have action actionGetUser(), then the route will be formated with hyphen as under,

    use \yii\helpers\Url;
    <?= Url::toRoute('site/get-user') ?>

Objective :

To learn the integration of node.js socket.io module with laravel with the use of redis to create real time functionalities.


Level1

Create new laravel application

> laravel new laravelnode

Install socket.io in the same laravel directory

> npm install socket.io

Create a new directory with name “ws_server”

> mkdir ws_server

Create a new file with the name “server.js”

> subl server.js

Write the server.js script and save ./laravelnode/ws_server/server.js

var socket = require('socket.io')(6001);
//handle new connection
io.on('connection',function(socket){
    console.log('New Connection \n' + socket.id);
    socket.send('You are connected to the server');
});

Now open the default welcome view and add the following js dependencies either cdn or download. welcome.blade.php

...
<script src="jquery.js"></script>
<script src="socket.io.js"></script>
...

Add the following script to connect to server via socket welcome.blade.php

<script>
var socket = new io(':6001');
socket.on('message',function(data){
        console.log('Server said: ' + data);
});
</script>

Now in cli run the laravel app

> php artisan serve

Run the node server

> node ws_server/server.js

Open the localhost:8000 in browser. If there’s no error, you should see the message in your browser’s console : Server said: You are connected to the server

Condition on related model in laravel

Situation

We want to fetch a model along with its related model based on condition on the related model.

Synatax and Flow

$result = User::where('name', $name)->whereHas('experience', function($query) use ($experience_required){
    $query->where('total_exp',$experience_required);
});

Wonder of union

Scenario

We have to find users with certain properties like email address, designation, country, city etc. Lets say we have these cases ..
1) We have to find users with given one parameter for eg. email address
2) We have to find users with given two parameter for eg. designation and country
3) We have to find users with given three parameter for eg. email address, designation and country
4) We have to find users with given four parameter for eg. email address, designation country and city
and so on according to no. of user’s properties

Another thing we need to care about is — the parameter that tells us that how many parameters – exacty – should be matched with the selected users viz factors.

Problem

If four parameters are given and factors needed to be matched are 2. So here we are with these combinations…
1) Users with matched email and designation both
2) Users with matched designation and country both
3) Users with matched country and city both
4) Users with matched city and email both

5) Users with matched email and country both

6) Users with matched designation and city both

etc…

Approach

We cant write query for every combination when the parameters and factors increases in number. So what’s the easy way to do that, the answer lies in sql’s UNION ALL

SELECT * FROM `users` WHERE `email` = '$email'
UNION ALL
SELECT * FROM `users` WHERE `designation` = '$designation'
UNION ALL
SELECT * FROM `users` WHERE `country` = '$country'
UNION ALL
SELECT * FROM `users` WHERE `city` = '$city'

The above query will unite the result of individual query of four parameters with the repeated row as well.

Now, how to know the factors matched by individual row?

Take a case when above query will have a duplicate of a row which matched two parameters. All we need to do is retrive the count through grouping the similar rows. Lets do that…

SELECT id,username count(*) AS factors FROM (
SELECT * FROM `users` WHERE `email` = '$email'
UNION ALL
SELECT * FROM `users` WHERE `designation` = '$designation'
UNION ALL
SELECT * FROM `users` WHERE `country` = '$country'
UNION ALL
SELECT * FROM `users` WHERE `city` = '$city') AS united_results GROUP BY `id`;

It will generate table similar to the following, that says id = 1 has four parameters that are matched while id = 4 has only one parameter matched.

id username factors
1 Perfc 4
4 Terrw 1