Javascript: How to break out of the forEach

While working with Java Script, all of us must have surely run into the case where we need to loop through an array and break the running loop if a certain condition is met. There are many methods how we can loop through an array but we are always looking for the most efficient way to do that.

Our favorite loop method: Array.prototype.forEach

forEach is such an useful method.
But…how can I break the forEach loop?
Well… you can’t break forEach.

var arr = ["Kathmandu", "Pokhara", "Lumbini", "Gorkha"];

arr.forEach(function(value, index, _arr) {
    console.log(index + ": " + value);
    return false;
});

The result should look like

0: Kathmandu
1: Pokhara
2: Lumbini
3: Gorkha

It’s still iterating through all items in the array. What should I do if I want to stop the loop based on the condition? We either set a variable that changes only if the condition is met, but it will still mean that the loop will iterate until the array is exhausted to the last item.

So, what do we do?? It’s simple.

Don’t use “forEach”. Use “some” or “every”.


Array.prototype.some

Array.prototype.some is pretty much the same as forEach but it break when the callback returns true.

Example:

var arr= ["Kathmandu", "Pokhara", "Lumbini", "Gorkha"];

arr.some(function (value, index, _arr) {
    console.log(index + ": " + value);
    return value === "Pokhara";
});

The result should look like

0: Kathmandu
1: Pokhara

What happened here? Since the third iteration returned true, we successfully stopped the loop!


Array.prototype.every

Array.prototype.every is almost identical to some except it’s expecting false to break the loop.

Example:

var arr = ["Kathmandu", "Pokhara", "Lumbini", "Gorkha"];

arr.every(function(value, index, _arr) {
    console.log(index + ": " + value);
    return value.indexOf("Lumbini") < 0;
});

The result should look like

0: Kathmandu
1: Pokhara
2: Lumbini

What happened here? Since the third iteration returned false, we successfully stopped the loop!

Now you can break loops whenever you want! Enjoy.

Code Igniter : Log all queries

Developing applications in Code Igniter is fun and easy, as we do not have to write much of the actual queries because of its Active Record Implementation. Moreover, we can find plugins for CI which will write all the model classes for you in a click.

As we keep on developing application, we might sometimes need to keep track of the queries that have been run during each page load. It might seem minimal but while developing large enterprise applications, even the smallest optimizations will speed up things a lot.

Below you’ll find a CodeIgniter hook that logs all database queries to a simple text file.

/* config/hooks.php */
$hook['post_system'][] = array(
    'class' => 'LogQueryHook',
    'function' => 'log_queries',
    'filename' => 'LogQueryHook.php',
    'filepath' => 'hooks'
);
/* application/hooks/LogQueryHook.php */
class LogQueryHook {

    function log_queries() {    
        $CI =& get_instance();
        $times = $CI->db->query_times;
        $dbs    = array();
        $output = NULL;     
        $queries = $CI->db->queries;

        if (count($queries) == 0){
            $output .= "no queries\n";
        }else{
            foreach ($queries as $key=>$query){
                $output .= $query . "\n";
            }
            $took = round(doubleval($times[$key]), 3);
            $output .= "===[took:{$took}]\n\n";
        }

        $CI->load->helper('file');
        if ( ! write_file(APPPATH  . "/logs/queries.log.txt", $output, 'a+')){
             log_message('debug','Unable to write query the file');
        }   
    }
}

Setup Code Igniter on a subdomain

Setting up CodeIgniter application on a sub domain can be a huge challenge. It seems to work fine on the view pages, but when we try to submit a form, or link pages, it shows a 505 error page. Our application just becomes useless when we are not able to submit a single form.

After much searching on Google, I finally found the best ideal solution to it. I am just making a copy of the answers given in the CI forum, as I think this will help solve a lot of problems.

Source: Code Igniter Forum by wiredesignz.

Make the following changes in your /system/application/config/config.php file.

$config['uri_protocol'] = "APP_PATH";  
  
// enable query strings if you are using 
// GET requests at any point of your application.  
$config['enable_query_strings'] = TRUE; 

Create your .htaccess file with the following code

RewriteEngine On  
  
RewriteBase /  
  
RewriteCond %{ENV:REDIRECT_APP_PATH} !^$  
RewriteRule ^(.*)$ - [E=APP_PATH:%{ENV:REDIRECT_APP_PATH}]  
  
RewriteCond %{ENV:APP_PATH} ^$  
RewriteRule ^(.*)$ - [E=APP_PATH:/$1]  
  
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^(.*)$ index.php [L]  

Dynamic CRUD Stored Procedures using PHP

Tired of writing Stored Procedures for regular CRUD operations? Here is useful PHP script, which generates the script for the required stored procedures. This code studies the table structure and creates the stored procedures accordingly.

<?php

$tableName = "Your Desired Table";

// Connection String
$conn = mysql_connect('localhost', 'root','');

// Select database
mysql_select_db('<DBNAME>', $conn);

$result = mysql_query('select * from `'.$tableName.'`');

$paramList = '(<br/>';

$tableIdField = mysql_field_name($result, 0);

$insertFields = "(";
$insertValues = "(";

$updateList = "";

for($i=0;$i< mysql_num_fields($result);$i++){
     $fieldName = mysql_field_name($result, $i);
     $fieldType = mysql_field_type($result, $i);

     if($i>0){
          $insertFields = $insertFields.$fieldName.',';
          $insertValues = $insertValues.' _'.$fieldName.',';
     }

     $updateList = $updateList.' '.$fieldName.'='.' _'.$fieldName.',';

     $fieldFormat = '';
     $fieldFormat = $fieldFormat.' _'.$fieldName;
     $fieldFormat = $fieldFormat.' '.$fieldType;
     $fieldFormat = $fieldFormat.' '.',<br/>';

     $paramList = $paramList.' '.$fieldFormat;
}

$insertFields = $insertFields.')';
$insertValues = $insertValues.')';

$updateList = $updateList.')';

$paramList = $paramList.')<br/>';
$paramList = str_replace('int','int(11)',$paramList);
$paramList = str_replace('string','text',$paramList);
$paramList = str_replace(',)',')',$paramList);

$insertFields = str_replace(',)',')',$insertFields);
$insertValues = str_replace(',)',')',$insertValues);

$updateList = str_replace(',)','',$updateList);

$spText = '<br/><br/>DELIMITER $<br/>';
$spText .= ' <br/>DROP PROCEDURE IF EXISTS Manage'.$tableName.' $<br/>';
$spText .= ' <br/>CREATE PROCEDURE Manage'.$tableName.'<br/>';
$spText .= $paramList;
$spText .= ' <br/>BEGIN<br/>';
$spText .= ' <br/>IF _'.mysql_field_name($result, 0).' = 0 THEN<br/>';
$spText .= ' INSERT INTO '.$tableName.' '.$insertFields;
$spText .= ' VALUES '.$insertValues.';';
$spText .= '<br/> ELSE<br/>';
$spText .= ' UPDATE '.$tableName.' SET '.$updateList;
$spText .= ' WHERE '.$tableIdField.'=_'.$tableIdField.';';
$spText .= ' <br/>END IF;<br/>';
$spText .= ' <br/>END $<br/>';
$spText .= ' <br/>DELIMITER ;<br/>';

echo '<br/><strong>Insert/Update stored Procedure: </strong><br/>';

echo $spText;
$spText='';

echo '<br/><br/><br/><br/>';

$spText = '<br/><br/>DELIMITER $<br/>';
$spText .= ' <br/>DROP PROCEDURE IF EXISTS Read'.$tableName.' $<br/>';
$spText .= ' <br/>CREATE PROCEDURE Read'.$tableName.'<br/>';
$spText .= '(_id int(11))';
$spText .= ' <br/>BEGIN<br/>';
$spText .= ' <br/>IF _id = 0 THEN<br/>';
$spText .= ' SELECT * FROM '.$tableName.';';
$spText .= '<br/> ELSE<br/>';
$spText .= ' SELECT * FROM '.$tableName.' WHERE ID = _ID;';
$spText .= ' <br/>END IF;<br/>';
$spText .= ' <br/>END $<br/>';
$spText .= ' <br/>DELIMITER ;<br/>';

echo '<br/><strong>Select All/specific record stored Procedure: </strong><br/>';

echo $spText;

?>

Generate Auto Table of Contents in Microsoft Word

Generating table of contents automatically in Microsoft Word is one of the necessities for bachelor level students these days. We get loaded with lots and lots of projects each and every semester and along with the projects come reports.

Before 2-3 years, I didn’t know about this amazing feature in word. I’d say that I never tried it at all. In olden days, after we finish writing a project, we would first make a final draft of the project and then print it. After we print it, we look at the page numbers printed on them and make the table of contents. I don’t know about others, but this is how I used to finish my reports. And suppose there is a small change in the project report, all pages succeeding the changes section might need page number alterations, which was a big hassle.

But with Microsoft’s auto Table of Contents, we need not worry about any of the problems at all. All we need to do is relax and put the I-beam on a new page and click a button, choose the layout and “Walla”, you get a Table of contents. Now if you make small changes to your pages, there is always an “Update” button which does all of the work.

So how do we start using this feature then…???

Steps:

  1. Identify the headings and sub headings that you want your TOC to highlight.In a report the main headings may be Acknowledgements, Executive Summary, Main Body, Conclusion, etc. Identify these topics.
  2. Use Appropriate formatting to the headings and sub headingsFor the main headings identified, choose formatting as “Heading 1”.Heading 1 Formatting

    Then for the sub headings, format it as “Heading 2”.Heading 2 Formatting

    Again for the sub-sub headings format is as “Heading 3”. This way you format the headings on each page where you use the headings, in an abstract hierarchy.

  3. Press the magic button
    TOC Selection

    Go to the “References” ribbon and then select “Table of Contents”. It allows us to select a format for the TOC, jus t select the required format. That’s it. Now we can see the Table of Contents with updated page numbers and topics.

  4. Feel good about it.

Backup MySql database automatically

Hello,

Recently, I had to work on a rather out of the scope issue, regarding the backup of mysql databases automatically. I mean manual backing of data or databases can be trouble some, and one might forget usually. So, why not write a script that can be scheduled to run automatically. This will ensure that the data is backed up regularly, and there is no loss of data at least for 1 day interval.

 

Step 1:

The first thing to do here is to create a database backup from the command prompt. To accomplish this you need to have MySql installed on your computer (the one where the backup needs to be done). The server to be backed up can be on any other computer on the network, doesnt matter. You can always change the host. So, if you have Mysql installed on your machine, you should be able to find a mysqldump.exe file located in the bin folder. Lets say I have installed it inside the C:\Program Files, then the location of the mysqldump.exe should be

C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqldump.exe

This is the particular file required, that will connect to the mysql database server, and retrieve the dump file.

File Display
 

Step 2:

The next step is to actually write the dos command to perform the backup of the database. Let us open the command prompt. This can be done by Clicking on

Start > All Programs > Accessories > Command Prompt
or
Start > Run > type “cmd” > OK

Next, point your prompt to the location of the mysqldump.exe file using the following command

      cd C:\Program Files\MySQL\MySQL Server 5.5\bin

The syntax for the dos command can be seen as below

      mysqldump.exe –e –u[username] -p[password] -h[hostname] [database name] > C:\[filename].sql

For Example if my database name is “testdb”, username is “testuser”, password is “pass” and the hostname is “localhost”, then my dos command will look like

      mysqldump.exe -e -u testuser -p pass testdb>C:\testdb.sql

Once, we confirm that the above command works, we are ready create our batch file, which will be put up into the scheduler.

Ms Dos

 

Step 3:

Creating a Batch file. Open up notepad from

Start > All Programs > Accessories > Notepad
Or
Start > run > type “notepad” > OK

Type the above code into the notepad as give below

C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqldump.exe -e -u testuser -p pass testdb>C:\testdb.sql

Save the file as auto_backup.bat, where bat stands for batch. Place the batch file in a safe location, where it cannot be edited easily.

Another line that we need to add to the file is the renaming of the backup file according to the date. This will help keep the backup files according to the date. Add the following line to rename the backup file, assuming the file name is auto_backup.bat.

      ren C:\auto_backup.sql auto_backup%date:~4,2%-%date:~7,2%-%date:~10,4%.sql

The above command will rename the file as auto_backup_01_03_2012.sql

With the addition of the above code, you batch file will look like

C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqldump.exe -e -u testuser -p pass testdb>C:\testdb.sql

ren C:\auto_backup.sql auto_backup%date:~4,2%-%date:~7,2%-%date:~10,4%.sql

Save the file after that.

notepad
 

Step 4:

Assigning the batch file to be run at a certain time, using the Task Scheduler.

In Windows 7, it is found inside Control Panel > Administrative Tools > Task Scheduler

In Windows XP, it is found inside Control Panel > Scheduled Tasks

Create a new task, and when it asks for a program to run, choose the batch file that we just created. (auto_backup.bat), select a suitable repeat interval, and the time to run the file.

With that, we are done.

Simple PHP Calendar

Here is a simple PHP based calender script for your website.Simply copy and paste the code and get it working.

The script generates a calender widget,can be styled through CSS as desired and next and previous months can be navigated.

<?php

// core
$monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"]))  $_REQUEST["year"]  = date("Y");

$cMonth = $_REQUEST["month"];
$cYear  = $_REQUEST["year"];

$prev_year = $cYear;
$next_year = $cYear;

$prev_month = $cMonth-1;
$next_month = $cMonth+1;

if ($prev_month == 0 ) {
    $prev_month = 12;
    $prev_year = $cYear - 1;
}

if ($next_month == 13 ) {
    $next_month = 1;
    $next_year = $cYear + 1;
}
?>
<div id="calendar_div" name="calendar_div">
    <table width="200">
        <tr align="center">
          <td bgcolor="#999999" style="color:#FFFFFF">
            	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="50%" align="left">&nbsp;&nbsp;<a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $prev_month . "&year=" . $prev_year; ?>" style="color:#FFFFFF">Previous</a></td>
                      <td width="50%" align="right"><a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $next_month . "&year=" . $next_year; ?>" style="color:#FFFFFF">Next</a>&nbsp;&nbsp;</td>
                    </tr>
              </table>
          </td>
        </tr>
        <tr>
            <td align="center">
              <table width="100%" border="0" cellpadding="2" cellspacing="2">
                <tr align="center">
                  <td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong><?php echo $monthNames[$cMonth-1].' '.$cYear; ?></strong></td>
                </tr>
                <tr>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>M</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>W</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>F</strong></td>
                  <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td>
                </tr>

                <?php 
                	$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
                	$maxday    = date("t",$timestamp);
                	$thismonth = getdate ($timestamp);
                	$startday  = $thismonth['wday'];

                  for ($i=0; $i<($maxday+$startday); $i++) {
                    if(($i % 7) == 0 ) echo "<tr>\n";
                    if($i < $startday) echo "<td></td>\n";
                    else echo "<td align='center' valign='middle' height='20px'>". ($i - $startday + 1) . "</td>\n";
                    if(($i % 7) == 6 ) echo "</tr>\n";
                  }  
                 ?>
              </table>
            </td>
        </tr>
    </table>
</div>