Monday, 22 March 2021

How to execute a python script from an html button

 There are various ways to make it done, very simple technique with security peace in mind, here might help you


1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code. If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)


2.Create a new folder
- 1st file will be server.py

Thursday, 8 October 2020

Generate data format from current date to x months

 /**

 * Generate data format from current date to x months
*
* @param $months
*
* @return DateTime|string
*
* @throws Exception
*/
function generateDateByMonths($months)
{
$date = '';
$time = '23:59:59';
if(is_numeric($months) && $months > 0) {
$date = new DateTime('now');
$date->modify('+'.$months.' month'); // or you can use '-2 months' for deduct
$date = $date->format('Y-m-d');
}
return $date . ' ' . $time;
}

Tuesday, 3 March 2020

JavaScript: remove duplicate in multidimensional array by using specific key

     function removeDuplicatesMulti(array) {
// Declare a new array
var newArray = [];
 
// Declare an empty object
var uniqueObject = {};
 
// Loop for the array elements
for (var i in array) {
// Extract the title or key based on duplicate finding
objTitle = array[i]['ID'];
 
// Use the title as the index
uniqueObject[objTitle] = netSerices[i];
}
 
// Loop to push unique object into array
for (i in uniqueObject) {
newArray.push(uniqueObject[i]);
}

return newArray;
}

JavaScript finding intersection values from the 2 arrays

function arrayIntersection(ar1, ar2) {
return ar1.filter(function(n) {
return ar2.indexOf(n) !== -1;
});
}

JavaScript function to remove duplicates in single dimension array

function removeDuplicatesInSingleDimensionArray(array) {
  return array.filter((a, b) => array.indexOf(a) === b)
};

Saturday, 2 February 2019

Tips To Improve JavaScript Performance

Tip #1 – Evaluate Local Variables

Primarily, specific to IE, because local variables are found based on the most to the least specific scope and can pass through multiple levels of scope, the look-ups can result in generic queries. When defining the function scope, within a local variable without a preceding var declaration, it is important to precede each variable with var in order to define the current scope in order to prevent the look-up and to speed up the code.

Tip #2 – Create shortcut codes to speed up coding

For useful codes that are constantly being used, speeding up the coding process can be achieved by creating shortcuts for longer codes, for example, document.getElementById. By creating a shortcut, longer scripts will not take as long to code and will save time in the overall process.

Tip #3 –Manipulate element fragments before adding them to DOM

Before placing the elements to the DOM, ensure that all tweaks have been performed in order to improve JavaScript performance. This will eliminate the need to set aside Prepend or Append jQuery APIs.

Tip #4 – Save bytes by using Minification

Reduce the file size of your JavaScript documents by removing characters (tabs, source code documents, spaces etc.) without changing the functionality of the file.
There are a number of minification tools that can assist in this process, and have the ability to reverse the minification. Minification is the process of removing all unnecessary characters from source code, without changing its functionality.

Tip #5 –Don’t use nested loops if not required

Avoid unwanted loops, such as for/while, in order to keep the JavaScript linear and to prevent from having to go through thousands of objects. Unwanted loops can cause the browser to work harder to process the codes and can slow down the process.

Tip #6 – Cache objects to increase performance

Many times, scripts will be repeatedly used to access a certain object. By storing a repeated access object inside a user defined variable, as well as using a variable in subsequent references to that object, performance improvement can be achieved immediately.

Tip #7 – Use a .js file to cache scripts

By using this technique, increased performance can be achieved because it allows the browser to load the script once and will only recall it from cache should the page be reloaded or revisited.

Tip #8 – Place JavaScript at the bottom of the page

Placing the scripts as low as possible in the page will increase the rendering progress, and also increase download parallelization. The result is that the page will seem to load faster, and in some cases it can also save on the total amount of code needed.

Tip #9 – Use jQuery as a framework

Used for the scripting of HTML, jQuery is an easy to use JavaScript library that can help to speed up any website. jQuery provides a large number of plug-ins that can quickly be used, by even novice programmers.

Tip #10 – Compress your files with GZip

GZip can reduce a JavaScript file considerably, saving bandwidth, and accelerate the response time. JavaScript files can be very large, and without compression, it can bog down any website. Smaller files provide a faster and more satisfying web experience.

Tip #11- Don’t use “With” keyword

The “With” keyword is considered a black-sheep because it suffers from several flaws that can be very frustrating. Although it makes the process of working with local properties simpler, “With” can make looking up variables in other scopes more expensive.

Tip #12 – Minimize requests for HTTP

Minimize HTTP requests to render pages by combining external files and including JavaScript directly within XHTML pages. Each time a unique HTTP takes a trip to a server, the result is a large number of delays.

Tip #13 – Implement Event Delegation

With Event Delegation, it becomes easier to use a single event handler to manage a type of event for the entire page. Without using Event Delegation, large web applications can grind to a halt because of too many event handlers. Benefits of Event Delegation include; less functionality to manage, fewer ties between code and DOM, and less memory required to process.

Tip #14 – Don’t use the same script twice

Duplicate scripts will have a significant impact on performance. Duplicate scripts will create unnecessary requests on HTTP, especially in the IE browser. Using a SCRIPT tag, in an HTML page, will help to avoid accidentally duplicating scripts.

Tip #15 – Remove Double Dollar $$

Using “double dollar $$” function is not necessarily needed, when it comes to improving the speed of a website.

Tip #16 – Creating reference variables

When working with a specific node repeatedly, it is best to define a variable with that particular note, instead of switching to it repeatedly. This is not a significant enhancement but it can have a bigger impact on a large scale.

Tip #17 – Increase speed of Object Detection

A more efficient method to using Object Detection is to use a code created dynamically based off of object detection, rather than performing object detection inside of a function.

Tip #18 – Write effective Loops

Depending on the browser, the method used to write Loops can have a great effect on the performance of a site. Improper writing of loops can slow down pages with lots of queries and running a number of loops in parallel.

Tip #19 – Shorten Scope Chains

Global scopes can be slow, because each time a function executes, it cause a temporary calling scope to be created. JavaScript searchers for the first item in the scope chain, and if it doesn’t find the variable, it swells up the chain until it hits the global object.

Tip #20 – Index directly to NodeLists

NodeLists are live and can take up a lot of memory, as they are updated when an underlying document changes. Its quicker to index directly into a list, as a browser will not need to create a node list object.

Tip #21 – Don’t use ‘eval’

Although the “eval” function is a good method to run arbitrary code, each string that is passed to the eval function has to be parsed and executed on-the-fly. This cost has to be paid every time the execution reaches an eval function call.

Tip #22 – Use Function Inlining

Function Inlining helps to eliminate call costs, and replaces a function call with the body of the called function. In JavaScript, performing a function call is an expensive operation because it takes several preparatory steps to perform: allocating space for parameters, copying the parameters, and resolving the function name.

Tip #23 – Implement Common Sub-expression Elimination (CSE)

Common sub-expression elimination (CSE) is a performance-targeted compiler optimization technique that searches for instances of identical expressions and replaces them with a single variable holding the computed value. You can expect that using a single local variable for a common sub-expression will always be faster than leaving the code unchanged.

Tip #24 – Build DOM node and all its sub-nodes offline

When adding complex content such as tables to a site, performance is improved by adding complex sub-trees offline.

Tip #25 – Try not to use global variables

Because the scripting engine needs to look through the scope, when referencing global variables from within function or another scope, the variable will be destroyed when the local scope is lost. If variables in global scope cannot persist through the lifetime of the script, the performance will be improved.

Tip #26 – Use primitive functions operations vs. function calls

Improved speed can be achieved in performance critical loops and functions by using equivalent primitive functions instead of function calls.

Tip #27 – Don’t retain alive references of other documents

By not retaining alive references of other documents after the script has finished with them, faster performance will be achieved. This is because any references to those objects from that document are not to be kept in its entire DOM tree, and the scripting environment will not be kept alive in RAM. Thus the document itself is no longer loaded.

Tip #28 – Use XMLHttpRequest

XMLHttpRequest helps to reduce the amount of content coming from the server, and avoids the performance impact of destroying and recreating the scripting environment in between page loads. Its is important to ensure that XMLHttpRequest is supported, or otherwise it can lead to problems and confusion.

Tip #29 – Avoid using try-catch-finally

Whenever the catch clause is executed, where the caught exception object is assigned to a variable, “try-catch-finally” creates a new variable in the current scope at runtime. A number of browsers do not handle this process efficiently because the variable is created and destroyed at runtime. Avoid it!

Tip #30 – Don’t misuse for-in

Because the “for-in” loop requires the script engine to build a list of all the enumerable properties, coding inside for loop does not modify the array. It iterates pre-compute the length of the array into a variable len inside for loop scope.

Tuesday, 12 June 2012

Php isset


isset

(PHP 4, PHP 5)
issetDetermine if a variable is set and is not NULL

reject note Description

bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

reject note Parameters

var
The variable to be checked.
...
Another variable ...

reject note Return Values

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

reject note Changelog

VersionDescription
5.4.0
Checking non-numeric offsets of strings now returns FALSE

Example #1 isset() Examples
<?php

$var 
'';
// This will evaluate to TRUE so the text will be printed.if (isset($var)) {
    echo 
"This var is set so I will print.";
}
// In the next examples we'll use var_dump to output
// the return value of isset().
$a "test";$b "anothertest";
var_dump(isset($a));      // TRUEvar_dump(isset($a$b)); // TRUE
unset ($a);
var_dump(isset($a));     // FALSEvar_dump(isset($a$b)); // FALSE
$foo NULL;var_dump(isset($foo));   // FALSE
?>


This also work for elements in arrays:

<?php

$a 
= array ('test' => 1'hello' => NULL'pie' => array('a' => 'apple'));
var_dump(isset($a['test']));            // TRUEvar_dump(isset($a['foo']));             // FALSEvar_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try: 
var_dump(array_key_exists('hello'$a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUEvar_dump(isset($a['pie']['b']));        // FALSEvar_dump(isset($a['cake']['a']['b']));  // FALSE
?>

Example #2 isset() on String Offsets
PHP 5.4 changes how isset() behaves when passed string offsets.
<?php
$expected_array_got_string 
'somestring';var_dump(isset($expected_array_got_string['some_key']));var_dump(isset($expected_array_got_string[0]));var_dump(isset($expected_array_got_string['0']));var_dump(isset($expected_array_got_string[0.5]));var_dump(isset($expected_array_got_string['0.5']));var_dump(isset($expected_array_got_string['0 Mostel']));?>
Output of the above example in PHP 5.3:
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
Output of the above example in PHP 5.4:
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)