App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

#############################################################

# Javascript loaded in via ajax is not automatically executed.

# AJAX Javascript Example
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

# AJAX Javascript Example (simpler)
# 'onload' is newer and a replacement for 'onreadystatechange' with the state check
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onload = function() {                       // <== Difference
     document.getElementById("demo").innerHTML = this.responseText;
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

# Submit a form using ajax. (prevents auto reload)
function save_details(endpoint) {
    console.log("POST ", endpoint);
    const form  = document.querySelector("form[id=details]");
    const xhttp = new XMLHttpRequest();
    xhttp.open("POST", endpoint);
    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhttp.send( $("#details").serialize() );
}


#############################################################
## Javascript - Attributes
#############################################################

# Set/Get meta data for an HTML element
form = document.querySelector("form[id=details]");
form.setAttribute('_meta', "my_meta")
form.getAttribute('_meta')


#############################################################
## Javascript - Benchmark
#############################################################

# Time a function in javascript (benchmark)
# Not really accurate
const startTime = new Date().getTime();
const endTime = new Date().getTime();
console.log("sort function took " + (endTime-startTime) + "(ms)")

# Function for benchmarking different code snippets (timing,testing,profiling)
# Simple.
function benchmark(functions,iterations=1) {
  for(const code of functions){ // foreach loop in javascript
    const name = code.name;     // Code refence to name
    console.time(name);         // Timing/benchmarking function
    for(let i = 1; i <= iterations; i++ )
      code();
    console.timeEnd(name);
  }
}
# Usage
benchmark([get_head_checkbox, get_head_checkbox2]);
benchmark([get_head_checkbox, get_head_checkbox2],10000);

# Function for benchmarking different code snippets (timing,testing,profiling)
# Includes percentages and sorted.
// function benchmark() {
//   // Get inputs
//   let   code_refs  = [...arguments];
//   let   iterations = 1;
//   const last_index = code_refs.length - 1;
//
//   // Check last input
//   if(typeof(code_refs[last_index]) == "number")
//     iterations = code_refs.pop();
//
//   // Check for tests
//   if(!code_refs.length)
//     return;
//
//   const stats = [];
//
//   // Get statistics
//   for(const code of code_refs){           // foreach loop in javascript
//     const t0 = performance.now();         // High precision time
//     for(let i = 1; i <= iterations; i++ ) // Run a specified amount of times
//       code();
//     const time = (performance.now()-t0).toFixed(2);
//     stats.push({name: _get_code_name(code), time: time});
//   }
//
//   // Sort statistics: fastest (lowest time) first
//   stats.sort((a,b) => (Number(a.time) >= Number(b.time)) ? 1 : -1);
//
//   // Baseline to compare with
//   const longest_time = stats[stats.length-1]["time"];
//
//   // Add percentage to each test set
//   for(const set of stats){
//     const time    = set.time;
//     const percent = ((longest_time-time)/time*100).toFixed(0);
//     set.percent = percent;
//   }
//
//   // Print statistics
//   console.table(stats);
// }
//
# Javascript function to convert a block of code to a name
// function _get_code_name(code) {
//   const name     = code.name;             // Code reference to name
//   let   toString = code.toString();       // Code reference to name
//
//   if(name)
//     return name;
//
//   const is_anon_function1_start = /^\s*function\(\)\s*{\s*/;    // function(){ code }
//   const is_anon_function1_end   = /\s*}$/;
//   const is_anon_function2_start = /^\s*\(\s*\)\s*=>\s*{\s*/;    // () => { code }
//   const is_anon_function2_end   = /\s*}$/;
//   const is_anon_function3_start = /^\s*\(\s*\)\s*=>\s*(?!{)/;   // () => code
//   const is_anon_function3_end   = /\s*$/;
//
//   if(toString.match(is_anon_function1_start)){        // function(){ code }
//     toString = toString
//     .replace(is_anon_function1_start, "")
//     .replace(is_anon_function1_end,   "");
//   }
//   else if(toString.match(is_anon_function2_start)){   // () => { code }
//     toString = toString
//     .replace(is_anon_function2_start, "")
//     .replace(is_anon_function2_end,   "");
//   }
//   else if(toString.match(is_anon_function3_start)){   // () => code
//     toString = toString
//     .replace(is_anon_function3_start, "")
//     .replace(is_anon_function3_end,   "");
//   }
//
//   return toString;
// }
//
# Usage
benchmark(myfunc, myfunc2);
benchmark(myfunc, myfunc2,10000);
benchmark(myfunc, function(){ $('#table .row :checkbox') }, () => { $('#id') },() => $('#id') ,1000)

cheats.txt  view on Meta::CPAN

#     eval => sub {
#         $data =~ s{ ( ^ \s* START .*? STOP \s* \n ) }{
#             local $_ = $1;
#             /skip/ ? "" : $_;
#         }xmsger,
#     },
# };
#
# cmpthese( 3_000_000, $ways);

# Interpolation vs concat comparison:
#
# No assignment.
perl -Me -e 'my $v = 123; n { interp => sub { "$v" }, concat => sub { $v } }, 10000000'
#
             Rate interp concat
interp  29411765/s     --   -91%
concat 333333333/s  1033%     --
#
# Full assigned.
perl -Me -e 'my $v = 123; n { interp => sub { my $c = "$v"}, concat => sub { my $c = $v } }, 10000000'
             Rate interp concat
interp 12195122/s     --   -68%
concat 38461538/s   215%     --
#
# Inside a sentence.
perl -Me -e 'my $v = 123; n { interp => sub { my $c = "I got $v dollars"}, concat => sub { my $c = "I got " . $v . " dollars" } }, 10000000'
             Rate interp concat
interp 14285714/s     --    -4%
concat 14925373/s     4%     --

# Interpolation vs concat vs comma comparison:
perl -Me -e 'my $v = 123; n { interp => sub { "I got $v dollars"}, concat => sub { "I got " . $v . " dollars" }, comma => sub{ "I got ", $v, " dollars" } }, 10000000'
             Rate interp concat  comma
interp 20408163/s     --    -2%   -57%
concat 20833333/s     2%     --   -56%
comma  47619048/s   133%   129%     --

# Remove duplicate characters.
perl -E '$_ = "abbbc"; s/(.)\g1+/$1/; say'
abc
perl -E '$_ = "abbbc"; tr///cs; say'
abc

# Remove duplicate characters (benchmark).
perl -Me -e '
    $copy = "abbc";
    n {
        s => sub{
            local $_ = $copy;
            s/(.)\g1+/$1/;
            $_;
        },
        tr => sub{
            local $_ = $copy;
            tr///cs;
            $_;
        }
    }, 1000000
'
            (warning: too few iterations for a reliable count)
        Rate    s   tr
s  1408451/s   -- -70%
tr 4761905/s 238%   --

# Comparing different ways in perl to combine hashes.
#
# Each: 2.6s
while ( my ($key,$val) = each %users_one ) {
    $users{$key} = $val;
}
#
# Merge: 1.7s
%users = ( %users, %users_one);
#
# Slice: 700ms
@users{keys %users_one} = values %users_one;

# Benchmark glob() vs -e() functions
perl -Me -e '
    n {
        e_found                  => sub{ -e "recursive.pl" },
        e_not_found              => sub{ -e "recursive2.pl" },
        glob_found               => sub{ glob "recursive.pl" },
        glob_not_found           => sub{ glob "recursive2.pl" },
        glob_wild_flag_found     => sub{ glob "rec*.pl" },
        glob_wild_flag_not_found => sub{ glob "rec2*.pl" },
    }, 1_000_000
'
                              Rate glob_wild_flag_not_found glob_wild_flag_found glob_found glob_not_found e_found e_not_found
glob_wild_flag_not_found   79491/s                       --                 -45%       -94%           -95%    -96%        -98%
glob_wild_flag_found      143885/s                      81%                   --       -90%           -91%    -93%        -96%
glob_found               1408451/s                    1672%                 879%         --           -15%    -35%        -56%
glob_not_found           1666667/s                    1997%                1058%        18%             --    -23%        -48%
e_found                  2173913/s                    2635%                1411%        54%            30%      --        -33%
e_not_found              3225806/s                    3958%                2142%       129%            94%     48%          --


#############################################################
## Perl Binary
#############################################################

# Convert to binary using recursion (POC,perl).
sub binary{
    my($n) = @_;
    $n //= $_;
    return $n if $n == 0 or $n == 1;
    my $k = int($n/2);
    my $b = $n % 2;
    binary($k) . $b;
}
for(1..40){
    say "$_ ", binary;
}
__END__
1 1
2 10
3 11
4 100
5 101
6 110



( run in 0.415 second using v1.01-cache-2.11-cpan-5511b514fd6 )