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

Snippets

  • submit to reddit

Recent Snippets

                        /* Source : http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url  */
     
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match&&match[2].length==11){
        return match[2];
    }else{
        //error
    }
                
                    //Sample Code for Splitting all pages to new PDFs

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}
// class definitions
public class SplitPDFResponse : Saaspose.Common.BaseResponse
{
    public SplitPdfResult Result { get; set; }
}
public class SplitPdfResult
{
    public LinkResponse[] Documents { get; set; }
}

//Split specific pages to new PDFs

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split?from=2&to=3";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}

//Split PDF pages to any supported format

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split?from=2&to=3&format=tiff";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }}
                
                    / :- The root of overall file system. The starting directory of unix directory structure. 

/bin :- It contains all the standard system commands like ls, cp, rm etc. 

/dev :-This directory contains logical device names. 

/etc :- This directory contains configuration files. 

/home :- Home directory for users.

/export :- The default directory for shared file system's. eg;- User's home directories and other shared file systems.

/kernel :- This contains kernel files that are required as part of the booting process.

 /lib :- The contents of this directory are shared executable files that are used by many applications at the same time. Library files are part of executables (these are also executables) so that you don't have to write same code again and again. 

/mnt :- A temporary mount point for external file systems.

 /opt :- Directory used for installation of external software's and applications. 

/sbin :- This directory contains files that are used by system during booting process. it contains system specific commands. The executables in this directory are very important and are user during system failure. 

/usr :- Programs and files or executables available for normal system users. Basically /usr/bin and /bin are symbolic links to each other.

/var :- Directory for saving system and admin logs. we call it var directory because it contains files that vary from time and time and by that we mean log files. All system administration logs are under var directory.

/devices :- the primary directory for physical device names.

/proc :- stores current process related information. all the processes currently running have directories and subdirectories in this directory. these directories are named with the PID of the process. 

/tmp :- This directory is used to store temporary files. This directory gets cleared if system is down.                 
                    if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
// This will print user's real IP Address
// does't matter if user using proxy or not.
echo $ip;                
                    (8086 assembly)

//ah = month. 0 = Jan, 7 = Aug..etc. Feb not handled
//ah destroyed.
//al contains number of days in month
mov al,31
xor ah,9
jp thirty_one //parity bit set on 30 day months
dec al
:thirty_one
ret                
                    SaasposeApp.AppKey = "9a******************";
            SaasposeApp.AppSID = "77*********************";
            //specify product URI
            Product.BaseProductUri = @"http://api.saaspose.com/v1.0";
            try
            {
                int drawingObjectIndex = 1;
                string fileName = "SampleDrawingObject.doc";
                string saveFormat = "xls"; //Choose from jpeg, tiff, png and bmp
                string outputFile = "C:\\OutputDrawingObject." + saveFormat;
                string amazonS3StorageName = "MyAmazonS3Storage";
                string amazonS3BucketName = "MyS3Bucket"; // include folder name if file is not at root folder 

                //build URI
                string strURI = Product.BaseProductUri + "/words/" + fileName + "/drawingObjects/" + drawingObjectIndex;
                strURI += "/oleData?storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName;

                //sign URI
                string signedURI = Sign(strURI);

                //get response stream
                Stream responseStream = ProcessCommand(signedURI, "GET");

                using (Stream fileStream = System.IO.File.OpenWrite(outputFile))
                {
                    CopyStream(responseStream, fileStream);
                }
                responseStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            } 

//Following are the required methods and classes 

        public static string Sign(string url)
        {
            try
            {
                // Add appSID parameter.
                UriBuilder builder = new UriBuilder(url);
                if (builder.Query != null && builder.Query.Length > 1)
                    builder.Query = builder.Query.Substring(1) + "&appSID=" + SaasposeApp.AppSID;
                else
                    builder.Query = "appSID=" + SaasposeApp.AppSID;
                // Remove final slash here as it can be added automatically.
                builder.Path = builder.Path.TrimEnd('/');
                // Compute the hash.

                byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(SaasposeApp.AppKey);

                System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
                //System.Text.ASCIIEncoding
                byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
                byte[] hash = algorithm.ComputeHash(sequence);
                string signature = Convert.ToBase64String(hash);
                // Remove invalid symbols.
                signature = signature.TrimEnd('=');
                signature = System.Web.HttpUtility.UrlEncode(signature);
                // Convert codes to upper case as they can be updated automatically.
                signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
                
                // Add the signature to query string.
                return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static Stream ProcessCommand(string strURI, string strHttpCommand)
        {
            try
            {
                Uri address = new Uri(strURI);
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
                request.Method = strHttpCommand;
                request.ContentType = "application/json";
                request.ContentLength = 0;
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                return response.GetResponseStream();
            }
            catch (System.Net.WebException webex)
            {
                throw new Exception(webex.Message);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
        public static void CopyStream(Stream input, Stream output)
        {
            try
            {
                byte[] buffer = new byte[8 * 1024];
                int len;
                while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, len);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    public class Product
    {
       public static string BaseProductUri { get; set; }
    }
    public class SaasposeApp
    {
       public static string AppSID { get; set; }
       public static string AppKey { get; set; }
    }
                
                     expdp system / [password_of_System] @ [SID] schemas=[name of the schema] dumpfile=[filename].dmp logfile=[filename].log
     
 #Example
     
expdp system/oracle@mydbsid SCHEMAS=staging dumpfile=export_staging_original.dmp logfile=original.log                
                    <?php
  $im=imagecreatefromjpeg('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com');
    header('Content-type:image/jpeg');
    imagejpeg($im);
 ?>                
                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Demo Page For Autoplay youtube video while clicking on a custom thumbnail image</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'><script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<style>
	body
	{
		margin	: 0;
		padding	: 0;
		background	: #EEE;
		color		: #333;
		font-family: 'Open Sans', sans-serif;
		font-size	: 12px;
 
	}
	#wrapper
	{
		width	: 1012px;
		margin	: 0 auto;
 
	}
 
</style>
<body>
	<div id="wrapper">
		<h1>Demo Page For Autoplay youtube video while clicking on a custom thumbnail image</h1>
		<div class="custom-th"><img src="http://blog.pixelthemes.com/demo/custom-yt-thumbnail/cusotm-yt-thumbanil.jpg" style="cursor:pointer" /></div>
		<div id="thevideo" style="display:none">
		<object width="560" height="315"><param name="movie" value="http://www.youtube.com/v/XSGBVzeBUbk?&autoplay=1&hl=en_US&version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/XSGBVzeBUbk?hl=en_US&version=3&autoplay=1" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>
		</div>
 
		<p>Demo by : <a href="http://blog.pixelthemes.com/">WordPress Themes</a> </br>
		Article Link : <a href="http://blog.pixelthemes.com/ideas/autoplay-youtube-video-while-clicking-on-a-custom-thumbnail-image">Custom Thumbnail with fadeout animation for Youtube Videos</a>
	</div>
 
	<script type="text/javascript">
	$(document).ready(function() {
		$('.custom-th').click(function() {
			$('.custom-th').fadeOut('slow', function() {
				$("#thevideo").css("display","block");
				});
			});
		});
	</script>
</body>
</html>                
                    SaasposeApp.AppKey = "9a******************";
SaasposeApp.AppSID = "77*********************";
            //specify product URI
            Product.BaseProductUri = @"http://api.saaspose.com/v1.0";
            
            try
            {
                string fileName = "Sample.doc";
                string saveFormat = "doc";
                string outputFile = "C:\\Output." + saveFormat;
                string amazonS3StorageName = "MyAmazonS3Storage";
                string amazonS3BucketName = "MyS3Bucket"; // include folder name if file is not at root folder 

                //serialize the JSON request content
                Field field = new Field();
                field.Alignment = "right";
                field.Format = "{PAGE} of {NUMPAGES}";
                field.IsTop = true;
                field.SetPageNumberOnFirstPage = true;

                string strJSON = JsonConvert.SerializeObject(field);

                //build URI
                string strURI = Product.BaseProductUri + "/words/" + fileName + "/insertPageNumbers";
                strURI += "?storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName;
                //sign URI
                string signedURI = Sign(strURI);
                //get response stream
                Stream responseStream = ProcessCommand(signedURI, "POST", strJSON, "json");
                //build URI
                strURI = Product.BaseProductUri + "/words/" + fileName;
                strURI += "?format=" + saveFormat + "&storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName; ;

                //sign URI
                signedURI = Sign(strURI);
                //get response stream
                responseStream = ProcessCommand(signedURI, "GET");

                using (Stream fileStream = System.IO.File.OpenWrite(outputFile))
                {
                    CopyStream(responseStream, fileStream);
                }
                responseStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }  
   public static string Sign(string url)
    {
        try
        {
            UriBuilder builder = new UriBuilder(url);
            if (builder.Query != null && builder.Query.Length > 1)
                builder.Query = builder.Query.Substring(1) + "&appSID=" + SaasposeApp.AppSID;
            else
                builder.Query = "appSID=" + SaasposeApp.AppSID;
                builder.Path = builder.Path.TrimEnd('/');
            byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(SaasposeApp.AppKey);

            System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
            byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
            byte[] hash = algorithm.ComputeHash(sequence);
            string signature = Convert.ToBase64String(hash);
            signature = signature.TrimEnd('=');
            signature = System.Web.HttpUtility.UrlEncode(signature);
            signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
     return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    public static Stream ProcessCommand(string strURI, string strHttpCommand)
    {
        try
        {
            Uri address = new Uri(strURI);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
            request.Method = strHttpCommand;
            request.ContentType = "application/json";

            request.ContentLength = 0;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            return response.GetResponseStream();
        }
        catch (System.Net.WebException webex)
        {
            throw new Exception(webex.Message);
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);
        }
    }

   public static Stream ProcessCommand(string strURI, string strHttpCommand, string strContent, string ContentType = "xml")
    {
        try
        {
            byte[] arr = System.Text.Encoding.UTF8.GetBytes(strContent);

            Uri address = new Uri(strURI);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
            request.Method = strHttpCommand;
            if (ContentType.ToLower() == "xml")
                request.ContentType = "application/xml";
            else
                request.ContentType = "application/json";

            request.ContentLength = arr.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(arr, 0, arr.Length);
            dataStream.Close();

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            return response.GetResponseStream();
        }
        catch (System.Net.WebException webex)
        {
            throw new Exception(webex.Message);
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);
        }
    }
    public static void CopyStream(Stream input, Stream output)
    {
        try
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

public class Product
{
   public static string BaseProductUri { get; set; }
}
public class SaasposeApp
{
    public static string AppSID { get; set; }
    public static string AppKey { get; set; }
}
public class Field
{
    public string Format { get; set; }
    public string Alignment { get; set; }
    public bool IsTop { get; set; }
    public bool SetPageNumberOnFirstPage { get; set; }
}