Saturday 30 January 2021

Python Basics

Python Basics 

 Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming.

Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary.

Python is extensible: with C/C++/Java code, and easily embeddable in applications.

Some Python modules are also useful as scripts.

Python source files are treated as encoded in UTF-8.

Start the interpreter and wait for the primary prompt, >>>.

The interpreter acts as a simple calculator. The operators +, -, * and / work just like in most other languages.

Python can also manipulate strings.  They can be enclosed in single quotes (‘) or double quotes (“). 

Simple print command in Python.

print("Hello world")

Math Commands acts like a calculator.

>>> 2 + 2
4

>>> 17 / 3  # classic division returns a float
5.666666666666667

>>> 5 * 3 + 2  # result * divisor + remainder
17

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

If Statement in Python: Below example is asking to input integer value. isdigit() function is checking if provided value in of type int.
Try Except statements are used for catching any exception. It protects any exception if we don't enter any
input.

try:
    x = int(input("Please enter number: "))
    if x.isdigit():
        if x <= 0:
            x = 0
            print('Printing 0 value')
        elif x < 10:
            print('Printing ' + str(x))
        else:
            print('Value is very big')
except:
    print("Please enter valid input")


For Loop Below example printing hexa code of colors by their name in Python.

Install colour package of Python
pip install colour
Ref: https://pypi.org/project/colour/
Converts and manipulates common color representation (RGB, HSL, web, …)
from colour import Color
colors = ['red', 'green', 'white', 'blue']
for c in colors:
    n = Color(c)
    print(c, n.hex)


Fibonacci Series in Python as follows:
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 10:
    print(a)
    a, b = b, a+b

For loop in Python:

a = 0 b = [] for a in range(0, 10): b.append(4 + ((a - 1) * 3)) s = ',' . join(str(c) for c in b) print(s) // print array elements in string


Function in Python:
def parrot(a, b, c):
print(a,b,c)

d = {"a": "this", "b": " is my ", "c": "test"}
parrot(**d)

Saturday 9 January 2021

AWS X-ray Send Traces Lumen

AWS X-ray Test Script in PHP Framework Lumen


I have tested sending traces to AWS X-Ray through API Gateway through Lumen.

I have used below PHP package:

https://packagist.org/packages/pkerrigan/xray

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Support\Response;
use Pkerrigan\Xray\Trace;
use Pkerrigan\Xray\Submission\DaemonSegmentSubmitter;
use Pkerrigan\Xray\Segment;

class TestController extends Controller
{
    /**
     * construct
     */
    public function __construct(Response $response) {
        $this->response = $response;
    }

    /**
     * test xray
     */
    public function xray() {    
      try {  
        if(env('ENABLE_XRAY')) {

              //echo "----Tracing Start 14 ----";

              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-1')
                ->setUrl("[API-1-URL]")
                ->setMethod('GET')
                ->begin();

              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-2')
                ->setUrl("[API-2-URL]")
                ->setMethod('GET')
                ->begin();
                
              Trace::getInstance()
                ->setTraceHeader($_SERVER['HTTP_X_AMZN_TRACE_ID'] ?? null)
                ->setName('api-3')
                ->setUrl("[API-3-URL]")
                ->setMethod('GET')
                ->begin();    
                  
              Trace::getInstance()
              ->getCurrentSegment()
              ->end()
              ->setResponseCode(http_response_code())
              ->submit(new DaemonSegmentSubmitter());
              return $this->response->success(array('xray-res' => 'success'));
          } else {
            return $this->response->success(array('xray-res' => 'no-set'));
          }
        } catch(Exception $e) {
          return $this->response->success(array('xray-res' => $e->getMessage()));
        }
    }
}

Saturday 14 December 2019

GIT Pull Using Nodejs

GIT Pull Using Nodejs

I am sharing my code to take GIT pull through NodeJS. May be this small code can help someone.

// create config module
var config = {};
to_dir_client = "path to folder...";
client_git_repo = "Bitbucket URL... ";

// export config object as a node module
export default config;

/*-----------------------------------------------------------
--- install git repo js file
-----------------------------------------------------------*/
// include modules
import config, { to_dir_client, client_git_repo } from './config';
import gitP from 'simple-git/promise';

// install repo
const git_client = gitP(to_dir_client);
git_client.checkIsRepo()
   .then(isRepo => !isRepo && initialiseClientRepo(git_client))
   .then(() => git_client.pull('origin', 'master'));

// function to add origin
function initialiseClientRepo (git) {
   return git.init()
      .then(() => git.addRemote('origin', client_git_repo))
}

Friday 13 December 2019

SonarQube Scanner Local Windows

SonarQube Scanner Windows

I am sharing my tutorial to describes how to run a Sonar Scanner on Windows machine.

Add the project to SonarQube, In SonarQube, go to






Enter Project Key


Enter Project Key which can be used later to identify the project.




















New project created. 



Download SonarQube Scanner


Windows Installer

















Install SonarQube on Windows














Installation Guide

Go through the installation and running scanner manual online https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/

  My Local Instance

    My test local instance looks like

There is only one file to review t.php















My sonar.json looks like






My sonar-project.properties file looks like:














Running Sonar Scanner CLI





After scanning is done, we can see report in Sonarqube console like below:








Saturday 3 August 2019

Speech to Voice in Website using Javascript

Speech to Voice in Website using Javascript

W3C Community introduced the Web Speech API specification. Its a wonderful feature to introduce voice enabled commands on your website which works in Chrome Browser.

Convert Speech to Text

Below code just convert voice speech to text that you can use to make any search on your website or to navigate to another link on your website. Also you can make simple Bot on your website using this feature.

window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
console.log(window.SpeechRecognition);
if ('SpeechRecognition' in window{
    const recognition = new window.SpeechRecognition();
    recognition.onresult = (event) => {
        let speechToText = event.results[0][0].transcript;
        console.log("speech text", speechToText);
    }

    recognition.start();
    console.log('Ready to receive a command.');
} else {
    alert("speaking not working");
    // speech recognition API not supported
}



Below code is used to output speech on Chrome browser.
speechSynthesis.getVoices(); method is used to get voices from various countries accents.

var m = 'Hi How are you?';
if ('speechSynthesis' in window{
    const msg = new SpeechSynthesisUtterance(m);
    const voices = window.speechSynthesis.getVoices();
    // msg.voice = voices[9];
    //msg.voice = voices[4];
    console.log("speaking: " + m);
}

Sunday 22 July 2018

Progressive App Example

Progressive App Example Add to Home Screen

I am sharing my research on how to allow users to Add Website Icon on mobile device's Homescreen, just like Mobile Apps Icon(works mainly for Android devices).

Reference tutorials code



Create manifest.json at the root of the website

manifest.json
{
    "name": "Example site",
    "short_name": "examplesite",
    "icons": [{
            "src": "images/logo-96x96.png",
            "sizes": "32x32",
            "type": "image/png"
        },
        {
            "src": "images/logo-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "images/logo-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "start_url": "/?utm_source=web_app_manifest",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#000000"
}

Add following code in head part of the HTML of Index page

<meta name="theme-color" content="#000000"/>
<link rel="manifest" href="/manifest.json" />

Add following JS code in the footer of Index page


    if (window.matchMedia('(display-mode: standalone)').matches{

        console.log('display-mode is standalone');
    }

    if (window.navigator.standalone === true{
        console.log('display-mode is standalone');
    }

    window.addEventListener('appinstalled', (evt) => {
        //app.logEvent('a2hs', 'installed');
    });

    let deferredPrompta;

    window.addEventListener('beforeinstallprompt', (e) => {
        // Prevent Chrome 67 and earlier from automatically showing the prompt
        e.preventDefault();
        // Stash the event so it can be triggered later.
        deferredPrompta = e;

        // very important to prompt flyout
        deferredPrompta.prompt();
    });

    if ('serviceWorker' in navigator{
        window.addEventListener('load', function () {
            navigator.serviceWorker.register('/service-worker.js').
            then(function (registration) {
                // Registration was successful
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            }).catch(function (err) {
                // registration failed :(
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }


Finally create service-worker.js at the root of the website

server-worker.js

self.addEventListener('install', function (event) {});
self.addEventListener('activate', function (event) {});
self.addEventListener('fetch', function (event) {});

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...