article

Thursday, July 7, 2016

Laravel - Routing

Laravel - Routing

Basic RoutingBasic routing is meant to route your request to an appropriate controller. The routes of the application can be defined in app/Http/routes.php file.

Example
app/Http/routes.php


 
Route::get('/', function () {
   return view('welcome');
});
resources/view/welcome.blade.php
<!DOCTYPE html>
<html>
   
   <head>
      <title>Laravel</title>
      <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" 
         type = "text/css">
      
      <style>
         html, body {
            height: 100%;
         }
         body {
            margin: 0;
            padding: 0;
            width: 100%;
            display: table;
            font-weight: 100;
            font-family: 'Lato';
         }
         .container {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
         }
         .content {
            text-align: center;
            display: inline-block;
         }
         .title {
            font-size: 96px;
         }
      </style>
   </head>
   
   <body>
      <div class = "container">
         
         <div class = "content">
            <div class = "title">Laravel 5</div>
         </div>
   
      </div>
   </body>

</html>
Step 1 − First, we need to execute the root URL of the application.

Step 2 − The executed URL will match with the appropriate method in the route.php file. In our case, it will match to get the method and the root (‘/’) URL. This will execute the related function.

Step 3 − The function calls the template file resources/views/welcome.blade.php. The function later calls the view() function with argument ‘welcome’ without using the blade.php. It will produce the following HTML output.

Routing Parameters 
 
<?php
// First Route method – Root URL will match this method
Route::get('/', function () {
   return view('welcome');
});

// Second Route method – Root URL with ID will match this method
Route::get('ID/{id}',function($id){
   echo 'ID: '.$id;
});

// Third Route method – Root URL with or without name will match this method
Route::get('/user/{name?}',function($name = 'Virat Gandhi'){
   echo "Name: ".$name;
});

Here, we have defined 3 routes with get methods for different purposes. If we execute the below URL then it will execute the first method.

http://localhost:8000

If we execute the below URL, it will execute the 2nd method and the argument/parameter ID will be passed to the variable $id.

http://localhost:8000/ID/5

After successful execution of the URL, you will receive the following output − ID: 5

If we execute the below URL, it will execute the 3rd method and the optional argument/parameter name will be passed to the variable $name.

http://localhost:8000/user/tutorial101

After successful execution of the URL, you will receive the following output −  Name: tutorial101

Laravel - Configuration


Laravel - Configuration 

Basic Configuration

After installing Laravel, the first thing we need to do is to set the write permission for the directory storage and bootstrap/cache.

Generate Application key to secure session and other encrypted data. If the root directory doesn’t contain the .env file then rename the .env.example to .env file and execute the following command where you have installed Laravel. The newly generated key can be seen in the .env file.

 You can also configure the locale, time zone, etc. of the application in the config/app.php file.

 Environmental Configuration

rename the .env.example file to .env file.


Database Configuration

The database of your application can be configured from config/database.php file.


PHP MySqli Basic usage (select, insert & update)

PHP MySqli Basic usage (select, insert & update) 

<?php
//Connect to Database
$mysqli =  mysqli_connect('host','username','password','database_name');
//object oriented style (recommended)
$mysqli = new mysqli('host','username','password','database_name');

$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

//-----------------------------------------------------------------
//SELECT Multiple Records as Associative array
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1">';
while($row = $results->fetch_assoc()) {
    print '<tr>';
    print '<td>'.$row["id"].'</td>';
    print '<td>'.$row["product_code"].'</td>';
    print '<td>'.$row["product_name"].'</td>';
    print '<td>'.$row["product_desc"].'</td>';
    print '<td>'.$row["price"].'</td>';
    print '</tr>';
}  
print '</table>';
// Frees the memory associated with a result
$results->free();
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Multiple Records as Array
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1"';
while($row = $results->fetch_array()) {
    print '<tr>';
    print '<td>'.$row["id"].'</td>';
    print '<td>'.$row["product_code"].'</td>';
    print '<td>'.$row["product_name"].'</td>';
    print '<td>'.$row["product_desc"].'</td>';
    print '<td>'.$row["price"].'</td>';
    print '</tr>';
}   
print '</table>';
// Frees the memory associated with a result
$results->free();
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Multiple Records as Objects
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT id, product_code, product_desc, price FROM products");
print '<table border="1">';
while($row = $results->fetch_object()) {
    print '<tr>';
    print '<td>'.$row->id.'</td>';
    print '<td>'.$row->product_code.'</td>';
    print '<td>'.$row->product_name.'</td>';
    print '<td>'.$row->product_desc.'</td>';
    print '<td>'.$row->price.'</td>';
    print '</tr>';
}  
print '</table>';
// close connection 
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Single value
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//chained PHP functions
$product_name = $mysqli->query("SELECT product_name FROM products WHERE id = 1")->fetch_object()->product_name; 
print $product_name; //output value
$mysqli->close();

//-----------------------------------------------------------------
//SELECT COUNT Total records of a table
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get total number of records
$results = $mysqli->query("SELECT COUNT(*) FROM users");
$get_total_rows = $results->fetch_row(); //hold total records in variable
$mysqli->close();

//-----------------------------------------------------------------
//SELECT Using Prepared Statements
$search_product = "PD1001"; //product id
//create a prepared statement
$query = "SELECT id, product_code, product_desc, price FROM products WHERE product_code=?";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('s', $search_product);
//execute query
$statement->execute();
//bind result variables
$statement->bind_result($id, $product_code, $product_desc, $price);
print '<table border="1">';
//fetch records
while($statement->fetch()) {
    print '<tr>';
    print '<td>'.$id.'</td>';
    print '<td>'.$product_code.'</td>';
    print '<td>'.$product_desc.'</td>';
    print '<td>'.$price.'</td>';
    print '</tr>';
}   
print '</table>';
//close connection
$statement->close();

//Same query with multiple parameters:
$search_ID = 1; 
$search_product = "PD1001"; 
$query = "SELECT id, product_code, product_desc, price FROM products WHERE ID=? AND product_code=?";
$statement = $mysqli->prepare($query);
$statement->bind_param('is', $search_ID, $search_product);
$statement->execute();
$statement->bind_result($id, $product_code, $product_desc, $price);
print '<table border="1">';
while($statement->fetch()) {
    print '<tr>';
    print '<td>'.$id.'</td>';
    print '<td>'.$product_code.'</td>';
    print '<td>'.$product_desc.'</td>';
    print '<td>'.$price.'</td>';
    print '</tr>';

}   
print '</table>';
//close connection
$statement->close();

//-----------------------------------------------------------------
//INSERT a Record
//values to be inserted in database table
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
    print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
//Prepared Statement
//Prepared statements are very effective against SQL injection
//values to be inserted in database table
$product_code = 'P1234';
$product_name = '42 inch TV';
$product_price = '600';
$query = "INSERT INTO products (product_code, product_name, price) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('sss', $product_code, $product_name, $product_price);
if($statement->execute()){
    print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();

//-----------------------------------------------------------------
//Insert Multiple Records
//product 1
$product_code1 = '"'.$mysqli->real_escape_string('P1').'"';
$product_name1 = '"'.$mysqli->real_escape_string('Google Nexus').'"';
$product_price1 = '"'.$mysqli->real_escape_string('149').'"';
//product 2
$product_code2 = '"'.$mysqli->real_escape_string('P2').'"';
$product_name2 = '"'.$mysqli->real_escape_string('Apple iPad 2').'"';
$product_price2 = '"'.$mysqli->real_escape_string('217').'"';
//product 3
$product_code3 = '"'.$mysqli->real_escape_string('P3').'"';
$product_name3 = '"'.$mysqli->real_escape_string('Samsung Galaxy Note').'"';
$product_price3 = '"'.$mysqli->real_escape_string('259').'"';
//Insert multiple rows
$insert = $mysqli->query("INSERT INTO products(product_code, product_name, price) VALUES
($product_code1, $product_name1, $product_price1),
($product_code2, $product_name2, $product_price2),
($product_code3, $product_name3, $product_price3)");
if($insert){
    //return total inserted records using mysqli_affected_rows
    print 'Success! Total ' .$mysqli->affected_rows .' rows added.<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}

//-----------------------------------------------------------------
//Update/Delete a Records
//Updating and deleting records works similar way, just change to query string to MySql Update or delete
//MySqli Update Query
$results = $mysqli->query("UPDATE products SET product_name='52 inch TV', product_code='323343' WHERE ID=24");
//MySqli Delete Query
//$results = $mysqli->query("DELETE FROM products WHERE ID=24");
if($results){
    print 'Success! record updated / deleted'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}

//-----------------------------------------------------------------
//Update using Prepared Statement
$product_name = '52 inch TV';
$product_code = '9879798';
$find_id = 1;
$statement = $mysqli->prepare("UPDATE products SET product_name=?, product_code=? WHERE ID=?");
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('ssi', $product_name, $product_code, $find_id);
$results =  $statement->execute();
if($results){
    print 'Success! record updated'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}

//Delete Old Records
//Delete all records that is 1 day old, or specify X days records you want to delete.
//MySqli Delete Query
$results = $mysqli->query("DELETE FROM products WHERE added_timestamp < (NOW() - INTERVAL 1 DAY)");
if($results){
    print 'Success! deleted one day old records'; 
}else{
    print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}
?>

Sunday, July 3, 2016

Laravel Application Structure

Laravel Application Structure 

app − This directory contains the core code of the application.
bootstrap − This directory contains the application bootstrapping script.
config − This directory contains configuration files of application.
database − This folder contains your database migration and seeds.
public − This is the application’s document root. It starts the Laravel application. It also contains the assets of the application like JavaScript, CSS, Images, etc.
resources − This directory contains raw assets such as the LESS & Sass files, localization and language files, and Templates that are rendered as HTML.
storage − This directory contains App storage, like file uploads etc. Framework storage (cache), and application-generated logs.
test − This directory contains various test cases.
vendor − This directory contains composer dependencies.

App Directory

This is the application directory. It contains a variety of additional directories, which are described below −

Console − All the artisan commands are stored in this directory.

Events − This directory stores events that your application can raise. Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling.

Exceptions − This directory contains your application's exception handler and is also a good place to stick any exceptions thrown by your application.

Http − This directory contains your controllers, filters, and requests.

Jobs − This directory contains the queueable jobs for your application.

Listeners − This directory contains the handler classes for your events. Handlers receive an event and perform logic in response to the event being fired. For example, a UserRegistered event might be handled by a SendWelcomeEmail listener.

Policies − This directory contains various policies of the application

Providers − This directory contains various service providers.

Saturday, July 2, 2016

Laravel - Installation

Laravel

Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell.Laravel is an MVC framework with bundles, migrations, and Artisan CLI. Laravel offers a robust set of tools and an application architecture that incorporates many of the best features of frameworks like CodeIgniter, Yii, ASP.NET MVC, Ruby on Rails, Sinatra, and others. Laravel is an Open Source framework. It has a very rich set of features which will boost the speed of Web Development. If you familiar with Core PHP and Advanced PHP, Laravel will make your task easier. It will save a lot time if you are planning to develop a website from scratch. Not only that, the website built in Laravel is also secure. Laravel uses composer. Make sure you have a Composer installed on your system before you install Laravel.

Step 1 − Visit the following URL and download composer to install it on your system.

https://getcomposer.org/download/

Step 2 − After the Composer is installed, check the installation by typing the Composer command in the command prompt as shown in the following screenshot.


Step 3 − Create a new directory anywhere in your system for your new Laravel project. After that, move to path where you have created the new directory and type the following command there to install Laravel.

composer create-project laravel/laravel –prefer-dist 

Step 4 − The above command will install Laravel in the current directory. Start the Laravel service by executing the following command.

php artisan serve

Step 5 − Copy the URL or http://localhost/laravel/ and open that URL in the browser. If you see the Laravel 5 screen, it implies Laravel has been installed successfully.

Friday, June 24, 2016

Wordpress - You do not have sufficient permissions to access this page.

Wordpress - You do not have sufficient permissions to access this page.

You should check your wp-config.php file and if you find this line
define('DISALLOW_FILE_MODS',true);
change its value to false:
define('DISALLOW_FILE_MODS',false);
 

Sunday, June 12, 2016

Python Django - Creating Simple Views

Python Django - Creating Simple Views

In Django, views have to be created in the app views.py file.

See the following view −


 
from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

A template: myapp/templates/hello.html
myapp\templates\hello.html

add url C:\myprojectdjango\myprojectdjango\urls.py

 
from django.conf.urls import patterns, include, url
from django.contrib import admin

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),)

Run
python manage.py runserver 
http://127.0.0.1:8000/hello/

Saturday, June 11, 2016

Python Django - Apps Life Cycle

Python Django - Apps Life Cycle

Every application has an objective and can be reused into another project, like the contact form on a website can be an application, and can be reused for others.

Create an Application

We assume you are in your project folder. In our main “myprojectdjango” folder, the same folder than manage.py −

C:\myprojectdjango>python manage.py startapp myapp

You just created myapp application and like project, Django create a “myapp” folder with the application structure −

myapp/
   __init__.py
   admin.py
   models.py
   tests.py
   views.py

__init__.py − Just to make sure python handles this folder as a package.
admin.py − This file helps you make the app modifiable in the admin interface.
models.py − This is where all the application models are stored.
tests.py − This is where your unit tests are.
views.py − This is where your application views are.

Get the Project to Know About Your Application

we have our "myapp" application, now we need to register it with our Django project "myprojectdjango". To do so, update INSTALLED_APPS tuple in the settings.py file of your project (add your app name) −

myprojectdjango\myprojectdjango\settings.py

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp', #created application myapp folder
)

Python Flask - Sending Form Data to Template and Cookies

Python Flask - Sending Form Data to Template and Cookies
 
Flask – Sending Form Data to Template

In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to table.html.
 
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('student.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/
#if click submet call result http://127.0.0.1:5000/result   
Given below is the HTML script of student.html.

   
      
Name
Physics
Chemistry
Maths

Code of template (result.html) is given below −

   
      
         {% for key, value in result.iteritems() %}

{% endfor %}
      
{{ key }} {{ value }}
Flask – Cookies
A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie.
from flask import Flask, render_template, request,make_response
app = Flask(__name__)

@app.route('/') # http://localhost:5000/
def index():
   return render_template('index.html')
 
@app.route('/setcookie', methods = ['POST', 'GET']) # http://localhost:5000/setcookie
def setcookie():
   if request.method == 'POST':
      user = request.form['nm']
    
   resp = make_response(render_template('readcookie.html'))
   resp.set_cookie('userID', user)
    
   return resp
 
@app.route('/getcookie') # http://localhost:5000/getcookie
def getcookie():
   name = request.cookies.get('userID')
   return '

welcome '+name+'

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

   
      

Enter userID




Python Flask HTTP Method, Templates, Static Files

Python Flask

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.

The following table summarizes different http methods −

GET
Sends data in unencrypted form to the server. Most common method.   
HEAD
Same as GET, but without response body   
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.   
PUT
Replaces all current representations of the target resource with the uploaded content.   
DELETE
Removes all current representations of the target resource given by a URL

demonstrate the use of POST method in URL routing


   
      
      
Enter Name:
Now enter the following script in Python shell.
 
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)
Flask – Templates
Jinja2 template. HTML file can be engine rendered by the render_template() function
 
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('hello.html')

if __name__ == '__main__':
   app.run(debug = True)
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
Application folder
  • Hello.py
  • templates
    • hello.html
The following code is saved as hello.html in the templates folder.

   
      

Hello {{ name }}!

Next, run the following script from Python shell.
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost:5000/hello/tutorial101
The variable part of URL is inserted at {{ name }} place holder.

The Jinga2 template engine uses the following delimiters for escaping from HTML.

{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements

following example, use of conditional statement in the template is demonstrated.

 
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)
#http://localhost/hello/60
HTML template script of hello.html is as follows −

   
   
      {% if marks>50 %}
      

Your result is pass!

{% else %}

Your result is fail

{% endif %} Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}
Flask – Static Files
A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. these files are served from static folder in your package or next to your module and it will be available at /static on the application. In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)
   
   
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>
 
from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)
The HTML script of index.html is given below.

   
      
   
   
      
   

Hello.js contains sayHello() function.
 function sayHello() {
   alert("Hello World")
}

Python Flask Routing, Variable rules, URL Building

Python Flask - Routing, Variable rules, URL Building

Flask – Routing

The route() decorator in Flask is used to bind URL to a function. For example −


 
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
   return 'hello world'

if __name__ == '__main__':
   app.run()
   
#http://127.0.0.1:5000/hello
Flask – Variable Rules It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as . It is passed as a keyword argument to the function with which the rule is associated.
 
from flask import Flask
app = Flask(__name__)

@app.route('/hello/')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/hello/tutorial101
The following output will be displayed in the browser.
Hello tutorial101!
In the following code, all these constructors are used.
 
from flask import Flask
app = Flask(__name__)

@app.route('/blog/')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()
#http://127.0.0.1:5000/blog/11
#http://localhost:5000/rev/1.1
The given number is used as argument to the show_blog() function. The browser displays the following output −
Blog Number 11
Revision Number 1.100000
Flask – URL Building
The url_for() function is very useful for dynamically building a URL for a specific function.
The following script demonstrates use of url_for() function.
 
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/admin
#http://127.0.0.1:5000/guest/ednalan
#http://127.0.0.1:5000/guest/ednalan   
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.
The application response in browser is −
Hello Admin
Hello mvl as Guest

Python Flask install and run

 Python Flask Install and run

Flask is a web application framework written in Python. Armin Ronacher, who leads an international group of Python enthusiasts named Pocco, develops it. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.

1. Create folder name flaskmyproject
2. py -3 -m venv venv
3. venv\Scripts\activate
4. pip install flask
5. flask --version
6. mkdir demoapp
7. flask run

http://127.0.0.1:5000/

app.py
 
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello Worlddfdsf'

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

RUN
C:\>cd flaskmyproject
C:\flaskmyproject>venv\Scripts\activate
(venv) C:\flaskmyproject>cd demoapp
(venv) C:\flaskmyproject\demoapp>flask run
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Python How to check if a network port is open

Python How to check if a network port is open
 
import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

Friday, June 10, 2016

Python read csv

Python read csv
 
import csv

csvfilename = "server_L2.csv"

print "Printing all rows"
with open(csvfilename, 'rb') as csvfile:
 reader = csv.reader(csvfile, delimiter='\t')
 for row in reader:
  print "   ", row
print ""

print "Printing all rows using header line"
with open(csvfilename) as csvfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    for row in reader:
        print "   ", row
print ""

wxpython widgets wx.ListCtrl

wxpython widgets wx.ListCtrl

A wx.ListCtrl is a graphical representation of a list of items

wx.ListCtrl styles

wx.LC_LIST
wx.LC_REPORT
wx.LC_VIRTUAL
wx.LC_ICON
wx.LC_SMALL_ICON
wx.LC_ALIGN_LEFT
wx.LC_EDIT_LABELS
wx.LC_NO_HEADER
wx.LC_SORT_ASCENDING
wx.LC_SORT_DESCENDING
wx.LC_HRULES
wx.LC_VRULES
 
import wx
import sys

packages = [('jessica alba', 'pomona', '1981'), ('sigourney weaver', 'new york', '1949'),
    ('angelina jolie', 'los angeles', '1975'), ('natalie portman', 'jerusalem', '1981'),
    ('rachel weiss', 'london', '1971'), ('scarlett johansson', 'new york', '1984' )]



class Actresses(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(380, 230))

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        panel = wx.Panel(self, -1)

        self.list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT) #We create a wx.ListCtrl with a wx.LC_REPORT style
        self.list.InsertColumn(0, 'name', width=140)
        self.list.InsertColumn(1, 'place', width=130)
        self.list.InsertColumn(2, 'year', wx.LIST_FORMAT_RIGHT, 90)

        for i in packages:
            index = self.list.InsertStringItem(sys.maxint, i[0])
            self.list.SetStringItem(index, 1, i[1])
            self.list.SetStringItem(index, 2, i[2])

        hbox.Add(self.list, 1, wx.EXPAND)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

app = wx.App()
Actresses(None, -1, 'actresses')
app.MainLoop()

wxpython widgets wx.html Help window

wxpython widgets wx.html Help window

 wx.html.HtmlWindow to provide help in our application. We can create a standalone window or we can create a window that is going to be a part of the application. The following script will create a help window using the latter idea.
 
import wx
import wx.html as html

class HelpWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(570, 400))

        toolbar = self.CreateToolBar()
        toolbar.AddLabelTool(1, 'Exit', wx.Bitmap('img/quit.png'))
        toolbar.AddLabelTool(2, 'Help', wx.Bitmap('img/help.png'))
        toolbar.Realize()

        self.splitter = wx.SplitterWindow(self, -1)
        self.panelLeft = wx.Panel(self.splitter, -1, style=wx.BORDER_SUNKEN)

        self.panelRight = wx.Panel(self.splitter, -1)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        header = wx.Panel(self.panelRight, -1, size=(-1, 20))
        header.SetBackgroundColour('#6f6a59')
        header.SetForegroundColour('WHITE')
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        st = wx.StaticText(header, -1, 'Help', (5, 5))
        font = st.GetFont()
        font.SetPointSize(9)
        st.SetFont(font)
        hbox.Add(st, 1, wx.TOP | wx.BOTTOM | wx.LEFT, 5)

        close = wx.BitmapButton(header, -1, wx.Bitmap('img/quit.png', wx.BITMAP_TYPE_PNG), 
  style=wx.NO_BORDER)
        close.SetBackgroundColour('#6f6a59')
        hbox.Add(close, 0)
        header.SetSizer(hbox)

        vbox2.Add(header, 0, wx.EXPAND)

        help = html.HtmlWindow(self.panelRight, -1, style=wx.NO_BORDER)
        help.LoadPage('help.html')
        vbox2.Add(help, 1, wx.EXPAND)
        self.panelRight.SetSizer(vbox2)
        self.panelLeft.SetFocus()

        self.splitter.SplitVertically(self.panelLeft, self.panelRight)
        self.splitter.Unsplit()

        self.Bind(wx.EVT_BUTTON, self.CloseHelp, id=close.GetId())
        self.Bind(wx.EVT_TOOL, self.OnClose, id=1)
        self.Bind(wx.EVT_TOOL, self.OnHelp, id=2)

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)

        self.CreateStatusBar()

        self.Centre()
        self.Show(True)

    def OnClose(self, event):
        self.Close()

    def OnHelp(self, event):
        self.splitter.SplitVertically(self.panelLeft, self.panelRight)
        self.panelLeft.SetFocus()

    def CloseHelp(self, event):
        self.splitter.Unsplit()
        self.panelLeft.SetFocus()

    def OnKeyPressed(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_F1:
            self.splitter.SplitVertically(self.panelLeft, self.panelRight)
            self.panelLeft.SetFocus()


app = wx.App()
HelpWindow(None, -1, 'HelpWindow')
app.MainLoop()
help.html



Table of Contents

Basic Statistics
Overview of elementary concepts in statistics. Variables. Correlation. Measurement scales. Statistical significance. Distributions. Normality assumption.

Advanced Statistics
Overview of advanced concepts in statistics. Anova. Linear regression. Estimation and hypothesis testing. Error terms.

Introducing Newt
Introducing the basic functionality of the Newt application. Creating sheets. Charts. Menus and Toolbars. Importing data. Saving data in various formats. Exporting data. Shortcuts. List of methods.

Charts
Working with charts. 2D charts. 3D charts. Bar, line, box, pie, range charts. Scatterplots. Histograms.

Predicting values
Time series and forecasting. Trend Analysis. Seasonality. Moving averages. Univariate methods. Multivariate methods. Holt-Winters smoothing. Exponential smoothing. ARIMA. Fourier analysis.

Neural networks
Overview of neural networks. Biology behind neural networks. Basic artificial Model. Training. Preprocessing. Postprocessing. Types of neural networks.

Glossary
Terms and definitions in statistics.

wxpython widgets wx.html.HtmlWindow

wxpython widgets wx.html.HtmlWindow

The wx.html.HtmlWindow widget displays HTML pages. It is not a full-fledged browser. We can do interesting things with wx.html.HtmlWindow widget.
 
import wx
import wx.html as html

ID_CLOSE = 1

page = ' \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
 \
  Maximum  9000
  Mean  6076
  Minimum  3800
  Median  6000
  Standard Deviation  6076
' class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(400, 290)) panel = wx.Panel(self, -1) vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) htmlwin = html.HtmlWindow(panel, -1, style=wx.NO_BORDER) htmlwin.SetBackgroundColour(wx.RED) htmlwin.SetStandardFonts() htmlwin.SetPage(page) vbox.Add((-1, 10), 0) vbox.Add(htmlwin, 1, wx.EXPAND | wx.ALL, 9) bitmap = wx.StaticBitmap(panel, -1, wx.Bitmap('img/sales.png')) hbox.Add(bitmap, 1, wx.LEFT | wx.BOTTOM | wx.TOP, 10) buttonOk = wx.Button(panel, ID_CLOSE, 'Ok') self.Bind(wx.EVT_BUTTON, self.OnClose, id=ID_CLOSE) hbox.Add((100, -1), 1, wx.EXPAND | wx.ALIGN_RIGHT) hbox.Add(buttonOk, flag=wx.TOP | wx.BOTTOM | wx.RIGHT, border=10) vbox.Add(hbox, 0, wx.EXPAND) panel.SetSizer(vbox) self.Centre() self.Show(True) def OnClose(self, event): self.Close() app = wx.App(0) MyFrame(None, -1, 'Basic Statistics') app.MainLoop()

Java Swing


Java Swing

Swing is the principal GUI toolkit for the Java programming language. It is a part of the JFC (Java Foundation Classes), which is an API for providing a graphical user interface for Java programs. It is completely written in Java.
 
package com.tutorial101;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class SimpleEx extends JFrame {

    public SimpleEx() {

        initUI();
    }

    private void initUI() {
        
        setTitle("Simple example"); //window title
        setSize(300, 200); //size window
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() { //This method will close the window if we click on the close button of the titlebar
        
            @Override
            public void run() {
                SimpleEx ex = new SimpleEx();
                ex.setVisible(true);
            }
        });
    }
}

Saturday, June 4, 2016

wxpython advance widgets wx.ListBox

wxpython advance widgets wx.ListBox

A wx.ListBox widget is used for displaying and working with a list of items
 
import wx

ID_NEW = 1
ID_RENAME = 2
ID_CLEAR = 3
ID_DELETE = 4


class ListBox(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 220))

        panel = wx.Panel(self, -1)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.listbox = wx.ListBox(panel, -1) #create an empty wx.ListBox
        hbox.Add(self.listbox, 1, wx.EXPAND | wx.ALL, 20) # put a 20px border around the listbox

        btnPanel = wx.Panel(panel, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        new = wx.Button(btnPanel, ID_NEW, 'New', size=(90, 30))
        ren = wx.Button(btnPanel, ID_RENAME, 'Rename', size=(90, 30))
        dlt = wx.Button(btnPanel, ID_DELETE, 'Delete', size=(90, 30))
        clr = wx.Button(btnPanel, ID_CLEAR, 'Clear', size=(90, 30))

        self.Bind(wx.EVT_BUTTON, self.NewItem, id=ID_NEW)
        self.Bind(wx.EVT_BUTTON, self.OnRename, id=ID_RENAME)
        self.Bind(wx.EVT_BUTTON, self.OnDelete, id=ID_DELETE)
        self.Bind(wx.EVT_BUTTON, self.OnClear, id=ID_CLEAR)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnRename) #bind a wx.EVT_COMMAND_LISTBOX_DOUBLE_CLICKED event type with the OnRename() method

        vbox.Add((-1, 20))
        vbox.Add(new)
        vbox.Add(ren, 0, wx.TOP, 5)
        vbox.Add(dlt, 0, wx.TOP, 5)
        vbox.Add(clr, 0, wx.TOP, 5)

        btnPanel.SetSizer(vbox)
        hbox.Add(btnPanel, 0.6, wx.EXPAND | wx.RIGHT, 20)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

    def NewItem(self, event):
        text = wx.GetTextFromUser('Enter a new item', 'Insert dialog')
        if text != '':
            self.listbox.Append(text)

    def OnRename(self, event):
        sel = self.listbox.GetSelection()
        text = self.listbox.GetString(sel)
        renamed = wx.GetTextFromUser('Rename item', 'Rename dialog', text)
        if renamed != '':
            self.listbox.Delete(sel)
            self.listbox.Insert(renamed, sel)


    def OnDelete(self, event):
        sel = self.listbox.GetSelection()
        if sel != -1:
            self.listbox.Delete(sel)

    def OnClear(self, event):
        self.listbox.Clear()


app = wx.App()
ListBox(None, -1, 'ListBox')
app.MainLoop()

wxpython widgets wx.SpinCtrl

wxpython widgets wx.SpinCtrl

The wx.SpinCtrl widget lets us increment and decrement a value. It has two up and down arrow buttons for this purpose. 
 
import wx


class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
    def InitUI(self):   

        pnl = wx.Panel(self)

        
        wx.StaticText(self, label='Convert Fahrenheit temperature to Celsius', 
            pos=(20,20))
        wx.StaticText(self, label='Fahrenheit: ', pos=(20, 80))
        wx.StaticText(self, label='Celsius: ', pos=(20, 150))
        
        self.celsius = wx.StaticText(self, label='', pos=(150, 150))
        self.sc = wx.SpinCtrl(self, value='0', pos=(150, 75), size=(60, -1))
        self.sc.SetRange(-459, 1000)
        
        btn = wx.Button(self, label='Compute', pos=(70, 230))
        btn.SetFocus()
        cbtn = wx.Button(self, label='Close', pos=(185, 230))

        btn.Bind(wx.EVT_BUTTON, self.OnCompute)
        cbtn.Bind(wx.EVT_BUTTON, self.OnClose)
           
        self.SetSize((350, 310))
        self.SetTitle('wx.SpinCtrl')
        self.Centre()
        self.Show(True)          
        
    def OnClose(self, e):
        
        self.Close(True)    
        
    def OnCompute(self, e):
        
        fahr = self.sc.GetValue()
        cels = round((fahr - 32) * 5 / 9.0, 2)
        self.celsius.SetLabel(str(cels))        
                      
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    

if __name__ == '__main__':
    main()   

Related Post