article

Wednesday, June 30, 2021

SwiftUI Simple Stopwatch

SwiftUI Simple Stopwatch
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @ObservedObject var stopWatchManager = StopWatchManager()
    
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [Color.red, Color.purple]), startPoint: .top, endPoint: .bottom)
                .edgesIgnoringSafeArea(.vertical)
            
            VStack {
                Text(String(format: "%.1f", stopWatchManager.secondsElapsed))
                    .font(.system(size: 60))
                    .foregroundColor(.white)
                    .padding(.top, 200)
                    .padding(.bottom, 100)
                    .padding(.trailing, 100)
                    .padding(.leading, 100)
                if stopWatchManager.mode == .stopped {
                    Button(action: {self.stopWatchManager.start()}) {
                        TimerButton(label: "Start", buttonColor: .green, textColor: .white) //CMD-click and select Extract Subview
                    }
                }
                if stopWatchManager.mode == .running {
                    Button(action: {self.stopWatchManager.pause()}) {
                        TimerButton(label: "Pause", buttonColor: .green, textColor: .white)
                    }
                }
                if stopWatchManager.mode == .paused {
                    Button(action: {self.stopWatchManager.start()}) {
                        TimerButton(label: "Start", buttonColor: .green, textColor: .white)
                    }
                    Button(action: {self.stopWatchManager.stop()}) {
                        TimerButton(label: "Stop", buttonColor: .red, textColor: .white)
                    }
                    .padding(.top, 30)
                }
                
                Spacer()
            }
        }
    }
}

struct TimerButton: View {
    
    let label: String
    let buttonColor: Color
    let textColor: Color
    
    var body: some View {
        Text(label)
            .foregroundColor(textColor)
            .padding(.vertical, 20)
            .padding(.horizontal, 90)
            .background(buttonColor)
            .cornerRadius(10)
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
StopWatchManager.swift
 
//
//  StopWatchManager.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation
import SwiftUI

class StopWatchManager: ObservableObject {
    
    enum stopWatchMode {
        case running
        case stopped
        case paused
    }
    
    @Published var mode: stopWatchMode = .stopped
    
    @Published var secondsElapsed = 0.0
    var timer = Timer()
    
    func start() {
        mode = .running
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
            self.secondsElapsed += 0.1
        }
    }
    
    func pause() {
        timer.invalidate()
        mode = .paused
    }
    
    func stop() {
        timer.invalidate()
        secondsElapsed = 0
        mode = .stopped
    }
}

Live Poll using Jquery ajax and Python Flask PosgreSQL

Live Poll using Jquery ajax and Python Flask PosgreSQL

CREATE TABLE tblprogramming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tblprogramming(title)
VALUES
('Flask'),
('Laravel'),
('React.js'),
('Express'),
('Django');

CREATE TABLE tbl_poll (
id serial PRIMARY KEY,
web_framework VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tbl_poll(web_framework)
VALUES
('Flask'),
('Flask'),
('Flask'),
('Express'),
('React.js'),
('Laravel'),
('Flask'),
('Flask'),
('Laravel'),
('Django'),
('Django'),
('Flask');


install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
       
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    webframework = cur.fetchall()  
    return render_template('index.html', webframework = webframework)
 
@app.route("/polldata",methods=["POST","GET"])
def polldata():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    query = "SELECT * from tbl_poll"
    cur.execute(query)
    total_poll_row = int(cur.rowcount) 
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    framework = cur.fetchall()  
    frameworkArray = []
    for row in framework:
        get_title = row['title']
        cur.execute("SELECT * FROM tbl_poll WHERE web_framework = %s", [get_title])
        row_poll = cur.fetchone()  
        total_row = cur.rowcount
        #print(total_row)
        percentage_vote = round((total_row/total_poll_row)*100)
        print(percentage_vote)
        if percentage_vote >= 40:
            progress_bar_class = 'progress-bar-success'
        elif percentage_vote >= 25 and percentage_vote < 40:   
            progress_bar_class = 'progress-bar-info'  
        elif percentage_vote >= 10 and percentage_vote < 25:
            progress_bar_class = 'progress-bar-warning'
        else:
            progress_bar_class = 'progress-bar-danger'
  
        frameworkObj = {
                'id': row['id'],
                'name': row['title'],
                'percentage_vote': percentage_vote,
                'progress_bar_class': progress_bar_class}
        frameworkArray.append(frameworkObj)
    return jsonify({'htmlresponse': render_template('response.html', frameworklist=frameworkArray)})
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        poll_option = request.form['poll_option']
        print(poll_option)      
        cur.execute("INSERT INTO tbl_poll (web_framework) VALUES (%s)",[poll_option])
        conn.commit()       
        cur.close()
        msg = 'success' 
    return jsonify(msg)
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Live Poll using Jquery ajax and Python Flask PosgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
</head>  
    <body>  
        <div class="container">  
            <br />  <br />
            <h2 align="center">Live Poll using Jquery ajax and Python Flask PosgreSQL </h2><br />
            <div class="row">
                <div class="col-md-6">
                    <form method="post" id="poll_form">
                        <h3>Which is Best Web Development Frameworks</h3>
                        <br />
                        {% for row in webframework %}
                        <div class="radio">
                            <label><h4><input type="radio" name="poll_option" class="poll_option" value="{{row.title}}" /> {{row.title}}</h4></label>
                        </div>
                        {% endfor %}
                        <br />
                        <input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
                    </form>
                    <br />
                </div>
                <div class="col-md-6">
                    <br />
                    <br />
                    <h4>Live Poll Result</h4><br />
                    <div id="poll_result"></div>
                </div>
            </div>
        </div>
<script>  
$(document).ready(function(){
    fetch_poll_data();
    function fetch_poll_data()
    { 
        var fetchall = 'all';
        var dataString = 'fetchall='+ fetchall;
        $.ajax({
            url:"/polldata",
            method:"POST",
            data: dataString,
            success:function(data)
            {
                $('#poll_result').html(data); 
                $("#poll_result").append(data.htmlresponse);
            }
        });
    }
    $('#poll_form').on('submit', function(event){
        event.preventDefault();
        var poll_option = '';
        $('.poll_option').each(function(){
            if($(this).prop("checked"))
            {
                poll_option = $(this).val();
            }
        });
        if(poll_option != '')
        {
            $('#poll_button').attr('disabled', 'disabled');
            var form_data = $(this).serialize();
            $.ajax({
                url:"/insert",
                method:"POST",
                data:form_data,
                success:function()
                {
                    $('#poll_form')[0].reset();
                    $('#poll_button').attr('disabled', false);
                    fetch_poll_data();
                    alert("Poll Submitted Successfully");
                }
            });
        }
        else
        {
            alert("Please Select Option");
        }
    });
});  
</script>
</body>  
</html>
templates/response.html
//templates/response.html
{% for row in frameworklist %}  
<div class="row">
    <div class="col-md-2" align="right">
        <label>{{row.name}}</label>
    </div>
    <div class="col-md-10">
        <div class="progress">
            <div class="progress-bar {{row.progress_bar_class}}" role="progressbar" aria-valuenow="{{row.percentage_vote}}" aria-valuemin="0" aria-valuemax="100" style="width:{{row.percentage_vote}}%">
                {{row.percentage_vote}} % programmer like <b>{{row.name}}</b> Web Framework
            </div>
        </div>
    </div>
</div>
{% endfor %} 

Getting started With NodeJS and ExpressJS in Windows 10

Getting started With NodeJS and ExpressJS in Windows 10

Expressjs is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −

Allows to set up middlewares to respond to HTTP Requests.

Defines a routing table which is used to perform different actions based on HTTP Method and URL.

Allows to dynamically render HTML Pages based on passing arguments to templates.

run
PS C:\nodeproject>node index.js

PS C:\nodeproject> node index.js
Example app listening at http://localhost:3000

Live Data Search Select Dropdown using Python Flask Jquery Ajax PostgreSQL

Live Data Search Select Dropdown using Python Flask Jquery Ajax PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
       
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT DISTINCT office FROM employee ORDER BY office ASC")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)
 
@app.route("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        query = request.form['query']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM employee ORDER BY id DESC")
            employeelist = cur.fetchall()
            print('all list')
        else:
            search_text = request.form['query']
            print(search_text)
            cur.execute("SELECT * FROM employee WHERE office IN (%s) ORDER BY id DESC", [search_text])
            employeelist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', employeelist=employeelist)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Live Data Search Select Dropdown using Python Flask Jquery Ajax PostgreSQL</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    </head>
    <body>
        <div class="container">
            <br />
            <h2 align="center">Live Data Search Select Dropdown using Python Flask Jquery Ajax PostgreSQL</h2><br />
            <select name="search_filter" id="search_filter" class="form-control">
            <option value="">Select Option</option>';
            {% for row in employee %}
                <option value="{{row.office}}">{{row.office}}</option>';    
            {% endfor %}
            </select>
            <input type="hidden" name="hidden_value" id="hidden_value" />
            <div style="clear:both"></div>
            <br />
            <div class="table-responsive">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Age</th>
                            <th>Salary</th>
                            <th>Office</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
            <br />
            <br />
            <br />
        </div>
<script>
$(document).ready(function(){
    load_data();
    function load_data(query='')
    {
        $.ajax({
            url:"/fetchrecords",
            method:"POST",
            data:{query:query},
            success:function(data)
            { 
                $('tbody').html(data);
                $('tbody').append(data.htmlresponse);
            }
        })
    }
 
    $('#search_filter').change(function(){
        $('#hidden_value').val($('#search_filter').val());
        var query = $('#hidden_value').val(); 
        load_data(query);
    });
     
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %}  
<tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.age}}</td>
    <td>{{ "$%.2f"|format(row.salary) }}</td>
    <td>{{row.office}}</td>
</tr>
{% endfor %} 

Tuesday, June 29, 2021

SwiftUI Timer using Circular Progress Bar

SwiftUI Timer using Circular Progress Bar
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

let timer = Timer
    .publish(every: 1, on: .main, in: .common)
    .autoconnect()

struct ContentView: View {
    
    @State var counter: Int = 0
    var countTo: Int = 120 //4 minutes 120 - 2minutes
    
    var body: some View {
        VStack{
            ZStack{
                Circle()
                    .fill(Color.clear)
                    .frame(width: 250, height: 250)
                    .overlay(
                        Circle().stroke(Color.green, lineWidth: 25)
                )
                
                Circle()
                    .fill(Color.clear)
                    .frame(width: 250, height: 250)
                    .overlay(
                        Circle().trim(from:0, to: progress())
                            .stroke(
                                style: StrokeStyle(
                                    lineWidth: 25,
                                    lineCap: .round,
                                    lineJoin:.round
                                )
                            )
                            .foregroundColor(
                                (completed() ? Color.orange : Color.red)
                            ).animation(
                                .easeInOut(duration: 0.2)
                            )
                    )
                
                Clock(counter: counter, countTo: countTo)
            }
        }.onReceive(timer) { time in
            if (self.counter < self.countTo) {
                self.counter += 1
            }
        }
    }
    
    func completed() -> Bool {
        return progress() == 1
    }
    
    func progress() -> CGFloat {
        return (CGFloat(counter) / CGFloat(countTo))
    }
}

struct Clock: View {
    var counter: Int
    var countTo: Int
    
    var body: some View {
        VStack {
            Text(counterToMinutes())
                .font(.system(size: 60))
                .fontWeight(.black)
        }
    }
    
    func counterToMinutes() -> String {
        let currentTime = countTo - counter
        let seconds = currentTime % 60
        let minutes = Int(currentTime / 60)
        
        return "\(minutes):\(seconds < 10 ? "0" : "")\(seconds)"
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Monday, June 28, 2021

File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database

File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database

CREATE TABLE uploads (
id serial PRIMARY KEY,
file_name VARCHAR ( 150 ) NOT NULL,
upload_time TIMESTAMP NOT NULL
);

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.

https://github.com/jquery-form/form
bootstrap progressbar https://getbootstrap.com/docs/4.0/components/progress/

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
import os
from datetime import datetime

import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
       
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

app.config['UPLOAD_FOLDER'] = 'static/uploads'
   
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
   
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def index(): 
    return render_template('index.html')
 
@app.route("/upload",methods=["POST","GET"])
def upload():
    file = request.files['uploadFile']
    filename = secure_filename(file.filename)
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        filenameimage = file.filename
 
        today = datetime.today() 
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("INSERT INTO uploads (file_name,upload_time) VALUES (%s,%s)",[filenameimage,today])
        conn.commit()       
        cur.close()
        msg  = 'File successfully uploaded ' + file.filename + ' to the database!'
    else:
        msg  = 'Invalid Uplaod only png, jpg, jpeg, gif'
    return jsonify({'htmlresponse': render_template('response.html', msg=msg, filenameimage=filenameimage)})
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<!--<script src="/static/js/jquery.form.js"></script>-->
</head>
    <body>
        <div class="container">
            <br />
            <h3 align="center">File Upload Progress Bar using JQuery Ajax Python Flask PostgreSQL Database</h3>
            <br />
            <div class="panel panel-default">
                <div class="panel-heading"><b>Ajax File Upload Progress Bar using JQuery Ajax</b></div>
                <div class="panel-body">
                    <form id="uploadImage" action="/upload" method="post">
                        <div class="form-group">
                            <label>File Upload</label>
                            <input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
                        </div>
                        <div class="form-group">
                            <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
                        </div>
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <div id="targetLayer" style="display:none;"></div>
                    </form>
                    <div id="loader-icon" style="display:none;"><img src="/static/images/loader.gif" /></div>
                </div>
            </div>
        </div>
<script>
$(document).ready(function(){
    $('#uploadImage').submit(function(event){
        if($('#uploadFile').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                beforeSubmit:function(){
                    $('.progress-bar').width('50%');
                },
                uploadProgress: function(event, position, total, percentageComplete)
                {
                    $('.progress-bar').animate({
                        width: percentageComplete + '%'
                    }, {
                        duration: 1000
                    });
                },
                success:function(data){
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').append(data.htmlresponse);
                },
                resetForm: true
            });
        }
        return false;
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<p><b>{{ msg }}</b></p>
<img src="/static/uploads/{{ filenameimage }}" class="img-thumbnail" width="300" height="250" />

SwiftUI Search Bar Todo List

SwiftUI Search Bar Todo List
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI


struct ContentView: View {
        
    private var todoItems = [ ToDoItem(name: "Learn SwiftUI"),
                              ToDoItem(name: "Learn Programming language"),
                              ToDoItem(name: "Learn Python"),
                              ToDoItem(name: "Coding"),
                              ToDoItem(name: "Read Books"),
                              ToDoItem(name: "Play basketball"),
                              ToDoItem(name: "Coding"),
                              ToDoItem(name: "Buy some stuff"),
                              ToDoItem(name: "Create Project App"),
                              ToDoItem(name: "Play games")
                                ]
    
    @State private var searchText = ""
    @State var show = false
    var body: some View {
        
        ZStack {
            
            VStack {
                
                HStack {
                    Text("ToDo List")
                        .font(.system(size: 30, weight: .black, design: .rounded))
                        
                    Spacer()
                    
                    Button(action: {
                        show.toggle()
                    }) {
                        Image(systemName: "plus.circle.fill")
                            .font(.largeTitle)
                            .foregroundColor(.purple)
                    }
                }
                .padding()
                
                SearchBar(text: $searchText)
                    .padding(.top, 10)
                
                List(todoItems.filter({ searchText.isEmpty ? true : $0.name.contains(searchText) })) { item in
                    Text(item.name)
                }
                .padding(.top, 20)
                
            }//End VStack
            .sheet(isPresented: $show, content: {
                Addnew()
            })
    
        }
    }

}

struct Addnew: View {

    @State private var newTodo = ""
    var body: some View {
        
        HStack { //Horizontal Stack
            TextField("Add todo...", text: $newTodo)
              .textFieldStyle(RoundedBorderTextFieldStyle())
             
            Button(action: {
            }) {
                Image(systemName: "plus")
            }
            .padding(.leading, 5)
        }.padding() //end horizontal stack
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
SearchBar.swift
 
//
//  SearchBar.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct SearchBar: View {
    @Binding var text: String

    @State private var isEditing = false
        
    var body: some View {
        HStack {
            
            TextField("Search ...", text: $text)
                .padding(7)
                .padding(.horizontal, 25)
                .background(Color(.systemGray6))
                .cornerRadius(8)
                .overlay(
                    HStack {
                        Image(systemName: "magnifyingglass")
                            .foregroundColor(.gray)
                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                            .padding(.leading, 8)
                        
                        if isEditing {
                            Button(action: {
                                self.text = ""
                                
                            }) {
                                Image(systemName: "multiply.circle.fill")
                                    .foregroundColor(.gray)
                                    .padding(.trailing, 8)
                            }
                        }
                    }
                )
                .padding(.horizontal, 10)
                .onTapGesture {
                    self.isEditing = true
                }
            
            if isEditing {
                Button(action: {
                    self.isEditing = false
                    self.text = ""
                    
                    // Dismiss the keyboard
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                }) {
                    Text("Cancel")
                }
                .padding(.trailing, 10)
                .transition(.move(edge: .trailing))
                .animation(.default)
            }
        }
    }
}

struct SearchBar_Previews: PreviewProvider {
    static var previews: some View {
        SearchBar(text: .constant(""))
    }
}
ToDoItem.swift
 
//
//  ToDoItem.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation
import CoreData

enum Priority: Int {
    case low = 0
    case normal = 1
    case high = 2
}

struct ToDoItem: Identifiable {
    var id = UUID()
    var name: String = ""
    var priorityNum: Priority = .normal
    var isComplete: Bool = false
}

Sunday, June 27, 2021

SwiftUI Progress Rings Fitness Dashboard

SwiftUI Progress Rings Fitness Dashboard
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI


struct ContentView: View {
    var body: some View {
        Home()
    }
}

struct Home : View {
      
    var columns = Array(repeating: GridItem(.flexible(), spacing: 20), count: 2)
    
    var body: some View{
        GeometryReader { geometry in
            ZStack {
                Image("bg2")
                    .resizable()
                    .aspectRatio(geometry.size, contentMode: .fill)
                    .edgesIgnoringSafeArea(.all)
                
                ScrollView(.vertical, showsIndicators: false) {
                    VStack{
                        HStack{
                            Text("Hello Cairocoders")
                                .font(.title)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                            
                            Spacer(minLength: 0)
                            
                            Button(action: {}) {
                                
                                Image(systemName: "slider.horizontal.3")
                                    .renderingMode(.template)
                                    .foregroundColor(.white)
                            }
                        }//End HStack
                        .padding()
                        
                        HStack{
                            Text("Stats Today")
                                .font(.title)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                            
                            Spacer(minLength: 0)
                            
                            Text(Date(), style: .date)
                                .foregroundColor(.white)
                        }//End HStack
                        .padding()
                        
                        LazyVGrid(columns: columns,spacing: 30){
                            
                            ForEach(stats_Data){stat in
                                VStack(spacing: 32){
                                    
                                    HStack{
                                        Text(stat.title)
                                            .font(.system(size: 22))
                                            .fontWeight(.bold)
                                            .foregroundColor(.white)
                                        
                                        Spacer(minLength: 0)
                                    }
                                    
                                    ZStack{
                                        Circle()
                                            .trim(from: 0, to: 1)
                                            .stroke(Color.gray, lineWidth: 10)
                                            .frame(width: (UIScreen.main.bounds.width - 150) / 2, height: (UIScreen.main.bounds.width - 150) / 2)
                                        
                                        Circle()
                                            .trim(from: 0, to: (stat.currentData / stat.goal))
                                            .stroke(stat.color, style: StrokeStyle(lineWidth: 10, lineCap: .round))
                                            .frame(width: (UIScreen.main.bounds.width - 150) / 2, height: (UIScreen.main.bounds.width - 150) / 2)
                                        
                                        Text(getPercent(current: stat.currentData, Goal: stat.goal) + " %")
                                            .font(.system(size: 22))
                                            .fontWeight(.bold)
                                            .foregroundColor(Color.white)
                                            .rotationEffect(.init(degrees: 90))
                                    }
                                    .rotationEffect(.init(degrees: -90))

                                    Text(getDec(val: stat.currentData) + " " + getType(val: stat.title))
                                        .font(.system(size: 22))
                                        .foregroundColor(.white)
                                        .fontWeight(.bold)
                                }
                                .padding()
                                .background(Color.white.opacity(0.19))
                                .cornerRadius(15)
                                .shadow(color: Color.white.opacity(0.2), radius: 10, x: 0, y: 0)
                            }
                        }
                        .padding()
                    }
                }//End Scrollview
            }//End ZStack
        }//End GeometryReader
    }
}

// calculating Type...
func getType(val: String)->String{
    switch val {
    case "Water": return "L"
    case "Pushups": return "Pu"
    case "Running": return "Km"
    case "Cycling": return "Km"
    case "Steps": return "stp"
    default: return "Kcal"
    }
}

// converting Number to decimal...
func getDec(val: CGFloat)->String{
    let format = NumberFormatter()
    format.numberStyle = .decimal
    return format.string(from: NSNumber.init(value: Float(val)))!
}

// calculating percent...
func getPercent(current : CGFloat,Goal : CGFloat)->String{
    let per = (current / Goal) * 100
    return String(format: "%.1f", per)
}

struct Stats : Identifiable {
    var id : Int
    var title : String
    var currentData : CGFloat
    var goal : CGFloat
    var color : Color
}

var stats_Data = [
    Stats(id: 0, title: "Running", currentData: 7.5, goal: 15, color: Color.blue),
    Stats(id: 1, title: "Water", currentData: 3.5, goal: 5, color: Color.green),
    Stats(id: 2, title: "Calories", currentData: 1230, goal: 2000, color: Color.orange),
    Stats(id: 3, title: "Pushups", currentData: 45, goal: 100, color: Color.red),
    Stats(id: 4, title: "Cycling", currentData: 12.5, goal: 25, color: Color.blue),
    Stats(id: 5, title: "Steps", currentData: 6423, goal: 10000, color: Color.orange),
]

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL

Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE product (
pid serial PRIMARY KEY,
name VARCHAR ( 70 ) NOT NULL,
image VARCHAR ( 255 ) NOT NULL,
category VARCHAR ( 70 ) NOT NULL,
price INT NOT NULL
);

INSERT INTO
    product(name,image,category,price)
VALUES
('Samsung Galaxy A10S', '1.jpg', 'Mobile', 520),
('HP Laptop - 17z-ca100 ', '2.jpg', 'Laptop', 1600),
('3 IN 1 CAR VOLTMETER', '3.jpg', 'Car', 2020),
('Gucci G-Timeless', '4.jpg', 'Watch', 320),
('Infinix Hot S3', '5.jpg', 'Mobile', 150),
('VIVO V9 Youth', '6.jpeg', 'Laptop', 3500),
('Moto E4 Plus', '7.jpeg', 'Car', 250),
('Lenovo K8 Plus', '8.jpeg', 'Watch', 4500);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
  
app = Flask(__name__)
  
app.secret_key = "caircocoders-ednalan"
  
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
      
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index(): 
    return render_template('index.html')
 
@app.route("/fetchrecords",methods=["POST","GET"])
def fetchrecords():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        query = request.form['action']
        minimum_price = request.form['minimum_price']
        maximum_price = request.form['maximum_price']
        #print(query)
        if query == '':
            cur.execute("SELECT * FROM product ORDER BY pid ASC")
            productlist = cur.fetchall()
            print('all list')
        else:
            cur.execute("SELECT * FROM product WHERE price BETWEEN (%s) AND (%s)", [minimum_price, maximum_price])
            productlist = cur.fetchall()  
    return jsonify({'htmlresponse': render_template('response.html', productlist=productlist)})
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
    <br />
    <h2 align="center">Price Range Product Filters Using Jquery Ajax Python Flask and PostgreSQL</h2>
    <br />
        <div class="col-md-3">                                
            <div class="list-group">
                <h3>Price</h3>
                <input type="hidden" id="hidden_minimum_price" value="0" />
                <input type="hidden" id="hidden_maximum_price" value="65000" />
                <p id="price_show">10 - 5000</p>
                <div id="price_range"></div>
            </div>                
        </div>
        <div class="col-md-9">
           <div class="row filter_data">
        </div>
    </div>
    </div>
</div>
<style>
#loading
{
    text-align:center; 
    background: url('images/loading.gif') no-repeat center; 
    height: 150px;
}
</style>
<script>
$(document).ready(function(){
    filter_data();
    function filter_data()
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        $.ajax({
            url:"/fetchrecords",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price},
            success:function(data){
                $('.filter_data').html(data);
                $(".filter_data").append(data.htmlresponse);
            }
        });
    }
    $('#price_range').slider({
        range:true,
        min:50,
        max:5000,
        values:[50, 5000],
        step:50,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data();
        }
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
{% for row in productlist %}  
<div class="col-sm-4 col-lg-3 col-md-3">
    <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:300px;">
        <img src="/static/images/{{row.image}}" alt="" class="img-responsive" >
        <p align="center"><strong><a href="#">{{row.name}}</a></strong></p>
        <h4 style="text-align:center;" class="text-danger" >{{row.price}}</h4>
    </div>
</div>
{% endfor %} 

Saturday, June 26, 2021

Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL

Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

this post a user select multiple records using checkbox fields and click the delete button a loading image gif show and a successfully message display and animate effect every row selected without refresh the page

https://github.com/jquery-form/form

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allow you to have full control over how the data is submitted.

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
app.secret_key = "caircocoders-ednalan"
 
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
     
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id DESC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)
 
@app.route("/delete",methods=["POST","GET"])
def delete():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    for getid in request.form.getlist('checkdelete'):
        print(getid)
        cur.execute('DELETE FROM employee WHERE id = {0}'.format(getid))
        conn.commit()      
    cur.close()
    return jsonify('Records deleted successfully')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
</head>  
    <body>  
        <div class="container">  
            <br />
   <div class="table-responsive">  
    <h3 align="center">Delete Multiple Records using Jquey Ajax Python Flask PostgreSQL</h3><br />
    <div class="table-responsive">
        <div id="targetLayer" class="btn btn-success" style="display:none;width:100%;margin-bottom: 10px;"></div>
        <div id="loader-icon" style="display:none;"><img src="/static/img/loader.gif" /></div>
        <form id="deleteall" action="/delete" method="post">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th width="5%">
                                <input type="submit" value="Delete" name="delete_all" id="delete_all" class="btn btn-danger btn-xs" />
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead>
                        {% for row in employeelist %}
                            <tr>
                                <td>
                                    <input type="checkbox" name="checkdelete" id="checkdelete" class="delete_checkbox" value="{{row.id}}" />
                                </td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>$ {{ "%.2f"|format(row.salary) }}</td>
                            </tr>
                        {% endfor %}    
                    </table>
        </form>        
                </div>
   </div>  
  </div>
<style>
.removeRow {background-color: #64b418;color:#FFFFFF;}
</style>
<script>  
$(document).ready(function(){ 
    $('.delete_checkbox').click(function(){
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('removeRow');
        }else{
            $(this).closest('tr').removeClass('removeRow');
        }
    });
    $('#deleteall').submit(function(event){
        if($('#checkdelete').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                success:function(data){
                    $('.removeRow').fadeOut(1500);
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').html(data);
                },
                resetForm: true
            });
        }
        return false;
    });
});  
</script>
</body>  
</html> 

Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database

Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database

jQuery Editable Select is a jQuery plugin that transforms a select into an input field where single elements are shown in real-time according to the entered characters. It scales down to a real select list when javascript is not available.

https://github.com/indrimuska/jquery-editable-select

See demos here: http://indrimuska.github.io/jquery-editable-select/

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados'),
(21, 'Belarus'),
(22, 'Belgium'),
(23, 'Belize'),
(24, 'Benin'),
(25, 'Bermuda'),
(26, 'Bhutan'),
(27, 'Bolivia'),
(28, 'Bosnia and Herzegovina'),
(29, 'Botswana'),
(30, 'Bouvet Island'),
(31, 'Brazil'),
(32, 'British Indian Ocean territory'),
(33, 'Brunei Darussalam'),
(34, 'Bulgaria'),
(35, 'Burkina Faso'),
(36, 'Burundi'),
(37, 'Cambodia'),
(38, 'Cameroon'),
(39, 'Canada'),
(40, 'Cape Verde'),
(41, 'Cayman Islands'),
(42, 'Central African Republic'),
(43, 'Chad'),
(44, 'Chile'),
(45, 'China'),
(46, 'Christmas Island'),
(47, 'Cocos (Keeling) Islands'),
(48, 'Colombia'),
(49, 'Comoros'),
(50, 'Congo'),
(51, 'Congo'),
(52, ' Democratic Republic'),
(53, 'Cook Islands'),
(54, 'Costa Rica'),
(55, 'Ivory Coast (Ivory Coast)'),
(56, 'Croatia (Hrvatska)'),
(57, 'Cuba'),
(58, 'Cyprus'),
(59, 'Czech Republic'),
(60, 'Denmark'),
(61, 'Djibouti'),
(62, 'Dominica'),
(63, 'Dominican Republic'),
(64, 'East Timor'),
(65, 'Ecuador'),
(66, 'Egypt'),
(67, 'El Salvador'),
(68, 'Equatorial Guinea'),
(69, 'Eritrea'),
(70, 'Estonia'),
(71, 'Ethiopia'),
(72, 'Falkland Islands'),
(73, 'Faroe Islands'),
(74, 'Fiji'),
(75, 'Finland'),
(76, 'France'),
(77, 'French Guiana'),
(78, 'French Polynesia'),
(79, 'French Southern Territories'),
(80, 'Gabon'),
(81, 'Gambia'),
(82, 'Georgia'),
(83, 'Germany'),
(84, 'Ghana'),
(85, 'Gibraltar'),
(86, 'Greece'),
(87, 'Greenland'),
(88, 'Grenada'),
(89, 'Guadeloupe'),
(90, 'Guam'),
(91, 'Guatemala'),
(92, 'Guinea'),
(93, 'Guinea-Bissau'),
(94, 'Guyana'),
(95, 'Haiti'),
(96, 'Heard and McDonald Islands'),
(97, 'Honduras'),
(98, 'Hong Kong'),
(99, 'Hungary'),
(100, 'Iceland'),
(101, 'India'),
(102, 'Indonesia'),
(103, 'Iran'),
(104, 'Iraq'),
(105, 'Ireland'),
(106, 'Israel'),
(107, 'Italy'),
(108, 'Jamaica'),
(109, 'Japan'),
(110, 'Jordan'),
(111, 'Kazakhstan'),
(112, 'Kenya'),
(113, 'Kiribati'),
(114, 'Korea (north)'),
(115, 'Korea (south)'),
(116, 'Kuwait'),
(117, 'Kyrgyzstan'),
(118, 'Lao People\'s Democratic Republic'),
(119, 'Latvia'),
(120, 'Lebanon'),
(121, 'Lesotho'),
(122, 'Liberia'),
(123, 'Libyan Arab Jamahiriya'),
(124, 'Liechtenstein'),
(125, 'Lithuania'),
(126, 'Luxembourg'),
(127, 'Macao'),
(128, 'Macedonia'),
(129, 'Madagascar'),
(130, 'Malawi'),
(131, 'Malaysia'),
(132, 'Maldives'),
(133, 'Mali'),
(134, 'Malta'),
(135, 'Marshall Islands'),
(136, 'Martinique'),
(137, 'Mauritania'),
(138, 'Mauritius'),
(139, 'Mayotte'),
(140, 'Mexico'),
(141, 'Micronesia'),
(142, 'Moldova'),
(143, 'Monaco'),
(144, 'Mongolia'),
(145, 'Montserrat'),
(146, 'Morocco'),
(147, 'Mozambique'),
(148, 'Myanmar'),
(149, 'Namibia'),
(150, 'Nauru'),
(151, 'Nepal'),
(152, 'Netherlands'),
(153, 'Netherlands Antilles'),
(154, 'New Caledonia'),
(155, 'New Zealand'),
(156, 'Nicaragua'),
(157, 'Niger'),
(158, 'Nigeria'),
(159, 'Niue'),
(160, 'Norfolk Island'),
(161, 'Northern Mariana Islands'),
(162, 'Norway'),
(163, 'Oman'),
(164, 'Pakistan'),
(165, 'Palau'),
(166, 'Palestinian Territories'),
(167, 'Panama'),
(168, 'Papua New Guinea'),
(169, 'Paraguay'),
(170, 'Peru'),
(171, 'Philippines'),
(172, 'Pitcairn'),
(173, 'Poland'),
(174, 'Portugal'),
(175, 'Puerto Rico'),
(176, 'Qatar'),
(177, 'Runion'),
(178, 'Romania'),
(179, 'Russian Federation'),
(180, 'Rwanda'),
(181, 'Saint Helena'),
(182, 'Saint Kitts and Nevis'),
(183, 'Saint Lucia'),
(184, 'Saint Pierre and Miquelon'),
(185, 'Saint Vincent and the Grenadines'),
(186, 'Samoa'),
(187, 'San Marino'),
(188, 'Sao Tome and Principe'),
(189, 'Saudi Arabia'),
(190, 'Senegal'),
(191, 'Serbia and Montenegro'),
(192, 'Seychelles'),
(193, 'Sierra Leone'),
(194, 'Singapore'),
(195, 'Slovakia'),
(196, 'Slovenia'),
(197, 'Solomon Islands'),
(198, 'Somalia'),
(199, 'South Africa'),
(200, 'South Georgia and the South Sandwich Islands'),
(201, 'Spain'),
(202, 'Sri Lanka'),
(203, 'Sudan'),
(204, 'Suriname'),
(205, 'Svalbard and Jan Mayen Islands'),
(206, 'Swaziland'),
(207, 'Sweden'),
(208, 'Switzerland'),
(209, 'Syria'),
(210, 'Taiwan'),
(211, 'Tajikistan'),
(212, 'Tanzania'),
(213, 'Thailand'),
(214, 'Togo'),
(215, 'Tokelau'),
(216, 'Tonga'),
(217, 'Trinidad and Tobago'),
(218, 'Tunisia'),
(219, 'Turkey'),
(220, 'Turkmenistan'),
(221, 'Turks and Caicos Islands'),
(222, 'Tuvalu'),
(223, 'Uganda'),
(224, 'Ukraine'),
(225, 'United Arab Emirates'),
(226, 'United Kingdom'),
(227, 'United States of America'),
(228, 'Uruguay'),
(229, 'Uzbekistan'),
(230, 'Vanuatu'),
(231, 'Vatican City'),
(232, 'Venezuela'),
(233, 'Vietnam'),
(234, 'Virgin Islands (British)'),
(235, 'Virgin Islands (US)'),
(236, 'Wallis and Futuna Islands'),
(237, 'Western Sahara'),
(238, 'Yemen'),
(239, 'Zaire'),
(240, 'Zambia'),
(241, 'Zimbabwe');

CREATE TABLE tbl_user (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
country VARCHAR ( 100 ) NOT NULL
);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
app.secret_key = "caircocoders-ednalan"
 
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
     
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM countries ORDER BY name ASC")
    countrylist = cur.fetchall()
    return render_template('index.html', countrylist=countrylist)
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        fullname = request.form['name']
        country = request.form['country']
        cur.execute("INSERT INTO tbl_user (fullname, country) VALUES (%s,%s)",[fullname,country])
        conn.commit()      
        cur.close()
    return jsonify('New Records added successfully')
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<script src="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="http://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
</head>  
<body>  
<div class="container">  
   <br />
   <h2 align="center">Editable Select Box using Python Flask jQuery Ajax and PostgreSQL Database</h2><br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <form method="post" id="sample_form">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" id="name" class="form-control">
      </div>
      <div class="form-group">
       <label>Select Country</label>
       <select name="country" id="country" class="form-control">
        {% for row in countrylist %}
            <option value="{{row.name}}">{{row.name}}</option>
        {% endfor %} 
       </select>
      </div>
      <div class="form-group">
       <input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <script>  
$(document).ready(function(){
    $('#country').editableSelect();
  
    $('#sample_form').on('submit', function(event){
        event.preventDefault();
        if($('#name').val() == '') {
           alert("Enter Name");
           return false;
        }else if($('#country').val() == ''){
           alert("Select Country");
           return false;
        }else{
           $.ajax({
                url:"/insert",
                method:"POST",
                data:$(this).serialize(),
                success:function(data)
                {
                 alert(data);
                 $('#sample_form')[0].reset();
                }
           });
        }
    });
});  
</script>
</body>  
</html> 

Friday, June 25, 2021

SwiftUI Blog Post and Detail Post

SwiftUI Blog Post and Detail Post ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    //var posts:[Post]
    @State var search = ""
    @State var columns = Array(repeating: GridItem(.flexible(), spacing: 15), count: 2)
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            LazyVStack{
                HStack{
                    Text("Blog Post")
                        .font(.title)
                        .fontWeight(.bold)
                     
                    Spacer()
                    
                    Button {
                        withAnimation(.easeOut){
                            if self.columns.count == 2{
                                self.columns.removeLast()
                            }
                            else{
                                self.columns.append(GridItem(.flexible(), spacing: 15))
                            }
                        }
                    } label: {
                        Image(systemName: self.columns.count == 2 ? "rectangle.grid.1x2" : "square.grid.2x2")
                            .font(.system(size: 24))
                            .foregroundColor(.black)
                    }
                }
                .padding(.horizontal)
                 
                TextField("Search", text: self.$search)
                    .padding(.vertical,10)
                    .padding(.horizontal)
                    .background(Color.black.opacity(0.07))
                    .cornerRadius(10)
                    .padding(.horizontal)
                    .padding(.top,25)
                
                VStack {
                    Text("There are \(posts.count) posts")
                        .font(.title3)
                        .multilineTextAlignment(.leading)
                    
                    LazyVGrid(columns: self.columns,spacing: 25){
                        ForEach(posts) { post in
                            PostView(postsview: post, columns: self.$columns, setid: post.userId)
                        }
                    }
                    .padding([.horizontal,.top])
                }
                
            }//End LazyStack
            
        }
    }
}

struct PostView: View {
    
    let postsview: Post
    @Binding var columns : [GridItem]
    @Namespace var namespace
    @State var show = false
    @State var setid: Int
    
    var body: some View {
        VStack(spacing: 15){
            ZStack(alignment: Alignment(horizontal: .trailing, vertical: .top)) {
                  
                Image(postsview.postimage)
                    .resizable()
                    .frame(height: 250)
                    .cornerRadius(15)
                 
                Button {
                } label: {
                  
                    Image(systemName: "heart.fill")
                        .foregroundColor(.red)
                        .padding(.all,10)
                        .background(Color.white)
                        .clipShape(Circle())
                }
                .padding(.all,10)

            }
            .matchedGeometryEffect(id: "image", in: self.namespace)
              
            Text(postsview.title)
                .fontWeight(.bold)
                .lineLimit(1)
                .matchedGeometryEffect(id: "title", in: self.namespace)

            Button {
                setid = (postsview.userId)
                show.toggle()
            } label: {
              
                Text("Learn More")
                    .foregroundColor(.white)
                    .padding(.vertical,10)
                    .padding(.horizontal,25)
                    .background(Color.green)
                    .cornerRadius(5)
            }
            .matchedGeometryEffect(id: "learnmore", in: self.namespace)
            .sheet(isPresented: $show, content: {
                Details(setid: setid, data: postsview)
            })
             
        }//End VStack
        .onAppear {
            print("onAppear post = \(postsview.id) \(postsview.userId)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Details.swift
 
//
//  Details.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct Details: View {
    
    var setid: Int
    var data : Post
    
    var body: some View {
        //Text("\(setid)")
        //Text(data.title)
        ScrollView {
            VStack {
                Image(data.postimage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .clipped()
            }
            .frame(height: 400)
             
            VStack(alignment: .leading) {
                HStack {
                    Image("photo1")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 60, height: 60)
                        .clipped()
                        .cornerRadius(10)
                    VStack(alignment: .leading) {
                        Text("Article by")
                            .font(.title3)
                            .foregroundColor(.gray)
                        Text("Cairocoders")
                            .font(.title3)
                    }
                }
                .padding(.top, 20)
                 
                Text(data.title)
                    .font(.largeTitle)
                    .lineLimit(nil)
                    .padding(.top, 10)
                Text("23 min read • 22. July 2020")
                    .font(.title3)
                    .foregroundColor(.gray)
                    .padding(.top, 10)
                Text(data.body)
                    .font(.title2)
                    .lineLimit(nil)
                    .padding(.top, 30)
                 
            }//End VStack
            .frame(width: 350)
        }
        .edgesIgnoringSafeArea(.top)
    }
}

struct Details_Previews: PreviewProvider {
    static var previews: some View {
        Details(setid: 1, data: Post(userId: 1, title: "Sample Title", body: "Sample Body", postimage: "post1"))
    }
}
Model.swift
 
//
//  Model.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation
struct Post: Identifiable {
    let id = UUID()
    let userId: Int
    let title: String
    let body: String
    let postimage: String
}

let posts: [Post] = [
    Post(
        userId: 1,
        title: "How to easily share tweets to Instagram Stories in iOS",
        body: "Twitter rolled out an update to its iOS app earlier this week that lets users quickly and easily share tweets to their Instagram Stories. It’s now nearly a one-click operation, but not quite.",
        postimage: "post1"),
    Post(
        userId: 2,
        title: "Hands on: Safari in iOS 15 takes some getting used to, but it’s worth it",
        body: "The most controversial change in iOS 15 — moving Safari’s Address Bar to the bottom of the screen — doesn’t deserve the deluge of criticism some users are heaping upon it. I tried out the latest iOS 15 beta to check out that feature, plus the new Tab Groups and other changes coming to Safari. Here’s what I like and what I don’t.",
        postimage: "post2"),
    Post(
        userId: 3,
        title: "Sonic the Hedgehog speeds onto Minecraft to celebrate 30th birthday",
        body: "It’s somehow been 30 years since Sega’s rapid blue hedgehog mascot, Sonic, first speeded his way onto the Genesis and into video game history on June 23, 1991.",
        postimage: "post3"),
    Post(
        userId: 4,
        title: "Boring iOS 15 shows just how far iPhone has come",
        body: "iOS 15 is kind of boring. It brings some welcome new features, but nothing that will change the way you use your iPhone forever.",
        postimage: "post4"),
    Post(
        userId: 5,
        title: "How to easily share tweets to Instagram Stories in iOS",
        body: "Twitter rolled out an update to its iOS app earlier this week that lets users quickly and easily share tweets to their Instagram Stories. It’s now nearly a one-click operation, but not quite.",
        postimage: "post1"),
    Post(
        userId: 6,
        title: "Hands on: Safari in iOS 15 takes some getting used to, but it’s worth it",
        body: "The most controversial change in iOS 15 — moving Safari’s Address Bar to the bottom of the screen — doesn’t deserve the deluge of criticism some users are heaping upon it. I tried out the latest iOS 15 beta to check out that feature, plus the new Tab Groups and other changes coming to Safari. Here’s what I like and what I don’t.",
        postimage: "post2"),
    Post(
        userId: 7,
        title: "Sonic the Hedgehog speeds onto Minecraft to celebrate 30th birthday",
        body: "It’s somehow been 30 years since Sega’s rapid blue hedgehog mascot, Sonic, first speeded his way onto the Genesis and into video game history on June 23, 1991.",
        postimage: "post3"),
    Post(
        userId: 8,
        title: "Hands on: Safari in iOS 15 takes some getting used to, but it’s worth it",
        body: "The most controversial change in iOS 15 — moving Safari’s Address Bar to the bottom of the screen — doesn’t deserve the deluge of criticism some users are heaping upon it. I tried out the latest iOS 15 beta to check out that feature, plus the new Tab Groups and other changes coming to Safari. Here’s what I like and what I don’t.",
        postimage: "post2"),
    Post(
        userId: 9,
        title: "How to easily share tweets to Instagram Stories in iOS",
        body: "Twitter rolled out an update to its iOS app earlier this week that lets users quickly and easily share tweets to their Instagram Stories. It’s now nearly a one-click operation, but not quite.",
        postimage: "post1")
]

Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database

Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database

load dynamic data from the database using jqueryui tooltip

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

https://jqueryui.com/

Tooltip : https://jqueryui.com/tooltip/

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');

app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan"

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 
  
@app.route('/')
def index(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id ASC")
    employeelist = cur.fetchall()
    return render_template('index.html', employeelist=employeelist)
 
@app.route("/fetchdata",methods=["POST","GET"])
def fetchdata():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        id = request.form['id']
        cur.execute("SELECT * FROM employee WHERE id = %s", [id])
        rs = cur.fetchone() 
        name = rs['name']
        photo = rs['photo']
        position = rs['position']
        office = rs['office']
        print(photo)
    return jsonify({'htmlresponse': render_template('response.html', name=name, photo=photo, position=position, office=office)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>  
<div class="container">
   <br />
   <h3 align="center">Display Popups data on mouse hover using Jquery Ajax and Python Flask PostgreSQL database </a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-12">
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                        </tr>
                        </thead> 
                        {% for row in employeelist %}
                            <tr>
                                <td><a href="#" id="{{row.id}}" title=" "><img src="/static/images/{{row.photo}}" height="50" width="50"/></a></td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                            </tr>
                        {% endfor %} 
                </table>
            </div>
      </div>
     </div>
    </div>
  </div>
<script>  
$(document).ready(function(){ 
    $('a').tooltip({
        classes:{
            "ui-tooltip":"highlight"
        },
        position:{ my:'left center', at:'right+50 center'},
        content:function(result){
            $.post('/fetchdata', {
                id:$(this).attr('id')
            }, function(data){
                result(data.htmlresponse);
                 
            });
        }
    });
});  
</script>
</body>  
</html>
templates/response.html
//templates/response.html
<p align="center"><img src="/static/images/{{photo}}" class="img-thumbnail" /></p>
<p>Name : {{ name }}</p>
<p>Position : {{ position }}</p>
<p>Office : {{ office }}</p>

Related Post