Wednesday, December 19, 2018

imap.sfu.ca can not be verified message in iphone




"imap.sfu.ca can not be verified message" message popups in iPhone,
Remove those accounts using imap.sfu.ca, add accounts using mail.sfu.ca instead.
To remove email accounts in iphone 8.
1) Go to settings
2) Passwords & accounts
3) Click those accounts using imap.sfu.ca
4) Click "Delete Accounts"

To add accounts using mail.sfu.ca:
https://www.sfu.ca/sfumail/using-sfu-mail/getting-started/mobile-devices/ios.html

Monday, December 17, 2018

Maximum Ei weekly rate for 2019 (Canada)




Maximum insurable earnings (MIE) for 2019 is $53100.
For most people, the basic rate for calculating benefits is 55% of the weekly
average insurable earnings. Maximum EI weekly pay rate for 2019 = 53100*0.55/52=$562

Thursday, December 13, 2018

Export excel in PHPMyADmin




Click Export,
Under Format,  from dropdown menu select
OpenDocument Spreadsheet
and click go button

Tuesday, December 11, 2018

view saved password in iphone




In Settings->Passwords & Accounts
click Website & App Passwords

Thursday, December 6, 2018

MySQL max characters in GROUP_CONCAT




MySQL max characters in GROUP_CONCAT is 1024 characters by default. To increases the size,
in MySQL script run
SET SESSION group_concat_max_len = 10000;
first.

Thursday, November 29, 2018

MySQl, current date add 2 months




 MySQl, current date add 2 months
DATE_ADD(CURDATE(), INTERVAL (2) MONTH) 

Example:
SELECT fhs.Term AS term,s.Stakeholder_id AS stakeholder_id  FROM `fm_sita_historical`  AS  fhs
                    INNER JOIN
                    stakeholders AS s
                     ON s.Emplid = fhs.SFU_ID
                   
                    UNION
                    SELECT semester AS term,stakeholder_id  FROM `contract_si_ta_percourse`
                    WHERE cancelled='N'
                    AND (block='Y' OR gblock ='Y' OR cblock ='Y')
                    AND semester <(
                    SELECT `Term`
                                FROM terms_lut
                                WHERE  DATE_ADD(CURDATE(), INTERVAL (2) MONTH) BETWEEN     StartDate AND EndDate ) 

Wednesday, November 28, 2018

MySQL case when in order




Example of  using CASE WHEN ... ELSE... END ) in ORDER BY in MySQL
                 ORDER BY
                    (CASE WHEN     ranks.`EndDate` IS NULL OR ranks.`EndDate`='0000-00-00' OR TRIM(ranks.EndDate)='' THEN '9999-12-20'
                     ELSE                  
                     ranks.`EndDate` END)
DESC,

Friday, November 23, 2018

Blank page/or undefined function mysql_pconnect() in CodeIgniter when upgrading from PHP5 to PHP 7




Run ttr_view1.php when upgrading    from PHP5 to PHP 7, get blank page
<?php
if (!defined('BASEPATH')) die();

class Ttr_view1 extends CI_Controller {

        public function __construct() {
              parent::__construct();
              $this->load->model('auth');
        }

         public function test(){

                $data['styleSheets'] = array('ttr.css', 'shared.css');
                $data['title'] = "Access Denied";

         $this->load->view('access_denied', $data);

        }
}
?>

Add             
 error_reporting(E_ALL);
ini_set('display_errors', '1');

at top, get error message
"Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in
/var/www/tracs/new6sp/system/database/drivers/mysql/mysql_driver.php:91 Stack trace: #0
 /var/www/tracs/new6sp/system/database/DB_driver.php(115): CI_DB_mysql_driver->db_pconnect() #1
 /var/www/tracs/new6sp/system/database/DB.php(148): CI_DB_driver->initialize() #2
 /var/www/tracs/new6sp/system/core/Loader.php(346): DB(Array, NULL) #3
 /var/www/tracs/new6sp/application/models/stakeholders.php(23): CI_Loader->database() #4"


 In CodeIgniter application/config/database.php
 /var/www/tracs/new6sp/application/config/database.php
 line 56 change
   $db['default']['dbdriver'] = 'mysql';
 to
   $db['default']['dbdriver'] = 'mysqli';

Left shift operation in PHP when upgrading from PHP5 to PHP 7




1<< -1 is OK for PHP 5, but fails for PHP 7.
Directly using 1<< -1 = -9223372036854775808
(Obtained from PHP Sandbox http://sandbox.onlinephpfunctions.com/)
/var/www/html/new6sp/application/controllers/ttr_view.php
line 781 change from               
        if($rcode < 33) {
            $code = 1 << $rcode;
            $r[$sid]['terms'][$term]['code'] |= $code;
        }else{
            $code = 1 << ($rcode-33);
            $r[$sid]['terms'][$term]['code_upper'] |= $code;
        }

to
        if($rcode < 0) {
            $code = -9223372036854775808;
            $r[$sid]['terms'][$term]['code'] |= $code;
        }               
        elseif($rcode < 33) {
            $code = 1 << $rcode;
            $r[$sid]['terms'][$term]['code'] |= $code;
        }else{
            $code = 1 << ($rcode-33);
            $r[$sid]['terms'][$term]['code_upper'] |= $code;
        }     
           

Error message in PHP upgrade: Only variable references should be returned by reference




 When I update PHP5.3 to PHP7, the following error message shows:

"A PHP Error was encountered
Severity: Notice
Message: Only variable references should be returned by reference
Filename: core/Common.php"



CodeIgniter system/core/Common.php
My code location:
/var/www/html/new6sp/system/core/Common.php
line 257 change
        return $_config[0] =& $config;
to      
        $_config[0] =& $config;
        return $_config[0];

JS/JQuery: paste the plain text only





When I copy the Word document to the text box,
in background a lot html codes and strange characters from Word
are saved.
Below is the JS/JQuery code to paste the plain text ( I have a text box with class comment):

function clickcomments($td){

    $td.find('.comment').on('paste', function(event){
            event.preventDefault();

            var text = (event.originalEvent || event).clipboardData.getData('text/plain') || prompt('Paste something..');

            window.document.execCommand('insertText', false, text);

            $(this).html($(this).html().replace(/<div>/g, '<br>').replace(/<\/div>/g, '<br>'));

    });
}        

Wednesday, November 21, 2018

Replace a string in MySQL





MySQL Replace function to replace a string
REPLACE(str,old_string,new_string);
Example code in PHP:
  $sql = "UPDATE         courses_offered AS offered
    INNER JOIN courses_lut
        ON courses_lut.course_id = offered.course_id
    LEFT JOIN contract_si_ta_percourse AS SITA
        ON SITA.stakeholder_id = {$this->sanitizeInput($arr['stakeholder_id1'])}
            AND  SITA.Session0=offered.Session
        AND SITA.courses_id = offered.course_id AND SITA.semester = offered.Term   
        AND CASE
           WHEN LEFT(offered.Section ,2) ='OP'
         THEN  SITA.instr_section = offered.Section
          WHEN  TRIM(courses_lut.CourseSubject)='FASS' AND TRIM(courses_lut.CourseNumber)='101'  
        THEN  SITA.instr_section = offered.Section                     
          WHEN
          left(offered.Section, 1) in ('A', 'N') and right(offered.Section, 1) = '0'
            THEN
              SITA.instr_section = CONCAT(LEFT(offered.Section ,3),'0')
        ELSE SITA.instr_section = CONCAT(LEFT(offered.Section ,2),'00')
        END
        SET SITA.instr_section = REPLACE(SITA.instr_section, '$section1','$section2'),
          SITA.assign_section = REPLACE(SITA.assign_section, '$section1','$section2')

    WHERE offered.courses_offered_id = {$this->sanitizeInput($arr['courses_offered_id1'])}";   

        

Get the dropdown list value and list in JQuery





I have a dropdown list class TaList in a column in a table.
To get the option value of dropdown list in JQuery:
  row3.find('td.TaList select').val();
To get the selected text of dropdown list in JQuery:
  stakeholder_name1 = row3.find('td.TaList :selected').text();
More codes:
$('div.ajax_list').find("#defaultTable").find('tr').each(function() {
    if($(this).find('.swap_option').attr('checked') == 'checked') total += 1;
    var row3=  $(this);
    if(total==1 && $(this).find('.swap_option').attr('checked') == 'checked'){
        courses_offered_id1=row3.find("input.courses_offered_id").val();
        stakeholder_id1 = row3.find('td.TaList select').val();
        stakeholder_name1 = row3.find('td.TaList :selected').text();
        section1 = row3.find('.TutSection').html();
        assignedID1 = row3.find('.assignedID').val();
    }
    if(total==2 &&$(this).find('.swap_option').attr('checked') == 'checked'){
        courses_offered_id2=row3.find("input.courses_offered_id").val();
        stakeholder_id2 = row3.find('td.TaList select').val(); 
        assignedID2 = row3.find('.assignedID').val();
        stakeholder_name2 = row3.find('td.TaList :selected').text();
        section2 = row3.find('.TutSection').html();               
    }           
});  

Sunday, April 22, 2018

datatable order by nunmeric




https://datatables.net/examples/plug-ins/dom_sort.html 
For number, 1,2, 100,3 when datatable treats them as string, the order will be
1, 100, 2,3. We need to treat them as number and the order asc should be
1,2,3,100. The following is DataTable code  for numeric order


/* Create an array with the values of all the input boxes in a column */
$.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val();
    } );
}
 
/* Create an array with the values of all the input boxes in a column, parsed as numbers */
$.fn.dataTable.ext.order['dom-text-numeric'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val() * 1;
    } );
}
 
/* Create an array with the values of all the select options in a column */
$.fn.dataTable.ext.order['dom-select'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('select', td).val();
    } );
}
 
/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).prop('checked') ? '1' : '0';
    } );
}
 
/* Initialise the table with the required column ordering data types */
$(document).ready(function() {
    $('#example').DataTable( {
        "columns": [
            null,
            { "orderDataType": "dom-text-numeric" },
            { "orderDataType": "dom-text", type: 'string' },
            { "orderDataType": "dom-select" }
        ]
    } );
} );

Tuesday, March 20, 2018

PHP remove useless zero from decimal and number format




1) PHP remove useless zero from decimal
 floatval(1.0);
return 1
2) number format
number_format(100.23, 1','' ');
  return 100.2
3) return integer part
intval(4.2);
return 4

Saturday, March 17, 2018

deposit cheque in TD bank using Mobile phone




Deposit cheque in  TD bank using Mobile phone. I try once ad success and found it is pretty easy and I don not need to walk to bank machine to deposit my check.
1) Download TD App
2) login TD account and  click deposit
3) Take a photo of the front and back of the completed cheque. Make sure the frame shown in
Mobile match check frame.
4) Submit
5) Click Deposit button in TD App again to view Mobile deposit history

How to connect iPhone 5 to Windows 10 PC





I can not see my iPhone   5 when I connect to Windows 10 PC, which worked before.
I realize I need to download iTunes
1) Go to www.apple.com/itunes
2) Download iTunes6464Setup.exe installer and install
3) restart PC.
4) Connect iPhone to PC
  1. Trust this Computer? will appear on your iPhone. Click Trust.
  2. 'Do you want this computer to access your iPhone?' will appear in Windows. Click Continue.
5) open iTune
6) Click on Device in iTunes and choose your iPhone
7) You can back up or Sync iPhone  to Windows 10,but only for audio files
But at least I can see my iPhone icon in PC and delete video files or copy videos files

Friday, March 2, 2018

Undefined Values in JS is not posted In AJAX Requests





In following JS code
function saveLTDrowConv(parent){
                pad_id =$('select[name="department1"] option:selected').val();
                 year =$('select[name="ReviewYear"] option:selected').val();
                 Deanrecommd = parent.find('.term_CONV_Dean').val();
                 conv  = parent.find('.term_CONV').val();
                 fte = parent.find('.term_CONV_fte').val();
                 sfu_id  = parent.find('.sfuid').html();
                 var filter = {

                        "pad_id":pad_id,
                        "year":year,
                        "sfu_id":sfu_id,
                        "fte":fte,
                        "Deanrecommd":Deanrecommd,
                        "conv":conv

                }
                 parent.find('.ltd_CONV_row').attr('disabled','disabled');
                 $.post("/tracs/ajax/facultyHiringPlan_ajax/saveLTDrowConv",  {"post":filter
                        }, function(data) {
                 
                        parent.find('.ltd_CONV_row').removeAttr('disabled');

                        $("div#notice").html('Update successfully.');
                        $("div#notice").css('display', 'block');
                        $("div#notice").fadeOut(5000);  


                });
}

If  Deanrecommd is undefined and  we post Deanrecommd, the server will not receive
Deanrecommd. i.e no $post['Deanrecommd']  in server. So as to other post variables.

Monday, February 19, 2018

update php version in Linux/Unix with Apache





1)Type the following command on RHEL / Red Hat / CentOS / Fedora Linux based system to find out php version:
yum info php
My server return
Name        : php
Arch        : x86_64
Version     : 5.3.3
Release     : 40.el6_6
Size        : 3.5 M
Repo        : installed
From repo   : rhel-x86_64-server-6
2) In my  /etc/sysconfig/ha/conf/httpd.conf
LoadModule php5_module        modules/libphp5.so
I plan to change it to PHP7
LoadModule php7_module modules/libphp7.so
For safety and test, I'll use manually install PHP7 instead using yum
3) To start and stop or restart Apache
 sudo service httpd stop
sudo service httpd restart
4) In /etc/php.ini
I installed ibm_db2.so for PHP5
extension=/usr/lib64/php/modules/ibm_db2.so
Need to check ibm_db2.so OK for PHP7, save a copy of php.ini
Reference:
https://www.ibm.com/developerworks/community/blogs/96960515-2ea1-4391-8170-b0515d08e4da/entry/Install_PHP_ibm_db2_Driver?lang=en
5)get php 7 from http://www.php.net
gunzip < php-7.1.6.tar.gz | tar xvf -
Finally produce libphp7.so and modify httpd.conf and reatart Apache
6) I may need to re-install phpmyadmin
Reference:
https://code.tutsplus.com/tutorials/upgrading-your-linux-server-to-php-7--cms-27583

Make DataTable Cell contenteditable





Example code  DataTable Cell  contenteditable
html:
<div style="padding:20px">
  <div class="row rowAddLine">
    <div style=" text-align: right;">
      <button type="button" id="btnAddRow" class="btn btn-info"><i class="fa fa-plus" style="margin-right:10px;"></i>Add</button>
    </div>
  </div>
  <div class="row">
    <div class="table-responsive">
      <table id="id_table" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
          <tr>
            <th>Column1</th>
            <th>Column2</th>
            <th>Column3</th>
            <th class="noWidth">Column4</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>freerf</td>
            <td>rfrfe</td>
            <td>erferfrfe</td>
            <td class="noWidth">
              <button class="action btn btn-default" type="button">
                <span class="glyphicon glyphicon-remove"></span>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

 
JS

$(document).ready( function () {
    var myTable = $('#id_table').DataTable({"bSort" : false, "createdRow": function ( row, data, index ){
                    $("td:last", row).addClass("noWidth");}
                });
 
    function makeEmptyArray(nbElements){
            var arr = [];
            for(var i=0; i<nbElements-1; i++)
            {
                arr.push("");
            }
            arr[i] = '<button type="button" class="action btn btn-default"><span class="glyphicon glyphicon-remove"></span></button>';
            return arr;
        }


 var emptyArrayOfElement = makeEmptyArray(myTable.columns().nodes().length);


  // Add row after click on the button 'add row'
  $("#btnAddRow").click(function(){
    var row = myTable.row.add(emptyArrayOfElement).draw(false).node();
    myTable.page('last').draw('page');
    $('html, body').animate({
      scrollTop : $(row)[0].offsetTop
    }, 500);
  });
 
 
  // Making TD editable exept td with action button
  $('body').on('dblclick', 'td:not(:has(button))', function(){
    // The cell that has been clicked will be editable
    $(this).attr('contenteditable', 'true');
    var el = $(this);
    // We put the cursor at the beginning
    var range = document.createRange();
    var sel = window.getSelection();
    if(el[0].childNodes.length > 0)
    {
      range.setStart(el[0].childNodes[0],0);
      range.collapse(true);
      sel.removeAllRanges();
      sel.addRange(range);
    }
    // The cell have now the focus
    el.focus();

    $(this).blur(endEdition);
  });

  function endEdition()
  {
  
    // We get the cell
    var el = $(this);
   
    // We tell to datatable to refresh the cache with the DOM, like that the filter will find the new data added in the table.
    // BUT IF WE EDIT A ROW ADDED DYNAMICALLY, THIS INSTRUCTION IS A PROBLEM
    myTable.cell( el ).invalidate().draw();
   
    // When the user finished to edit a cell and click out of the cell, the cell can't be editable, unless the user double click on this cell another time
    el.attr('contenteditable', 'false');

    el.off('blur', endEdition); // To prevent another bind to this function
  }
 
  } );

  CSS
  .noWidth {width: 0px;}
  Reference
  https://codepen.io/robert91/pen/wWwmeE

contenteditable div vs textarea





contenteditable div   is more flexible comparing to textarea.  The height is adjusted automatically.
Example  of contenteditable div:
<div contenteditable='true'  id='award' class='award_name cfl_row' style= 'border: 1px solid red; min-height:70px;width:200px;border-radius: 5px;
        border-color:green;margin: 5px 0px;padding:5px 5px 5px 5px;background-color: #F5EAF7;'></div>

To get value of contenteditable div, using id and html()
$('#award').html();

Using  focusout instead of change for contenteditable div

$('.changeable').focusout(function() {
  alert('Handler for .change() called.');
});
 
Example of textarea:
<textarea id='award' class='comments cfl_row' cols=25 rows=2></textarea> 
To get value of textarea:
$('#award').val();
(Note $('#award').text(); works sometimes and fails other times! It's not reliable)

Thursday, February 15, 2018

PHP code editors





 PHP code editors
1) Notepad++FLOSS multi-language editor with macro support, syntax highlighting
2) Visual Studio Code
3) Aptana Studio
4) SublimeText
5) Eclipse

Reference
https://en.wikipedia.org/wiki/List_of_PHP_editors

Remove CKEDITOR built in SCAYT spellcheck, using default HTML5 spell check




To enable CKEDITOR  for following textarea,
<textarea id="EditManual "></textarea>
To remove CKEDITOR built in SCAYT spellcheck, using default HTML5 spell check
JavaScript code
       CKEDITOR.replace( 'EditManual', {
            removePlugins: 'scayt,wsc',
            disableNativeSpellChecker: false
        });

Spell Check in input box and textarea in Firefox and Chrome





Default spell check for textarea tag is  true, but false is for input tag in HTML form.
 To enable spellcheck in input text box in HTML form
<input id="title0" spellcheck="true" value="1"/> 
To enable spellcheck in textarea in HTML form
<textarea> </textarea>
or
<textarea spellcheck="true"> </textarea>
To disable spellcheck  in textarea in HTML form
 <textarea spellcheck="flase"> </textarea>
After enable spellcheck ,    red underlines will be shown below the incorrect words.

Tuesday, February 13, 2018

DataTable FAQ - Update search when changing input, textarea and selected text (dropdown menu)





When changing input and selected text (dropdown menu) in datatable, datatable should immediately
update the search.
For column with selected text from dropdown with select tag:
a) get value for search
     $.fn.dataTableExt.ofnSearch['html-select'] = function(sData) {
        return $("<div/>").html(sData).find(':selected')
                            .text();
     };
b) update when select change
    $('#'+tableId).find("td select").on('change', function() {
          var $td = $(this).closest('td');
          var value = this.value;
          $td.find('option').each(function(i, o) {
            $(o).removeAttr('selected');
            if ($(o).val() == value){ $(o).attr('selected','selected');}
          })
          $td.find('select').val(value);
           table.cell($td).invalidate().draw();             
       });    For column with input and textarea  tag:   
a) get value for search   
     $.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
        return $(value).val();
     };       
b) update when input change
    $('#'+tableId).find("td input").on('change', function() {
        var $td = $(this).parent();
             $td.find('input').attr('value', this.value);
           table.cell($td).invalidate().draw();
    });
c) update when textarea change
      $("#result").find('#'+tableId).find('textarea').on('change', function() {
        var $td = $(this).parent();
       $td.find('textarea').text(this.value);
       table.cell($td).invalidate().draw();          
    });  
  
Example JS code is as following (assume 9th column (column=8) with select dropdown
and third column (column=2) with input, 10thcolumn (column=9) for textarea), assume table id is defaultTable:   

     $.fn.dataTableExt.ofnSearch['html-select'] = function(sData) {
        return $("<div/>").html(sData).find(':selected')
                            .text();
     };
     $.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
        return $(value).val();
     };       
    var tableId='defaultTable';
    table= $("#result").find('#'+tableId).DataTable( {
                                     destroy: true,
                                    paging: false,
                                    columnDefs: [
                                       { "type": "html-select", "targets": [8] },
                                        { "type": "html-input", "targets": [2,9] }
                                    ],
                                fixedHeader: true
                            } );   
                           
    $('#'+tableId).find("td input").on('change', function() {
        var $td = $(this).parent();
             $td.find('input').attr('value', this.value);
           table.cell($td).invalidate().draw();
    });
     $("#result").find('#'+tableId).find('textarea').on('change', function() {
        var $td = $(this).parent();
       $td.find('textarea').text(this.value);
       table.cell($td).invalidate().draw();          
    });    


    $('#'+tableId).find("td select").on('change', function() {
          var $td = $(this).closest('td');
          var value = this.value;
          $td.find('option').each(function(i, o) {
            $(o).removeAttr('selected');
            if ($(o).val() == value){ $(o).attr('selected','selected');}
          })
          $td.find('select').val(value);
           table.cell($td).invalidate().draw();             
       });            

DataTable FAQ - exporting to EXCEL for column with input and selected text (dropdown menu)





For column with selected text from dropdown with select tag:
    data = table
    .cell( {row: row, column: column} )
    .nodes()
    .to$()
    .find(':selected')
    .text();


For column with input  tag:   
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find('input')
                            .val();   

  

Example JS code is as following (assume 9th column (column==8) with select dropdown
and thrid column (column--2) with input):   
    var buttonCommon = {
        exportOptions: {
            format: {
                body: function(data,  row, column) {
                             if(column==8)
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find(':selected')
                            .text();
                             if(column==2)
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find('input')
                            .val();               
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                },
                header: function(data, column, row) {
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                }
              }
            }
    };
    $.extend(true, $.fn.dataTable.defaults, {
              "lengthChange": false,
              "pageLength": 100,
              "orderClasses": false,
              "stripeClasses": [],
               "destroy": true,
              dom: 'Bfrtip',
              buttons: [
                    $.extend(true, {}, buttonCommon, {
                      extend: 'excel',
                      exportOptions: {
                              columns: ':visible'
                     },

                      customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                            $('row c[r^="A"]', sheet).attr( 's', '50' ); //<-- left aligned text for A column                                       
                            var col = $('col', sheet);
                            col.each(function () {
                                     $(this).attr('width', 20);
                            });
          
              }
            })
          ]
      }
    );

DataTable FAQ - Set text align and cell width when exporting to EXCEL





1) To set A column text left aligned when exporting to EXCEL using DataTable
   $('row c[r^="A"]', sheet).attr( 's', '50' );

  2) To set All column width 20
    var col = $('col', sheet);
    col.each(function () {
             $(this).attr('width', 20);
    });
  

3) To set first column width 10
    $(col[0]).attr('width', 10);

4) Example JS code is as following:   
    var buttonCommon = {
        exportOptions: {
            format: {
                body: function(data,  row, column) {
               
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                },
                header: function(data, column, row) {
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                }
              }
            }
    };
    $.extend(true, $.fn.dataTable.defaults, {
              "lengthChange": false,
              "pageLength": 100,
              "orderClasses": false,
              "stripeClasses": [],
               "destroy": true,
              dom: 'Bfrtip',
              buttons: [
                    $.extend(true, {}, buttonCommon, {
                      extend: 'excel',
                      exportOptions: {
                              columns: ':visible'
                     },

                      customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                            $('row c[r^="A"]', sheet).attr( 's', '50' ); //<-- left aligned text for A column                                       
                            var col = $('col', sheet);
                            col.each(function () {
                                     $(this).attr('width', 20);
                            });
                            $(col[0]).attr('width', 10);
                            $(col[1]).attr('width', 40);
                            $(col[2]).attr('width', 50);   
          
              }
            })
          ]
      }
    );

DataTable FAQ - Keep line break when exporting to EXCEL, columns and rows visible





To keep line break <br/>, <br /> or <br> when exporting to EXCEL,
we can use data.replace(/<br\s*\/?>/ig, "\r\n") to replace
<br/>, <br /> or <br> to \r\n in EXCEL.
But the cell text should be wrapped.
    $('row c', sheet).each( function () {
                $(this).attr( 's', '55' );
    });   

Only export visible rows and columns to EXCEL
                                  extend: 'excel',
                                  exportOptions: {
                                          rows: ':visible',
                                          columns: ':visible'
                                 },

Example JS code is as following:   
    var buttonCommon = {
        exportOptions: {
            format: {
                body: function(data,  row, column) {
               
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                },
                header: function(data, column, row) {
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                }
              }
            }
    };
    $.extend(true, $.fn.dataTable.defaults, {
              "lengthChange": false,
              "pageLength": 100,
              "orderClasses": false,
              "stripeClasses": [],
               "destroy": true,
              dom: 'Bfrtip',
              buttons: [
                    $.extend(true, {}, buttonCommon, {
                      extend: 'excel',
                      exportOptions: {

                             rows: ':visible',    
                          columns: ':visible'
                     },

                      customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                      //All cell wrapped text
                            $('row c', sheet).each( function () {
                                        $(this).attr( 's', '55' );
                            });       
          
              }
            })
          ]
      }
    );

DataTable FAQ - hide showing entries in summary





 In DataTable, you may see the summary line
"Showing 1 to 2 of 2 entries".
You may need to hide this line.

If your table id is 'defaultTable', then
this line id is defaultTable_info.

Jquery code to hide showing entries in DataTable

var tableId = 'defaultTable';
$('#'+tableId+"_info").hide();   

Monday, February 12, 2018

Bootstrap basic tutorial




Bootstrap (can be downloaded from https://getbootstrap.com/)

Build responsive, mobile-first projects on the web with the world's most popular front-end component library.

Bootstrap is an open source toolkit for developing with HTML, CSS, and JS

A) Container 
  <div class="container"></div>
 or
 <div class="container-fluid"></div>
    The .container class: responsive fixed width container
    The .container-fluid class: full width container over entire width of the viewport. This should be used for the application mainly for desktop.

B) Bootstrap Grid System
The # sign below is the place-holder for the number of columns.
Bootstrap's grid system allows up to 12 columns across the page.
.col-sm-12 for full screen width while .col-sm-6 for half screen width
column class: .col-xs-#  (Extra small, for phone screen less than 768px)   
column class: .col-sm-#  (small, for  tablets  screen  >= 768  px)
column class: .col-md-#  (Medium, for  small laptops  screen  >= 991 px)   
column class: .col-lg-#  (Large, for  laptop screen  >=1200 px)
Example
 <div class="row">
  <div class="col-sm-4">4 column width for not small device</div>
  <div class="col-sm-8">8 column width for not small device</div>
</div> 

For small device such as phone and tablet for above example, the columns will automatically stack.

C) Table
1) .table-striped   adds zebra-stripes to each row in a table, Example of table in Bootstrap
<div class="container-fluid">
  <h2>Striped Rows</h2>
  <table class="table table-striped">
    <thead>
      <tr>
        <th>header column</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>body column</td>
      </tr>
    </tbody>
  </table>
</div>

2)  .table-bordered:  adds borders on all sides of the table and cells:
3) .table-hover class adds a grey background hover effect
4)  .table-condensed makes a table more compact
5) .table-responsive  creates a responsive table.
6)  contextual classes: 
.active     .success     .info  .warning  .danger    

D) Alert
Example
<div class="alert alert-success"> </div>
<div class="alert alert-info"></div>
<div class="alert alert-warning"></div>
<div class="alert alert-danger"></div>    


More about Bootstrap tutorial
https://www.w3schools.com/bootstrap/



Sunday, February 11, 2018

Design Reponsive web application



To Design Reponsive web application
 1) Add media query in CSS
Display 24 px in h2, but 16px h2 in mobile CSS
h2{
      font-size: 24px;
}

add media query
@media screen and (max-width: 39.9375em){
    h2{
          font-size: 16px;
    }

2) Usefule softwares and tools 
A) Install npm and node.js - Javascript  package manager
npm opens up an entire world of JavaScript talent to you and to your team. It's the world's largest software registry, with approximately 3 billion downloads per week.The registry contains over 600,000 packages (building blocks of code). Open-source developers from every continent use npm to share and borrow packages.

Install Node.js & npm

If you're using OS X or Windows, use one of the installers from the Node.js download page. Be sure to install the version labeled LTS. Other versions have not yet been tested with npm.

more about install npm
https://docs.npmjs.com/getting-started/installing-node

node.js download:
https://nodejs.org/en/

B) Bootstrap (can be downloaded from https://getbootstrap.com/)

Build responsive, mobile-first projects on the web with the world's most popular front-end component library.

Bootstrap is an open source toolkit for developing with HTML, CSS, and JS

C) AngularJS (can be downloaded from https://angular.io/guide/quickstart)

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.