DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world


  • submit to reddit

Recent Snippets

                    Launch Facebook oAuth Box

    $stoken = Util::getMD5GUID();
    $fbAppId = Config::getInstance()->get_value("");
    $host = "http://".$_SERVER["HTTP_HOST"];
    $fbCallback = $host."/callback/fb2.php" ;
    $fbDialogUrl = "".$fbAppId ;
    $fbDialogUrl .= "&redirect_uri=".urlencode($fbCallback)."&scope=email&state=".$stoken ;

  <a href="<?php echo $fbDialogUrl; ?>"> Login with Facebook</a>

Example of error handler

function login_error_handler($errorno,$errorstr,$file,$line) {

    if(error_reporting() == 0 ) {
        // do nothing for silenced errors
        return true ;
    switch($errorno) {

        case E_STRICT :
            return true;
        case E_NOTICE :
        case E_USER_NOTICE :
            Logger->error(" $file :: $line :: $errorstr");
            break ;

        case E_USER_ERROR:
            $_SESSION["form.errors"] = array($errorstr);
            header('Location: /user/login.php');

            $_SESSION["form.errors"] = array("Error happened during login");
            header('Location: /user/login.php');
    //do not execute PHP error handler
    return true ;

Code for error check and user data

 include ($_SERVER['APP_WEB_DIR'].'/callback/');
    $fbAppId = Config::getInstance()->get_value("");
    $fbAppSecret = Config::getInstance()->get_value("");

    $host = "http://".$_SERVER["HTTP_HOST"];
    $fbCallback = $host. "/callback/fb2.php";
    $code = NULL;
    if(array_key_exists('code',$_REQUEST)) {
        $code = $_REQUEST["code"];
    $error = NULL ;
    if(array_key_exists('error',$_REQUEST)) {
       $error = $_REQUEST['error'] ;
       $description = $_REQUEST['error_description'] ;
       $message = sprintf(" Facebook returned error :: %s :: %s ",$error,$description);

       exit ;

     if(empty($code) && empty($error)) {
        //see how to launch an FB dialog again on Facebook URL given above

    //last state token
    $stoken = $gWeb->find('fb_state',true);
    if(!empty($code) && ($_REQUEST['state'] == $stoken)) {
    //request to get access token
    $fbTokenUrl = "".$fbAppId ;
    $fbTokenUrl .= "&redirect_uri=" . urlencode($fbCallback). "&client_secret=" . $fbAppSecret ;
    $fbTokenUrl .= "&code=" . $code;
    $response = file_get_contents($fbTokenUrl);
    $params = null;
    parse_str($response, $params);

    $graph_url = "".$params['access_token'];
    $user = json_decode(file_get_contents($graph_url));

   else {
    $message = " and Facebook state mismatch";

Code to process User Info

function processUser($user) {
    $id = $user->id;
    $name = $user->name;
    $firstName = $user->first_name ;
    $lastName = $user->last_name ;
    $link = $user->link ;
    $gender = $user->gender ;
    $email = $user->email ;

    if(empty($name) && empty($firstName)) {
        $name = "Anonymous" ;

    $message = sprintf("Login:Facebook :: id %d ,email %s \n",$id,$email); 

    $facebookDao = new \com\indigloo\sc\dao\Facebook();
    $loginId = $facebookDao->getOrCreate($id,$name,$firstName,$lastName,$link,$gender,$email);

    if(empty($loginId)) {
        trigger_error("Unable to create login",E_USER_ERROR);

    header("Location: / ");

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;

using Aspose.Words;

namespace MultipleDocsInMailMerge
    class Program
        public static void Main(string[] args)
            //Sample infrastructure.
            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
            string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

            ProduceMultipleDocuments(dataDir, "TestFile.doc");

        public static void ProduceMultipleDocuments(string dataDir, string srcDoc)
            // Open the database connection.
            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
                // Get data from a database.
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable data = new DataTable();

                // Open the template document.
                Document doc = new Document(dataDir + srcDoc);

                int counter = 1;
                // Loop though all records in the data source.
                foreach (DataRow row in data.Rows)
                    // Clone the template instead of loading it from disk (for speed).
                    Document dstDoc = (Document)doc.Clone(true);

                    // Execute mail merge.

                    // Save the document.
                    dstDoc.Save(string.Format(dataDir + "TestFile Out {0}.doc", counter++));
                // Close the database.

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Reflection

Imports Aspose.Words

Namespace MultipleDocsInMailMerge
    Friend Class Program
        Public Shared Sub Main(ByVal args() As String)
            'Sample infrastructure.
            Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
            Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

            ProduceMultipleDocuments(dataDir, "TestFile.doc")
        End Sub

        Public Shared Sub ProduceMultipleDocuments(ByVal dataDir As String, ByVal srcDoc As String)
            ' Open the database connection.
            Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataDir & "Customers.mdb"
            Dim conn As New OleDbConnection(connString)
                ' Get data from a database.
                Dim cmd As New OleDbCommand("SELECT * FROM Customers", conn)
                Dim da As New OleDbDataAdapter(cmd)
                Dim data As New DataTable()

                ' Open the template document.
                Dim doc As New Document(dataDir & srcDoc)

                Dim counter As Integer = 1
                ' Loop though all records in the data source.
                For Each row As DataRow In data.Rows
                    ' Clone the template instead of loading it from disk (for speed).
                    Dim dstDoc As Document = CType(doc.Clone(True), Document)

                    ' Execute mail merge.

                    ' Save the document.
                    dstDoc.Save(String.Format(dataDir & "TestFile Out {0}.doc", counter))
                    counter += 1
                Next row
                ' Close the database.
            End Try
        End Sub
    End Class
End Namespace
                    <!DOCTYPE html>
<html lang="en">
		body {
			width: 830px; 
			#gallery-wrap {
				/* border: 1px solid #000; */
				width: 777px; 
				height: 450px; 
				border: 3px solid #000; 
				margin: 0 auto; 
			#gallery-container {
				width: 600px; 
				height: 450px; 
				border-right: 3px solid #000;
				float: left; 
			.description {
				position: absolute; 
				width: 600px; 
				height: 70px; 
				top: 465px; 
				opacity: 0.5; 
				background-color: #000; 
				color: #fff;
				font-family: Arial, Helvetica, sans-serif; 
				font-size: 13px; 
				text-align: center; 
			#thumbnail-container {
				width: 165px; 
				height: 447px;
				padding-top: 3px; 
				overflow: scroll; 
				float: right; 
			#thumbnail-container img {
				cursor: pointer; 
			#disclaimer {
				padding-left: 25px; 
				font-family: sans-serif; 
				font-size: 14px;
			footer {
				font-family: serif; 
				font-size: 13px;
				margin-left: 28px;  
		<script type="text/javascript" src=""></script>		
				$("#thumbnail-container img").click(function(){
					$("#largeImage").attr("src", $(this).attr('src').replace('thumb', 'large')); 
					$(".description p").html($(this).attr('alt')); 
		<h1 style="text-align: center">A Visit To The National Zoo, D.C.</h1>
	<div id="gallery-wrap">
		<div id="gallery-container">
			<img id="largeImage" src="images/image_01_large.jpg" alt="Thumbnail"/>
			<div class="description"><p>A day at the Smithsonian's National Zoo, Washington, D.C.</p></div>
			<!--<div id=""><img src="images/zooimage2.jpg"/></div>
			<div id=""><img src="images/zooimage3.jpg"/></div>
			<div id=""><img src="images/zooimage4.jpg"/></div>
			<div id=""><img src="images/zooimage5.jpg"/></div>
			<div id=""><img src="images/zooimage6.jpg"/></div>
			<div id=""><img src="images/zooimage7.jpg"/></div>
			<div id=""><img src="images/zooimage8.jpg"/></div>-->
		</div><!-- Gallery Container -->
		<div id="thumbnail-container">
			<img src="images/image_01_thumb.jpg" alt="A day at the Smithsonian's National Zoo, Washington, D.C." />
			<img src="images/image_02_thumb.jpg" alt="The lions yawns either in boredom or hunger."/>
			<img src="images/image_03_thumb.jpg" alt="In a video captured by our journalist, the female lion here goes ahead to massage the male lion's back, a gesture that appears well received at first 
			but eventually leads up to a brief, but fiesty ruffle."/>
			<img src="images/image_04_thumb.jpg" alt="This tiger prawls in search for his prey, a bouncing ball containing meat and simulating an animal on the run."/>
			<img src="images/image_05_thumb.jpg" alt="This elephant, out from a bath in the pond, is picking up the sand with his trunk and throwing it onto his back."/>
			<img src="images/image_06_thumb.jpg" alt="A panda lays leisurely in his man-made territory."/>
			<img src="images/image_07_thumb.jpg" alt="This special breed of a lizard gazes curiously as a camera clicks in his direction."/>
			<img src="images/image_08_thumb.jpg" alt="A gorrilla, done with his meal of bananas, watches the curious passerbys atop his little jungle."/>
		</div><!-- Thumbnail container -->
	</div><!-- Gallery Wrap-->
	<div id="disclaimer">
		<p>Note: The pictures are only for demonstration. The captions may or may not actually go along with the event's occurences.
					© Copyright  by Faithful Okoye
                    def format_with_separator(number)
  whole_part, decimal_part = number.to_s.split('.')
  [whole_part.gsub(/(\d)(?=\d{3}+$)/, '\1,'), decimal_part].compact.join('.')
                    // [C#]

//Create a copy of original image to avoid any alteration
File.Copy(MyDir + "sample.tif", MyDir + "Testconct.tif", true);

//Create an instance of TiffImage and load the copied destination image
using (TiffImage image = (TiffImage)Aspose.Imaging.Image.Load(MyDir + "Testconct.tif"))
 //Create an instance of TiffImage and load the source image
                using (TiffImage image1 = (TiffImage)Aspose.Imaging.Image.Load(MyDir + "sample1.tif"))
 // Create an instance of TIffFrame and copy active frame of source image
                    TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
                    // Add copied frame to destination image
                    // save the image with changes.



'Create a copy of original image to avoid any alteration
File.Copy(MyDir&"sample.tif", MyDir&"Testconct.tif", True)

'Create an instance of TiffImage and load the copied destination image
Using image As TiffImage = CType(Aspose.Imaging.Image.Load(MyDir&"Testconct.tif"), TiffImage)

'Create an instance of TiffImage and load the source image
Using image1 As TiffImage = CType(Aspose.Imaging.Image.Load(MyDir&"sample1.tif"), TiffImage)

' Create an instance of TIffFrame and copy active frame of source image
Dim frame As TiffFrame = TiffFrame.CopyFrame(image1.ActiveFrame)

' Add copied frame to destination image
save the image with changes.

                    package com.javatechig.example.ui;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.widget.TextView;
*  @author: nilanchala
public class MainActivity extends Activity {
private final String htmlText = "<body><h1>Heading Text</h1><p>This tutorial " +
            "explains how to display " +
            "<strong>HTML </strong>text in android text view. </p>" +
            "<img src="hughjackman.jpg">" +
            "<blockquote>Example from <a href="">" +
protected void onCreate(Bundle savedInstanceState) {
          TextView htmlTextView = (TextView)findViewById(;
          htmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));
public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(, menu);
         return true;
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
        int id;
        if (source.equals("hughjackman.jpg")) {
               id = R.drawable.hughjackman;
        else {
            return null;
       Drawable d = getResources().getDrawable(id);
       return d;
                    // Use median smoothing, HLS and gray-scale image processing techniques while recognizing the barcode.


string image = @"code39Extended.jpg";

// create an instance of BarCodeReader and set image and symbology type to recognize
BarCodeReader reader = new BarCodeReader(image, BarCodeReadType.Code39Standard);
// set grayscale image processing
reader.ImageBinarizationHints = RecognitionHints.ImageBinarization.Grayscale;
// try to recognize all possible barcodes in the image
while (reader.Read())
    // display the codetext
    Console.WriteLine("Codetext: " + reader.GetCodeText());
// close the reader


Dim image As String = "code39Extended.jpg"

' create an instance of BarCodeReader and set image and symbology type to recognize
Dim reader As BarCodeReader = New BarCodeReader(image, BarCodeReadType.Code39Standard)
' set grayscale image processing
reader.ImageBinarizationHints = RecognitionHints.ImageBinarization.Grayscale
' try to recognize all possible barcodes in the image
Do While reader.Read()
	' display the codetext
	Console.WriteLine("Codetext: " & reader.GetCodeText())
' close the reader
                    <!-- Grab Google CDN's jQuery and load local version if necessary -->
<script src=""></script>
<script type="text/javascript">!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>                
                    <style type="text/css">
/* Center your website horizontally */
/* Center certain content vertically */
   min-height: 10em;
   display: table-cell;
   vertical-align: middle;
<div class="wrapper">
    <div class="container">
        <p>Content goes here</p>
                    This example shows you how to define custom error pages in .htaccess file and also how to display the error page on your site.