Archive for the ‘Code Snippets’ Category.

Binary Search – Java Source Code Snippet


  public static int binarySearch(int a[],int s)
  {
     int N = a.length;
     int start=0;
     int end = N-1;
     while(start <= end)
     {
        int mid = start+(end-start)/2;
        if(a[mid] > s)
        {
          end=mid-1;
        }else if(a[mid] < s)
        {
          start=mid+1;
        }else
        {
          return mid;
        }
     }
     return -(start+1);
  }

Oracle SQL Snippet : Find Definition of a View

To find the definition of view SYS.ALL_TABLES use the following SQL code

select TEXT
    from DBA_VIEWS
    where OWNER = 'SYS'
    and VIEW_NAME  = 'ALL_TABLES'

PHP Snippet: Iterating through an array


$colorList = array(0 =>"red",1=>"green",2=>"blue",3=>"black",4=>"white");

foreach( $colorList as $key => $value){
	      echo "Key: $key, Val: $value ";
}

OUTPUT:

Key: 0, Val: red
Key: 1, Val: green
Key: 2, Val: blue
Key: 3, Val: black
Key: 4, Val: white

PHP Snippet: PHP MySQL Database Sample Code

<?php
//Connect to Databse
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($G['dbname']);
?>
<?php
// Simple query returning a single row 'COL_VAL'
$query = " SELECT 'COL_VAL' as COL_VAL ";
//Fetch Result
$result = mysql_query($query) or die('Error2, query failed:'.$query);
//Iterate through Result
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$C_COL_VAL = $row['COL_VAL'];
echo "$C_COL_VAL";
}
?>
<?php
//Closing DB Connection
mysql_close($conn);
?>

PHP Snippet: Print an array

$mappings = array ('windows' => 'microsoft', 'ipod' => 'apple', 'corby' => 'samsum');
print_r($mappings);

output:

Array ( [windows] => microsoft [ipod] => apple [corby] => samsum )

Sample Code: Simple Form Processing in PHP

<?php

 if(isset($_POST['submit'])){
    echo $_POST['name'];
 }else{

?>
<html>
<body>
  <form method="post" action="">
    <input name="name" id="name" type="text" />
	<input name="submit" id="submit" value="Add Me" type="submit" />
  </form>
</body>
</html>
<?php
}
?>