Tuesday, November 20, 2018

Postgres usefull query

PostgreSQL Useful Queries


If you are programmer or DB administrator you need some useful query like how much data occupied by one database or how much data is for single or multiple tables, Below are useful queries.



Open terminal

psql -d test  #Login to your database which you want to know size.

SELECT pg_database_size(‘test’); # Check database size in Octal format.

SELECT pg_size_pretty(pg_database_size(‘test’)); # Check database size in actual format.

SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) AS size FROM pg_database; # Check all database size

SELECT pg_size_pretty(pg_relation_size(‘users’)); # Check particular table size

SELECT pg_size_pretty(pg_total_relation_size(‘users’)); #Check particular table size with relative table.

 SELECT relname, relpages FROM pg_class ORDER BY relpages DESC limit 1; #Find largest table



Postgres Python Integration

 How to fetch data from POSTGRESQL from Python script.
 
 Here you will learn how to connect your python script to postgresql database. You can see below example only trying to fetch data from database.
 
 
 
 
import psycopg2 # database connection


#Data base connection
try:
    conn = psycopg2.connect("dbname='YourDatabase' user='DBUserName' host='IP/locatalhost' password='DBPassword'")
except:
    print "I am unable to connect to the database"

cur = conn.cursor()
query = "SELECT name from users limit 5";
cur.execute(query)
rows = cur.fetchall()
for row in rows:
    print "   ", row[0]
conn.close()

Monday, November 19, 2018

Convert your string in python default types

 Convert your string in python default types



There are many possibilities while doing some complex programming and some data getting as string or JSON format but somehow it won't be converted into actual type like dictionary, list or tuple format.

Here you can find the alternate solution to get actual type using only few steps.

1) Open your terminal.

2) Type python [Python must be installed on your system.]

3) Past This example in your terminal.

#Import literal_eval python package
from ast import literal_eval

#Here is your string formatted dictionary
older_string = "{'a':123, 'b':}"

print older_string

#output as below
"{'a':123, 'b':}"

#Now using literal_eval lib to convert string to dictionary.
new_string = literal_eval(older_string)

print new_string

#output as below
{'a':123, 'b':}


NOTE :-
In case key value is missing than it won't be convert. it will throw exception.

 

num2text-arabic

How to print num2text in arabic version


There are few below steps you need to follow.

1) Open your terminal.

2) If you already install git library than it would be good if not than first install git library.

3) Clone this link using your terminal (Just copy past below link).
git clone https://github.com/ahmedzaqout/num2words.git
4) Install another python library bidi
 sudo apt-get install bidi
5) Once successfully installed python-bidi you need to again install rashaper lib.
sudo apt-get install git+https://github.com/mpcabd/python-arabic-reshaper

Now you have well enough library to print number to text as Arabic.

Here below few lines you need to copy past in your python file save it and run it.

1) Create new python file as test.py

2) Past below command in your test.py file and save it

from bidi.algorithm import get_display
import arabic_reshaper
from num2words import num2words
print get_display(arabic_reshaper.reshape(num2words(550,lang='ar')))
print get_display(arabic_reshaper.reshape(num2words(100125,lang='ar')))

3) Run this test.py file and you will get below output.

خمسمائة وخمسون
مائة ألف ومائة وخمسة وعشرون


Referenced From


How to use xmlrpc using Python for new verion


Integration with Odoo using XMLRPC New Version.




#Step1 Add library
import xmlrpclib

#Step2 Add Variables
url="http://YourIP/DomainName:PortNumber"
db = "v2"
username = "admin"
password = "admin"

#Call to server
common = xmlrpclib.ServerProxy("{}/xmlrpc/common".format(url), allow_none=True)
uid = common.login(db, username, password)
common = xmlrpclib.ServerProxy("{}/xmlrpc/2/object".format(url), allow_none=True)

#Call specific API
print common.execute_kw(db, uid, password, "Model.Name", "Model.Method.Name", "YourPayload", "ContextIncaseNeedToPass")


Add xmlrpc library in case didn't install in your server click here to download and install.

How to use xmlrpc using Python older version


Integration with Odoo using XMLRPC Older Version.




#Step1 Add library
import xmlrpclib

#Step2 Add Variables
url="http://YourIP/DomainName:PortNumber"
db = "v2"
username = "admin"
password = "admin"

#Call to server
common = xmlrpclib.ServerProxy("{}/xmlrpc/common".format(url), allow_none=True)
uid = common.login(db, username, password)
common = xmlrpclib.ServerProxy("{}/xmlrpc/object".format(url), allow_none=True)

#Call specific API
print common.execute(db, uid, password, "Model.Name", "Model.Method.Name", "YourPayload", "ContextIncaseNeedToPass")


Add xmlrpc library in case didn't install in your server click here to download and install.

Wednesday, October 07, 2015

Iteration Statements

Iteration Statements


Java’s iteration statements are for, while and do-while. These statements create what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination condition is met. As you will see Java has a loop to fit any programming need.

While Loop

The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

while(condition)
{
// body of loop
}

The condition can be any Boolean expression.

The body of the loop will be executed as long as the conditional expression is true.

When condition becomes false, control passes to the next line of code immediately following the loop.

The curly braces are unnecessary if only a single statement is being repeated.



// Demonstrate the while loop.
class WLWhile
{
     public static void main(String args[])
     {
          int n = 5;
          while(n > 0)
          {
               System.out.println("tick " + n);
               n--;
          }
    }
}

Type following command in command prompt

javac WLWhile.java
java WLWhile

tick 5
tick 4
tick 3
tick 2
tick 1

do while loop

do-while

The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do
{
     // body of loop
} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression.

If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.

Here is a reworked version of the “tick” program that demonstrates the do-while loop.

// Demonstrate the do-while loop.
class WLDoWhile
{
public static void main(String args[])
{
int n = 5;
do
{
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}

type following command in command prompt

javac WLDoWhile.java
java WLDoWhile

tick 5
tick 4
tick 3
tick 2
tick 1

As you just saw if the conditional expression controlling a while loop is initially false then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning.


Sunday, October 04, 2015

For Loop

For Loop

For loop is a powerful and versatile construct. Beginning with JDK 5, there are two forms of the for loop.


  • The first is the traditional form that has been in use since the original version of Java.
  • The second is the new “for-each” form.


for(initialization; condition; iteration)
{
      // body
}

If only one statement is being repeated, there is no need for the curly braces.

When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop.It is important to understand that the initialization expression is only executed once.

Condition is evaluated, This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

Here is a version of the “tick” program that uses a for loop:

// Demonstrate the for loop.
class WLFor
{
public static void main(String args[])
{
int n=5;
for(n; n>0; n--)
{
System.out.println("tick " + n);
}
}
}

Using the Comma

Java allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

Using the comma, the preceding for loop can be more efficiently coded as shown here:

// For Loop Using the comma.
class WLForComma
{
public static void main(String args[])
{
int a, b;
for(a=1, b=4; a<b; a++, b--)
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

In this example, the initialization portion sets the values of both a and b. The two comma-separated statements in the iteration portion are executed each time the loop repeats.

The program generates the following output:

javac WLForComma.java
java WLForComma

a = 1
b = 4
a = 2
b = 3

Monday, September 28, 2015

The For-Each Loop Version of the For Loop

Beginning with JDK 5 A second form of for was defined that implements a “for-each” style loop. A foreach style loop is designed to cycle through a collection of objects such as an array in strictly sequential fashion from start to finish.
The advantage of this approach is that no new keyword is required and no preexisting code is broken. The for-each style of for is also referred to as the enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from acollection. one at a time, from beginning to end.
The collection being cycled through is specified by collection. There are various types of collections that can be used with the for.
With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection.
Type must be the same as (or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the base type of the array.
To understand the motivation behind a for-each style loop, consider the type of for loop that it is designed to replace. The following fragment uses a traditional for loop to compute the sum of the values in an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Using Simple For Loop.
class WLFor
{
public static void main(String args[])
{
int nums[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int sum = 0;
for(int i=0; i < 10; i++)
{
sum += nums[i];
}
System.out.println(sum);
}
}
To compute the sum, each element in nums is read, in order, from start to finish. Thus, the entire array is read in strictly sequential order. This is accomplished by manually indexing the nums array by i, the loop control variable.
The for-each style for automates the preceding loop. Specifically, it eliminates the need to establish a loop counter, specify a starting and ending value and manually index the array. Instead it automatically cycles through the entire array obtaining one element at a time in sequence from beginning to end.
For example, here is the preceding fragment rewritten using a for-each version of the for:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Using For-Each Loop.
class WLForEach
{
public static void main(String args[])
{
int nums[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int sum = 0;
for(int x: nums)
{
sum += x;
}
System.out.println(sum);
}
}