Home / Articles by: madhu

Author Archive

perl abs Function

PERL abs Function
PERL abs Function Syntax

abs VALUE
abs


PERL abs Function Definition and Usage
Returns the absolute value of its argument. If pure interger value is passed then it will return it as it is but if a string is passed then it will return zero. If VALUE is omitted then it uses $_

PERL abs Function Return Value

Returns the absolute value of its argument.


PERL abs Function Example

Following is the piece of code
 
#!/usr/bin/perl
 
$par1 = 10.25;
$par2 = 20;
$par3 = "ABC";
 
$abs1 = abs($par1);
$abs2 = abs($par2);
$abs3 = abs($par3);
 
print "Abs value of par1 is $abs1\n" ;
print "Abs value of par2 is $abs2\n" ;
print "Abs value of par3 is $abs3\n" ;
 
This will produce following result
 
Abs value of par1 is 10.25
Abs value of par2 is 20
Abs value of par3 is 0

printf function in PERL

PERL printf Function
PERL printf Function Syntax

printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST



PERL printf Function Definition and Usage
Prints the value of LIST interpreted via the format specified by FORMAT to the current output filehandle, or to the one specified by FILEHANDLE.
Effectively equivalent to print FILEHANDLE sprintf(FORMAT, LIST)
You can use print in place of printf if you do not require a specific output format.
Following is the list of accepted formatting conversions.
Format
Result

%%
A percent sign

%c
A character with the given ASCII code

%s
A string

%d
A signed integer (decimal)

%u
An unsigned integer (decimal)

%o
An unsigned integer (octal)

%x
An unsigned integer (hexadecimal)

%X
An unsigned integer (hexadecimal using uppercase characters)

%e
A floating point number (scientific notation)

%E
A floating point number, uses E instead of e

%f
A floating point number (fixed decimal notation)

%g
A floating point number (%e or %f notation according to value size)

%G
A floating point number (as %g, but using .E. in place of .e. when
appropriate)

%p
A pointer (prints the memory address of the value in hexadecimal)

%n
Stores the number of characters output so far into the next variable in
the parameter list

Perl also supports flags that optionally adjust the output format. These are specified between the % and conversion letter. They are shown in the following table:
Flag
Result

space
Prefix positive number with a space

+
Prefix positive number with a plus sign

-
Left-justify within field

0
Use zeros, not spaces, to right-justify

#
Prefix non-zero octal with .0. and hexadecimal with .0x.

number
Minimum field width

.number
Specify precision (number of digits after decimal point) for floating point numbers

l
Interpret integer as C-type .long. or .unsigned long.

h
Interpret integer as C-type .short. or .unsigned short.

V
Interpret integer as Perl.s standard integer type

v
Interpret the string as a series of integers and output as numbers
separated by periods or by an arbitrary string extracted from the
argument when the flag is preceded by *.



PERL printf Function Return Value

0 on failure
1 on success



PERL printf Function Example

Try out following  example:
 
#!/usr/bin/perl -w
printf "%d\n", 3.1415126;
printf "The cost is \$%6.2f\n",499;
printf "Perl's version is v%vd\n",%^V;
printf "%04d\n", 20;
 
It will produce following results: Try more options yourself.
 
3
The cost is $499.00
Perl's version is v
0020

A regular expression that recognizes numbers in Javascript

Numbers consist of an integral part and optional minus sign, followed by an optional decimal part and an optional exponent.

var parse_number = /^-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?$/i;
var test = function (num) {
document.writeln(parse_number.test(num));
};
test('1'); // true
test('number'); // false
test('98.6'); // true
test('132.21.86.100'); // false
test('123.45E-67'); // true
test('123.45D-67'); // false

A regular expression to detect URLs in Javascript

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)
(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
 
var url = "http://www.w3mentor.com:80/someparts?q#fragment";
var result = parse_url.exec(url);
var names = ['url', 'scheme', 'slash', 'host', 'port',
'path', 'query', 'hash'];
var blanks = ' ';
var i;
for (i = 0; i < names.length; i += 1) {
document.writeln(names[i] + ':' +
blanks.substring(names[i].length), result[i]);
}

Example for building a unit matrix in Javascript

Array.identity = function (n) {
var i, mat = Array.matrix(n, n, 0);
for (i = 0; i < n; i += 1) {
mat[i][i] = 1;
}
return mat;
};
myMatrix = Array.identity(4);
document.writeln(myMatrix[3][3]); // 1

Create a 4×4 multidimensional array in Javascript

Array.matrix = function (m, n, initial) {
var a, i, j, mat = [];
for (i = 0; i < m; i += 1) {
a = [];
for (j = 0; j < n; j += 1) {
a[j] = initial;
}
mat[i] = a;
}
return mat;
};
var myMatrix = Array.matrix(4, 4, 0);
document.writeln(myMatrix[3][3]); // 0

Create an array of 10 zeroes by adding a method to Javascript array

Array.dim = function (dimension, initial) {
var a = [], i;
for (i = 0; i < dimension; i += 1) {
a[i] = initial;
}
return a;
};

// Create an array of 10 zeroes

var myArray = Array.dim(10, 0);

Add a method to an array to perform calculations

Array.method('reduce', function (f, value) {
var i;
for (i = 0; i < this.length; i += 1) {
value = f(this[i], value);
}
return value;
});

Highlight featured sticky posts in wordpress

Insert the following code inside the Loop, after a call to the_post.

<?php
if(is_sticky()) {
?>
<div class="sticky-post-class">
<p>This post is sticky.</p>
</div>
<?php
}
?>

Remove posts with a certain tag from the Loop in wordpress

Add the following to functions.php.

add_action('pre_get_posts', 'remove_tag_from_loops');
function remove_tag_from_loops( $query ) {
if(!$query->get('suppress_filters')) {
//replace tag1 by the slug for the tag to be hidden
$tag_id = get_term_by('name','tag1','post_tag')->term_id;
$excluded_tags = $query->get('tag__not_in');
if(is_array( $excluded_tags )) {
$excluded_tags[] = $tag_id;
} else {
$excluded_tags = array($tag_id);
}
$query->set('tag__not_in', $excluded_tags);
}
return $query;
}

Hide posts from a certain category in WordPress

Insert the following code into functions.php.

add_action('pre_get_posts', 'remove_cat_from_loops');
function remove_cat_from_loops( $query ) {
if(!$query->get('suppress_filters')) {
//add category name below.
$cat_id = get_cat_ID('Category Name');
$excluded_cats = $query->get('category__not_in');
if(is_array($excluded_cats)) {
$excluded_cats[] = $cat_id;
} else {
$excluded_cats = array($cat_id);
}
$query->set('category__not_in', $excluded_cats);
}
return $query;
}

Displaying ads after every x posts in wordpress

Add the following to template file like index.php or category.php.

<?php
if( have_posts() ) {
$ad_counter = 0;
$after_every = x //change this to the number of posts;
while( have_posts() ) {
$ad_counter++;
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
// Display content
$ad_counter = $ad_counter % $after_every;
if( 0 == $ad_counter ) {
echo '<h2 style="color:red;">Advertisement or custom content here</h2>';
}
}
}
?>

Iterate through the available posts in wordpress and display titles

<?php
if( have_posts() ) {
while( have_posts() ) {
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
}
}
?>

Create random number values with the System.Security.Cryptography.RandomNumberGenerator class

byte[] RandomValue = new byte[16];
RandomNumberGenerator RndGen = RandomNumberGenerator.Create();
RndGen.GetBytes(RandomValue);
ResultLabel.Text = Convert.ToBase64String(RandomValue);

Read a certificate from the store and assign it to a web request

X509Certificate2 Certificate = null;
// Read the certificate from the store
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
try
{
// Try to find the certificate
// based on its common name
X509Certificate2Collection Results =
store.Certificates.Find(
X509FindType.FindBySubjectDistinguishedName,
"CN=Someone, CN=Something", false);
if (Results.Count == 0)
throw new Exception("Unable to find certificate!");
else
Certificate = Results[0];
}
finally
{
store.Close();
}

Example of using a DELETE command with ExecuteNonQuery method

The ExecuteNonQuery() method executes commands that don’t return a result set, such as INSERT, DELETE, and UPDATE. The ExecuteNonQuery() method returns a single piece of information—the number of affected records.
 
SqlConnection con = new SqlConnection(connectionString);
string sql = "DELETE FROM Employees WHERE EmployeeID = " + empID.ToString();
SqlCommand cmd = new SqlCommand(sql, con);
try
{
con.Open();
int numAff = cmd.ExecuteNonQuery();
HtmlContent.Text += string.Format("<br />Deleted <b>{0}</b> record(s)<br />", numAff);
}
catch (SqlException exc)
{
HtmlContent.Text += string.Format(
"<b>Error:</b> {0}<br /><br />", exc.Message);
}
finally
{
con.Close();
}

Example of using ExecuteScalar() Method

The ExecuteScalar() method returns the value stored in the first field of the first row of a result set generated by the command’s SELECT query.

SqlConnection con = new SqlConnection(connectionString);
string sql = " SELECT COUNT(*) FROM Employees ";
SqlCommand cmd = new SqlCommand(sql, con);
// Open the Connection and get the COUNT(*) value.
con.Open();
int numEmployees = (int)cmd.ExecuteScalar();
con.Close();
// Display the information.
HtmlContent.Text += "<br />Total employees: <b>" +
numEmployees.ToString() + "</b><br />";

Cycle through the records and all the rowsets and build the HTML string

StringBuilder htmlStr = new StringBuilder("");
int i = 0;
do
{
htmlStr.Append("<h2>Rowset: ");
htmlStr.Append(i.ToString());
htmlStr.Append("</h2>");
while (reader.Read())
{
htmlStr.Append("<li>");
// Get all the fields in this row.
for (int field = 0; field < reader.FieldCount; field++)
{
htmlStr.Append(reader.GetName(field).ToString());
htmlStr.Append(": ");
htmlStr.Append(reader.GetValue(field).ToString());
htmlStr.Append("&nbsp;&nbsp;&nbsp;");
}
htmlStr.Append("</li>");
}
htmlStr.Append("<br /><br />");
i++;
} while (reader.NextResult());
// Close the DataReader and the Connection.
reader.Close();
con.Close();
// Show the generated HTML code on the page.
HtmlContent.Text = htmlStr.ToString();

Example connection string that sets a minimum pool size

string connectionString = "Data Source=localhost; Initial Catalog=Northwind;" +
"Integrated Security=SSPI; Min Pool Size=10";
SqlConnection con = new SqlConnection(connectionString);
// Get the connection from the pool (if it exists)
// or create the pool with 10 connections (if it doesn't).
con.Open();
// Return the connection to the pool.
con.Close();

Page.Load event handler to test a connection

// Create the Connection object.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
try
{
// Try to open the connection.
con.Open();
lblInfo.Text = "<b>Server Version:</b> " + con.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + con.State.ToString();
}
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. " + err.Message;
}
finally
{
// Either way, make sure the connection is properly closed.
// Even if the connection wasn't opened successfully,
// calling Close() won't cause an error.
con.Close();
lblInfo.Text += "<br /><b>Now Connection Is:</b> " +
con.State.ToString();
}