Thursday, December 28, 2017

PHP Round up to specific number | Round to nearest number | Round to next multiple of number



<?php
#Round to the next multiple of 5, exclude the current number
function roundNumberToUp($n, $x = 5)
{
    return round(($n + $x / 2) / $x) * $x;
}
roundNumberToUp(10);    #10
roundNumberToUp(10.2);  #15
roundNumberToUp(11.5);  #15

#Round to the nearest multiple of 5, include the current number
function roundNumberToNearest($n, $x = 5)
{
    return (round($n) % $x === 0) ? round($n) : round(($n + $x / 2) / $x) * $x;
}
roundNumberToNearest(10);   #10
roundNumberToNearest(10.3); #10
roundNumberToNearest(10.5); #15
roundNumberToNearest(11.7); #15

#Round up to an integer, then to the nearest multiple of 5
function roundNumberToNearestAsInteger($n, $x = 5)
{
    return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
}
roundNumberToNearestAsInteger(10.3);    #15
roundNumberToNearestAsInteger(11.7);    #15



URL Redirect: Redirecting From of an iFrame


IFrame


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>IFrame Title</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("button").click(function() {
                window.top.location.href = 'https://pritomkumar.blogspot.com';
            });
        });
    </script>
</head>
<body>
<button type="button">Reload IFrame Parent</button>
</body>
</html>

To modify your iframe embed code, you will add the following attribute inside the opening iframe tag:
sandbox="allow-top-navigation allow-scripts allow-forms"

Container of IFrame


<style type="text/css">
    iframe {
        width: 40%;
        height: 95%;
        margin-left: calc(30%);
        border: 1px solid lightgray;
    }
</style>
<div>
    <iframe src="iframe-html.php" sandbox="allow-top-navigation allow-scripts allow-forms"></iframe>
</div>

Get Latest Record In Each MySQL Group



Table=check_group_by
id   group_by    value
-------------------------
1    1           Value 1
2    1           Value 2
3    1           Value 3
4    2           Value 4
5    2           Value 5
6    3           Value 6

Query will be as like:

SELECT id,group_by,value FROM check_group_by
WHERE id IN (
 SELECT MAX(id) FROM check_group_by GROUP BY group_by
)





SQL Fiddle Example



Friday, December 22, 2017

Get code line and file name that's executing processing the current function in PHP


function log() {
    try {
        $bt = debug_backtrace();
        $fileAndLine = "";
        for ($i = 0; $i < 10; $i++) {
            $row = $bt[$i];
            if (isset($row["file"]) && isset($row["line"])) {
                $fileAndLine = $row["file"] . "::" . $row["line"];
                $i = 50;
            }
        }
        return $fileAndLine;
    }
    catch (Exception $ex) {
        return "";
    }
}


Tuesday, December 19, 2017

Grails on Groovy: Get Retrieve MySQL Database name from DataSource | Get List of MySQL Tables | Execute MySQL Raw Query




import grails.util.Holders
import org.hibernate.SessionFactory
import org.apache.commons.lang.StringUtils

def dataSource
SessionFactory sessionFactory

String connectionURL = dataSource.targetDataSource.targetDataSource.poolProperties.url
connectionURL = StringUtils.substringAfterLast(connectionURL, '/')
connectionURL = StringUtils.substringBefore(connectionURL, '?')
println(connectionURL)

String databaseName = sessionFactory.currentSession.createSQLQuery("SELECT DATABASE()")
        .setReadOnly(true).setCacheable(false).list().first()
println(databaseName)

String query = "SELECT table_name FROM information_schema.tables WHERE table_schema='$databaseName'".toString()
List list = sessionFactory.currentSession.createSQLQuery(query)
        .setReadOnly(true).setCacheable(false).list()
println(list.size())
println(list)




Saturday, December 16, 2017

MYSQL Group Concat Select Some Selected Rows Only | Use Sort In Group Concat | Sort MySQL Rows in Group Concat

Its so simple. Just need to do below thins:
SELECT SUBSTRING_INDEX(GROUP_CONCAT(x.id ORDER BY x.nx DESC), ',', 2) as row_name from some_table GROUP BY some_field
It will select First two values only.
It total value of GROUP_CONCAT is "1,2,3,4,5" Then Using SUBSTRING_INDEX would be like "1,2"
You can use DISTINCT in GROUP_CONCAT function like
SUBSTRING_INDEX(DISTINCT(GROUP_CONCAT(x.id ORDER BY x.nx DESC)), ',', 2)

Friday, December 8, 2017

Mysql GROUP_CONCAT of first n rows || Selecting first and last values in a group || Select first and last row from group_concat when grouping sortable days




select s.id,count(e.id) as total,
substring_index(group_concat(e.id order by e.id asc),',',5) as group_value
from students s left join exams e on s.id=e.student_id
group by s.id
order by count(e.id) desc




Thursday, December 7, 2017

PHP Call Static Function Method Dynamically Based on __callStatic Method



<?php
abstract class ParentClass {
    public static function __callStatic($method, $args) {
        echo "Method=".$method.",Args=".json_encode($args)."\r\n<BR/>";
    }
}

class ChildClass extends ParentClass {
    public static function x1() {
        $args = func_get_args();
        call_user_func_array(
            array(parent::class, __FUNCTION__), $args
        );
    }
}

ChildClass::x1("x1", 10, 20);
ChildClass::x2("x2", 30, 40);


And output would be like:


Method=x1,Args=["x1",10,20] 
Method=x2,Args=["x2",30,40] 

Sunday, December 3, 2017

GRAILS GROOVY | GString Template Engine | Parse Simple String AS GString Template | String GSP Parser




def gEngine = new groovy.text.GStringTemplateEngine()
def binding = ["a": "a"]
String testVar = gEngine.createTemplate("MY ENGINE STRING AS=\${a}").make(binding).toString()
println(testVar)

Saturday, December 2, 2017

jQuery.noConflict() | Avoiding Conflicts with Other Libraries


(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $j = jQuery.noConflict();
        jQuery = $;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery previous version=" + $.fn.jquery + ", version=" + $j.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    loadJQuery();
})();


Check here for JSFiddle

Load jQuery with Javascript and use jQuery | Load jQuery dynamically




(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $ = window.jQuery;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery is loaded, after " + tookTime + " milliseconds!, version=" + $.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    if (window.jQuery) {
     alert("JQuery loaded");
    }
    else {
     alert("JQuery not loaded");
      loadJQuery();
    }
})();


Check here for JSFiddle



GIT | View Changed Details For Files By Commits | View List Of Files Changed During Different Commits

This below command will show changes made during last 3 commits for specific file defined
git diff HEAD~3..HEAD -- project/location/file.name
This command will list files changes made during last 3 commits
git diff --name-status HEAD~3..HEAD
This command will list files changes made during last 3 commits with changes
git diff HEAD~3..HEAD
Below command will show history of commits:
git log -3
git log -2
Below command will show difference between two commits:
git diff old_commit new_commit
git diff 5300b....4ea31a 754e8d....c33
git diff --name-status 5300b....4ea31a 754e8d....c33

MySQL Table Create Index Remove Index List Index | Primary Indexing | Unique Indexing | Field Indexing | FullText Indexing




/* Primary INDEXING */
ALTER TABLE `TABLE_NAME` ADD PRIMARY KEY (`ID`);

/* General INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD INDEX `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Unique INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD UNIQUE `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Fulltext INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD FULLTEXT `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Remove INDEXING */
DROP INDEX `INDEX_NAME` ON `TABLE_NAME`;

/* List INDEXING */
SHOW INDEX FROM `TABLE_NAME`;





Friday, December 1, 2017

MYSQL : SQL For Create Table Example




CREATE TABLE `table_name` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `int_field` BIGINT(20) NOT NULL DEFAULT '0',
  `string_field` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
  `long_text_field` LONGTEXT NULL COLLATE 'utf8_unicode_ci',
  `time_stamp_field` TIMESTAMP NULL DEFAULT NULL,
  `date_field` DATE NULL DEFAULT NULL,
  `date_time_field` DATETIME NULL DEFAULT NULL,
  `tinyint_field` TINYINT(1) NOT NULL DEFAULT '0',
  `double_field` DOUBLE(30,10) NULL DEFAULT '0.0000000000',
  `enum_field` ENUM('TRUE','FALSE') NULL DEFAULT 'TRUE' COLLATE 'utf8_unicode_ci',
  `set_field` SET('XA','XB','XC') NULL DEFAULT 'XA,XB' COLLATE 'utf8_unicode_ci',
  `uuid` VARCHAR(70) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `uuid` (`uuid`),
  INDEX `int_field_index` (`int_field`),
  INDEX `int_field_index_complex` (`int_field`, `string_field`)
) COLLATE='utf8_general_ci' ENGINE=InnoDB;