Vagrantfile for Docker

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "geerlingguy/ubuntu2004"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
  # documentation for more information about their specific syntax and use.
  config.vm.provision "shell", inline: <<-SHELL
    sudo apt-get update
    sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release -y
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-achive-keyring.gpg
    echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-achive-keyring.gpg] https://download.docker.com/linux/ubuntu \
    $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt-get update
    sudo apt-get install docker-ce docker-ce-cli containerd.io -y
  SHELL
end

View More...

Get Logs error message, linenumber and path files using flask

  • Create Simple Log file
import logging
logging.basicConfig(filename="logs.txt",
                    filemode='a',
                    format='%(asctime)s\t%(lineno)d\t%(levelname)s\t%(pathname)s\t%(name)s\t%(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.DEBUG)
msg = "NameError: name filename' is not defined "
logging.info(msg)
logging.warn(msg)
logging.error(msg)
logging.critical(msg)
  • Logs file created in logs.txt like as: 20:05:16 10 INFO C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 11 WARNING C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 12 ERROR C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 13 CRITICAL C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined

write the code for post api using flask

from flask import Flask, request, jsonify
import os
# Create a Flask app for post api
app = Flask(__name__)
@app.route('/logs', methods= ['POST', 'GET'])
def logs_func():

    response = {
        "status": True,
        "message": "Logs data found!",
        "data":[]
    }

    if request.method == 'POST':
        file_name = request.json['filename']
        i = 1
        result = {}
        if os.path.exists(file_name):
            with open('logs.txt') as f:
                lines = f.readlines()
                for line in lines:
                    r = line.split('\t')

                    if r[2]== 'ERROR':

                        result[i] = {
                            'timestamp': r[0], 
                            'linenumber' : r[1],
                            'name': r[4],
                            'pathname': r[3],

                            'message': r[5]
                            }
                        i += 1
            response['data']= result
            return jsonify(response)
        else:
            response['status']= False
            response['message']= "File not found!"
            return jsonify(response)
    else:
        response['status']= False
        response['message']= "Only Post method is not allow"
        return jsonify(response)


if __name__ == '__main__':
    app.run(debug = True)

  • API Response:
{
    "data": {
        "1": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:16"
        },
        "2": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:18"
        },
        "3": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:20"
        },
        "4": {
            "linenumber": "13",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:08:12"
        }
    },
    "message": "Logs data found!",
    "status": true
}

View More...

Vuejs Basic Tutorial part 1

1: Create Vue App, Template and Data

Create app.js file and paste below code

const app = Vue.createApp({
    data(){
        return {
            title:"My first components",
            age:29,
            author:"Vishavjeet Singh",
            languages:["Python", "JavaScript"]
        }
    }
});
app.mount("#app")

Create index.html file and paste below code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=Test, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@3.0.2" ></script>
</head>
<body>
   Hi vue js 
   <div id="app">
       {{ title}} - {{ age}} - {{ author}} - {{ languages}}    
   </div>

   <script src="app.js"></script>

</body>
</html>

2: Method and click events

  • app.js
const app = Vue.createApp({
    data(){
        return {
            title:"My first components",
            age:29,
            name:"Vishavjeet Singh",
            languages:["Python", "PHP"]
        }
    },
    methods:{
        changeTitle(){
            this.title = "Change title by changeTitle method"
        },
        changeTitleWithParam(title){
            this.title =title
        }
        }
});
app.mount("#app")
  • index.html
<div id="app">
       <button v-on:click="age++"> Increase Age by 1</button>
       <button v-on:click="age--">Decrese Age by 1</button>
       <button @click="title= 'Change title using assingment '"> Change title by attribute</button>
       <button @click="changeTitle()"> Change title by changeTitle function without argument</button>
       <button @click="changeTitleWithParam('My new title')"> Change title by changeTitle function with argument</button>

  </div>

3: Conditinal rendering

  • app.js
const app = Vue.createApp({
    data(){
        return {
            title:"Core Python Book",
            age:29,
            author:"Vishavjeet Singh",
            languages:["Python", "PHP", "JavaScript", "SQL", "CQL"],
            showBook: true
        }
    },
    methods:{
        changeTitle(){
            this.title = "Change title by changeTitle method"
        },
        changeTitleWithParam(title){
            this.title =title
        },
        toggleShowBook(){
            this.showBook = !this.showBook
        }
        }
});
app.mount("#app")

  • index.html
<div id="app">

       <div v-if="showBook">
        {{ title}} - {{ age}} - {{ author }} - {{ languages}}
       </div>

       <button v-if="showBook">
           <span @click="toggleShowBook()"> Hide Book</span>
       </button>

       <button v-else>
        <span @click="toggleShowBook()"> Show Book</span>
        </button>

        <button v-if="showBook">
            <span> v-if </span>
        </button>

        <button v-show="showBook">
            <span> v-show </span>
        </button>

  </div>

# 4: Other Mouse Events - app.js

const app = Vue.createApp({
    data(){
        return {
            x:0,
            y:0
        }
    },
    methods:{
        handleEvent(e, data){
            console.log(e, e.type)
            if(data){
                console.log("data found", data)
            }
        },
        handleMouseMove(e){
            this.x = e.offsetX
            this.y = e.offsetY
        }
    }
});
app.mount("#app")

  • index.html
<head>
    <script src="https://unpkg.com/vue@3.0.2" ></script>
    <style>
        .box {
         padding: 100px 0;
         width: 400px;
         text-align: center;
         background: #ddd;
         margin: 20px;
         display: inline-block;
        }
    </style>
</head>
<body>
   <div id="app">
       <div class="box" @mouseover="handleEvent($event, 5)"> Mouse Over</div>
       <div class="box" @mouseleave="handleEvent($event)"> Mouse Over</div>
       <div class="box" @dbclick="handleEvent"> Double click </div>
       <div class="box" @mousemove="handleMouseMove"> Mouse Move: {{x}}, {{y}} </div>
   </div>
</body>

5: output list v-for

  • app.js
const app = Vue.createApp({
    data(){
        return {
            books:[
                {title:"Python Book", author:"Vishavjeet Singh", age:29},
                {title:"JavaScript Book", author:"JavaScript Publications", age:24},
                {title:"VueJs Book", author:"VueJs Publications", age:33},
                {title:"PHP Book", author:"Php  Publications", age:35}
            ],
            showBook:true
        }
    },
    methods:{
        toggleShowBook(){
            this.showBook = !this.showBook
        }
    }

});

app.mount("#app")

  • index.html
   <div id="app">
       <div v-if="showBook">
        <ul>
            <li v-for="book in books">
             <h3> {{ book.title}} </h3>
             <p>{{ book.author}}</p>
             <p>{{ book.age}}</p>
            </li>
        </ul>
       </div>

       <button v-if="showBook">
           <span @click="toggleShowBook()"> Hide Book</span>
       </button>
       <button v-else>
        <span @click="toggleShowBook()"> Show Book</span>
        </button>

   </div>

6: Attribute Binding

  • create assets folder and put some images
  • app.js
const app = Vue.createApp({
    data(){
        return {
            url:"https://www.python-ds.com",
            books:[
                {title:"Python Book", author:"Vishavjeet Singh", age:29, img:"assets/1.jpg"},
                {title:"JavaScript Book", author:"JavaScript Publications", age:24, img:"assets/2.jpg"},
                {title:"VueJs Book", author:"VueJs Publications", age:33, img:"assets/3.jpg"},
                {title:"PHP Book", author:"Php  Publications", age:35, img:"assets/1.jpg"}
            ],
            showBook:true
        }
    },
    methods:{
        toggleShowBook(){
            this.showBook = !this.showBook
        }
    }

});
app.mount("#app")
  • index.html
<div id="app">
       <div v-if="showBook">
        <a v-bind:href="url">Best website over</a>
        <a :href="url">Python Tutorial here</a>

        <ul>
            <li v-for="book in books">
            <img :src="book.img" :alt="book.title">
             <h3> {{ book.title}} </h3>
             <p>{{ book.author}}</p>
             <p>{{ book.age}}</p>
            </li>
        </ul>
       </div>

       <button v-if="showBook">
           <span @click="toggleShowBook()"> Hide Book</span>
       </button>
       <button v-else>
        <span @click="toggleShowBook()"> Show Book</span>
        </button>

   </div>

7: Dynamic Classes and Computed properties

  • app.js
 const app = Vue.createApp({
    data(){
        return {
            url:"https://www.python-ds.com",
            books:[
                {title:"Python Book", author:"Vishavjeet Singh", age:29, img:"assets/1.jpg", isFav:true},
                {title:"JavaScript Book", author:"JavaScript Publications", age:24, img:"assets/2.jpg", isFav:true},
                {title:"VueJs Book", author:"VueJs Publications", age:33, img:"assets/3.jpg", isFav:true},
                {title:"PHP Book", author:"Php  Publications", age:35, img:"assets/1.jpg", isFav:false}
            ],
            showBook:true
        }
    },
    methods:{
        toggleShowBook(){
            this.showBook = !this.showBook
        },
        toggleIsFav(book){
            book.isFav= !book.isFav
        }
    },
    computed:{
        filteredBooks(){
            return this.books.filter((book)=>book.isFav)
        }
    }

});
app.mount("#app")
  • index.html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=Test, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@3.0.2" ></script>
    <style>
    body{
      background: #eee;
      max-width: 960px;
      margin: 20px auto;
    }
    p, h3, ul{
      margin: 0;
      padding: 0;
    }
    li{
      list-style-type: none;
      background: #fff;
      margin: 20px auto;
      padding: 10px 20px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    li.fav{
      background: #ff9ed2;
      color: white;
    }
    </style>
</head>
<body>
   Hi Tech-Question 
   <div id="app">
       <div v-if="showBook">
        <h3>All Books</h3>
        <ul>
            <li v-for="book in books" :class="{fav: book.isFav}" @click="toggleIsFav(book)">
            <img :src="book.img" :alt="book.title">
             <h3> {{ book.title}} </h3>
             <p>{{ book.author}}</p>
             <p>{{ book.age}}</p>
            </li>
        </ul>

        <h3>My Favourite Book</h3>
        <ul>
            <li v-for="book in filteredBooks" :class="{fav: book.isFav}" @click="toggleIsFav(book)">
            <img :src="book.img" :alt="book.title">
             <h3> {{ book.title}} </h3>
             <p>{{ book.author}}</p>
             <p>{{ book.age}}</p>
            </li>
        </ul>
       </div>

       <button v-if="showBook">
           <span @click="toggleShowBook()"> Hide Book</span>
       </button>
       <button v-else>
        <span @click="toggleShowBook()"> Show Book</span>
        </button>

   </div>
<script src="app.js"></script>
</body>
</html>

Part-2 >>

View More...

Python script for find next monitoring/appointment/birthday ect

Using Function

from datetime import datetime, timedelta

def get_remaining_days(review_date, frequency):
    date_formate = '%Y-%m-%d'
    review_date = datetime.strptime(str(review_date), date_formate)
    today_date = datetime.strptime(str(datetime.now()).split(" ")[0], date_formate)

    difference = today_date - review_date
    if difference.days <= 0:
        next_monitoring = review_date + timedelta(days=frequency)
    else:
        flag = True
         next_monitoring = review_date + timedelta(days=0)
        while flag:
            next_monitoring = next_monitoring + timedelta(days=frequency)
            difference = next_monitoring - today_date
            if difference.days >= 0:
                flag = False
    remaining = next_monitoring - today_date

    print(f'Next Monitoring date will be  {next_monitoring} or after {remaining.days} days')
    return remaining.days, next_monitoring

get_remaining_days("2022-04-15", 20)

Using Class

from datetime import datetime, timedelta
class RemaningDayFinder():

    DATETIME_FORMAT = '%Y-%m-%d'

    def __init__(self, review_date, frequency):
        self.review_date = datetime.strptime(str(review_date), self.DATETIME_FORMAT)
        self.today_date = datetime.strptime(str(datetime.now()).split(" ")[0], self.DATETIME_FORMAT)
        self.frequency = frequency

    def get_remaining_days(self):

        difference = self.today_date - self.review_date

        if difference.days <= 0:
            next_monitoring = self.review_date + timedelta(days=self.frequency)
        else:
            flag = True
           next_monitoring = self.review_date + timedelta(days=0)
            while flag:
                next_monitoring = next_monitoring  + timedelta(days=self.frequency)
                difference = next_monitoring - self.today_date
                if difference.days >= 0:
                    flag = False

        remaining = next_monitoring - self.today_date
        return remaining.days, next_monitoring

    def __str__(self):
        remaining_days, next_monitoring = self.get_remaining_days()
        return f'Next Monitoring date will be  {next_monitoring} or after {remaining_days} days'

remaining_days = RemaningDayFinder("2022-04-15", 20) print(remaining_days)

Best Logic Based on Performance

def get_remaining_days(review_date, frequency): date_formate = '%Y-%m-%d' review_date = datetime.strptime(str(review_date), date_formate) today_date = datetime.strptime(str(datetime.now()).split(" ")[0], date_formate)

difference = today_date - review_date
if difference.days <= 0:
    next_monitoring = review_date + timedelta(days=frequency)
else:
    pass_days = ((difference.days//frequency)*frequency)+frequency
    next_monitoring = review_date + timedelta(days=pass_days)

remaining = next_monitoring - today_date

print(f'Next Monitoring date will be  {next_monitoring} or after {remaining.days} days')
return remaining.days, next_monitoring
View More...

First Previous 1 2 3 4 Next Last