App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

# 1.o | 5.o 4.o 3.o 2.o

# Update a member of an archive of if a newer file exists
ar -ruv libMy.a 1.o

# Alternate syntax to link to an archive library
-lABC          # looks for libABC.so, then for libABC.a
-l:libABC.a    # Looks for libABC.a (more explicit, but simplier)


#############################################################
## C,CPP - String
#############################################################

# Convert anything to a string in cpp using string streams (DWORD,int)
#include <string>
#include <sstream>
if(it->GetName() == L"MyProg.exe"){
	std::stringstream ss;
	ss << "taskkill /T /F /PID " << it->GetPID();
	std::string command = ss.str();
	system(command.c_str());
}

# String comparison breakpoint in Visual studio
strcmp(static_cast<const char *>(name),"place_absolute")==0

// In cpp split a string by a delimeter and put the contents into a map (or vector)
std::map<std::string, int> map_column_names;
std::istringstream ss(default_columns);
std::string token;
while (std::getline(ss, token, ',')) {
	map_column_names[token] = 1;
}

# Convert a float to an integer in cpp.
int myInt = static_cast<int>(myFloat);

# Check if a string is NOT found in a vector in cpp
# This returns a bool (true if present, false otherwise)
#
if ( std::find(vec.begin(), vec.end(), item) == vec.end() )
   do_this();
else
   do_that();

# Cpp double to string conversion
std::string makeTime = std::to_string(time_span.count());

# Cpp uses floor() to get the integer part of a float.
# like int() in perl.
# ceil() returns the smallest integer, but rounding up.
#
# ceil did not for so used this instead:
int total_pages = (amount + tool_limit - 1) / tool_limit;

# Cpp std::string for const char *
string myStr;
myStr.c_str();

# Raw string in CPP. Do not need to escape characters.
# R"ABC(TEXT)ABC";
#
R"sql(CREATE TABLE IF NOT EXISTS version (
	version INTEGER
);)sql"


#############################################################
## C,CPP - Templates
#############################################################

# Function Template example in Cpp
// Make a generic to_string function to convert anything to a string
//
#include <string>
#include <sstream>
//
template <typename T>
std::string to_string (T data) {
	std::stringstream ss;
	ss << data;
	return ss.str();
}


#############################################################
## C,CPP - Threads
#############################################################

# Get the current thread's name (like thread ID, tid)
QThread::currentThread()->objectName()


#############################################################
## C,CPP - Timer
#############################################################

# Timer in Cpp
#
#include <ctime>
#include <chrono>
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
// run something
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::milliseconds rawTime = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::string stringTime = std::to_string(rawTime.count());

# Timer in Cpp (simpler)
#
#include <ctime>
#include <chrono>
//
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
//
auto t1 = Time::now();
auto t2 = Time::now();
std::string runTime = std::to_string(std::chrono::duration_cast<ms>(t2 - t1).count());

# Timer in Cpp (as a function)

cheats.txt  view on Meta::CPAN

## Linux Commands - ssh-agent
#############################################################

# Add ssh agent
eval `ssh-agent -s`
ssh-add

# Kill agent
ssh-agent -k


#############################################################
## Linux Commands - ssh-keygen
#############################################################

# Setup new machine: key for quick access
# Use a longer key with ssh public keys
ssh-keygen -t rsa -b 4096
cd ~/.ssh/
cat id_rsa.pub >> authorized_keys

# Generate ssh key with more details
ssh-keygen -t rsa -b 4096 -C timofey.potapov@otrs.com -f id_rsa_OTRS_SAAS_$(date +%F)
# -C COMMENT
# -f Specific file to use
# -b Specific encryption bit size

# Problem: Host key differs from IP address
# Fix:     Remove offending ssh key ECDSA.
ssh-keygen -R 10..181.54

# Remove offending key for a host and port name
ssh-keygen -f "$HOME/.ssh/known_hosts" -R "host:port"
ssh-keygen -f "$HOME/.ssh/known_hosts" -R "[localhost]:2222"


#############################################################
## Linux Commands - sort
#############################################################

# Sort ignoring case (Bash)
sort -f
ls -1d [Ee]* | sort -f


#############################################################
## Linux Commands - stat
#############################################################

# View the number of hard links to a file or folder
stat -c %h /run

# View the group id (GID) of a file.
stat -c %g ~/.vimrc


#############################################################
## Linux Commands - stty
#############################################################

# View the control character escapes
stty -a

# Fix terminal after doing a hard exit in a script (control-C).
reset
tset
stty echo


#############################################################
## Linux Commands - systemctl
#############################################################

# Autostart linux service at boot
sudo systemctl enable elasticsearch.service

# Reload fstab without reboot
systemctl daemon-reload

# Run a user server (not system wide)
mkdir ~/.config/systemd/user/defaults.target.wants
cd ~/.config/systemd/user
vi selenium.service
#
# Add to file:
+ [Unit]
+ Description=Selenium Server
+
+ [Service]
+ Environment=DISPLAY=:1   # should match echo $DISPLAY
+ ExecStart=/usr/bin/java -Dwebdriver.chrome.driver=/usr/bin/chromedriver -jar /usr/local/lib/selenium/current.jar -role standalone -debug
+ SuccessExitStatus=143
+
+ [Install]
+ WantedBy=default.target
#
# Reload services
systemctl --user daemon-reload
#
# Restart user service
systemctl --user start selenium.service

# Workaround for not being able to set selenium service
# environmental dynamically.
# Add to ~/.profile
#
+ # Workaround: Update DISPLAY variable in selenium.service file
+ export SELENIUM_SERVICE_FILE=/etc/systemd/system/selenium.service
+ if [ -e "$SELENIUM_SERVICE_FILE" ]; then
+    if [ $(grep "Environment=DISPLAY=$DISPLAY" $SELENIUM_SERVICE_FILE -c) -eq 0 ]; then
+       sudo perl -i -lpe 's/ ^ Environment=DISPLAY= \K .* /$ENV{DISPLAY}/x' $SELENIUM_SERVICE_FILE
+       sudo systemctl daemon-reload
+       sudo systemctl stop selenium.service
+       sudo systemctl start selenium.service
+       echo "Updated DISPLAY in $SELENIUM_SERVICE_FILE"
+    fi
+ fi


#############################################################
## Linux Commands - su

cheats.txt  view on Meta::CPAN

# Minimize the window for a few seconds, then restore it (Putty,xterm)
echo -e '\e[2t' && sleep 2 && echo -e '\e[1t'

# Move the window to the top/left corner of the display (Putty,xterm)
echo -e '\e[3;0;0t'

# Zoom the window (Putty,xterm)
echo -e '\e[9;1t'

# Bring the window to the front (without changing keyboard focus) (Putty,xterm)
echo -e '\e[5t'

 Change the name of an xterm window to "string"
echo -ne "\033]2;string\007"

# Change the name of an xterm icon to "string"
echo -ne "\033]1;string\007"

# Change the name of an xterm icon and window to "string"
echo -ne "\033]0;string\007"

# Create alias to easily change the window name and icon name
# Must be run together!
set_title(){ echo -ne "\033]0;$@\007"; }
alias title='set_title'

# Get dimensions/size of a screen/xterm
xdpyinfo | grep dimensions
xrandr | grep '*'

# Get the size of an xterm window
xwininfo

# Get info about current xterm window
xdpyinfo

# Get size info of a named xterm window
xwininfo -name omsGUI_0_3

# Get info about an xterm window
xprop -id <window_id>
xprop -id 0x2400022

# Get position of the cursor
perl -e '$/ = "R";' -e 'print "\033[6n";my $x=<STDIN>;my($n, $m)=$x=~m/(\d+)\;(\d+)/;print "Current position: $m, $n\n";'

# Print how many columns and rows an xterm window uses for its screen size
tput cols
tput lines
reset

# Change fond/colors of an xterm window
RESTORE='\033[0m'
RED='\033[00;31m'
GREEN='\033[00;32m'
YELLOW='\033[00;33m'
VIOLET='\033[00;35m'
TEAL='\033[00;36m'
GREY='\033[00;37m'

# View color ansi escapes with less (like Vim)
less -R file

# Make xterm text color bold
BOLD='\033[1m'

# Make xterm text color blink
BLINK='\033[5m'

# Move mouse to a specific location on the screen/xterm window (on lnxbr42)
xdotool mousemove 764 11

# Click on a button (cannot on top bar , like the X for close)
xdotool click 1

# Get mouse location
xdotool getmouselocation

# Move mouse to a location and click at the same time
xdotool mousemove 1747 30 click 1

# print contents of X events (mouse activity/movement)
xev

# Install xdotool dependencies
sudo apt-get install libxcb-xtest0:i386 libxcb-xtest0-dbg:i386 libxcb-xtest0-dev:i386
dpkg -l | grep xtest

# Other xdotool dependenacies
sudo aptitude install

# install xdotool from repository
cd ~junk/xdo/xdotool-master
sudo make install

# Check dependencies of a debian package
dpkg -I xdotool_3.20160512.1-1_i386.deb

# Install package from source (.deb)
sudo dpkg -i xdotool_3.20160512.1-1_i386.deb
sudo apt-get install -f

# Launch an xterm window into a certain directory
xterm -e 'cd ~/dsu && /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu && /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu; /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu; bash'

# Check if xterm environment is working (Added: 2017-11-02 03:56:18 PM)
xeyes

# Check what kind of terminal I am using (xterm,bench)
echo $TERM

# Wrap long lines unto next row in bash/linux
# Exclose PS1 in '\[PS1_VALUE\]'

# Function which run on each prompt.
PROMPT_COMMAND=__prompt_command
__prompt_command ()
{

cheats.txt  view on Meta::CPAN

for n in "${a[*]}"; do echo $n; done
one two three four

# Loop through array ($* $@)
for n in "${a[@]}"; do echo "$n"; done
one
two
three four

# Copy one array in bash to another array
b=("${a[@]}")

# Get size of an array (bash,var)
size=${#array[@]}

# Delete first or last element from an array (bash,shift,var)
unset array[0]
unset array[-1]

# Loop through array input ($* $@)
for n in "$@"; do echo "[$n]"; done

# Add to an associative array/hash in bash
h[a b c]="abc val"
h[d e f]="def val"
h[x y z]="xyz val"

# Print an associative array/hash in bash
echo ${h[@]}
echo ${h[*]}

# Check if associative array/hash in bash is set.
if [[ -z ${h[abc]} ]]; then
    echo yup
fi

# Bash var sublty (bug 1). Unset array is missing instead of empty
a=(one two "three four" "five")
print_args "${a[@]}"
print_args "${a[@]}" 5
unset b
print_args "${b[@]}" 5
print_args "${b}" 5

# Bash provide default if undef or empty.
unset v1
v2=""
v3="data"
echo "A${v1:- }B"
echo "A${v2:- }B"
echo "A${v3:- }B"

# Trick/hack to prevent work sptting when assigning the output
# of a bash function to an array.
unset v; IFS=$'\n' read -r -d '' -a v < <(_build_AND_regex); declare -p v
#
# IFS=$'\n': This sets the Internal Field Separator (IFS) to newline (\n).
    This ensures that spaces in the output of _my_function won't cause
    word splitting.
# read -r -d '' -a v: This command reads input into the array variable v.
# -r: Prevents backslash escapes from being interpreted.
# -d '': Delimiter option set to an empty string. This ensures that
    read reads until it encounters a null byte (this effectively
    reads the whole output as a single line).
# -a v: Assigns the input to the array variable v.
# < <(_my_function): This redirects the output of _my_function to the
    read command.


#############################################################
## Bash - Ascii Art
#############################################################

# Ascii Art
figlet "svn update"

# Nice format for representing binary numbers (art,ascii)
figlet "0000011111" -f digital

# Show all available figlest fonts (ascii art)
figlist | perl -lne '$a=/\bfonts.*:$/ ... /.*:/; print if $a > 1 and $a !~ /E/'
# There are the nicer fonts
banner big lean slant smslant standard
# favorite
slant
figlet "svn update" -f slant

# Center the ascii art (justify)
figlet "svn update" -f slant -c

# Right justify the ascii art and set a width of 60
figlet "svn update" -f slant -r -w 60


#############################################################
## Bash - Autocomplete
#############################################################

# Example of using autocompletion (tab)
/usr/share/bash-completion/completions/perltidy
/usr/share/bash-completion/completions/perl
/usr/share/bash-completion/completions/ip

# Generate autocompletion for own scripts (Bash,Tab)
# Options - aaa aba bbb ccc
_sb_tab(){
   COMPREPLY=( $(compgen -W "`sb info`" -- "${COMP_WORDS[COMP_CWORD]}") )
}
complete -F _sb_tab sb

# Colon should not be a word break in perl.
export COMP_WORDBREAKS=${COMP_WORDBREAKS//:}

# View all tab completions (Bash,Tab,auto)
complete

# Delete all tab completions (Bash,Tab,auto)
complete -r

# Use existing autocompletions
complete -p | grep ls      # finds _longopt

cheats.txt  view on Meta::CPAN

+     no strict 'refs';
+
+     for my $func (sort keys %{"${pkg}::"}) {
+         my $code = ${"${pkg}::"}{$func}->*{CODE};
+         next if not $code;
+
+         ${"${pkg}::"}{$func}->** = sub {
+             say "-> $pkg\::$func";
+             &$code;
+         }
+     }
+   }
+ }
+
+
+ 1

# Subs::Trace use case (example)
perl -I. -E '{ package P; use Subs::Trace; sub F1{10} sub F2{20} } say P::F1() + P::F2()'

# Subs::Trace cpan modules.
cpanm Subs::Trace
perl -E '{ package P; sub F1{10} sub F2{20} sub F4{40} use Subs::Trace; sub F3{30} } say P::F1() + P::F2() + P::F3() + P::F4()'
-> P::F1
-> P::F2
-> P::F4
100


#############################################################
## Perl Modules - Template (Toolkit,tt)
#############################################################

# Concatenation operator in template tookkit (tt)
Data.var1 _ Data.var2

# Compare |html and |uri:
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | html %]"), { id => "has & and spaces" }, \$out); say $out'
has &amp; and spaces
#
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | uri %]"), { id => "has & and spaces" }, \$out); say $out'
has%20%26%20and%20spaces


#############################################################
## Perl Modules - Term::Animation
#############################################################

# Using a terminal animation framework
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(2); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1); while(1){ $anim->animate; my $in = getch(); last if $in eq...

# Using a terminal animation framework (with colors)
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(1); $anim->color(1); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1, default_color => "yellow"); while(1){ $ani...


#############################################################
## Perl Modules - Term::ANSIColor
#############################################################

# Proper way to color text in perl instead of hardcoding
# escape codes (which are not all the same on all devices).
perl -MTerm::ANSIColor -E 'say colored ($_,$_) for qw( RED YELLOW GREEN ON_BRIGHT_BLACK )'

# Color an remote color (uncolor).
perl -MTerm::ANSIColor=colored,colorstrip -E 'say length colorstrip(colored("HEY", "YELLOW"))'
3


#############################################################
## Perl Modules - Term::ProgressBar
#############################################################

# Progress bar example 1
perl -Mojo -MTerm::ProgressBar -CO -E "STDOUT->autoflush(1); my $ua = Mojo::UserAgent->new; $ua->on(prepare => sub($ua,$tx){ my($len,$bar); $tx->res->on(progress => sub($res){ return unless $len ||= $res->headers->content_length; my $prog = $res->con...

# Progress Bar example 2
perl -MTerm::ProgressBar -E "$|++; @a=1..100; $bar = Term::ProgressBar->new({count => ~~@a}); $bar->update($_), select undef,undef,undef,0.05 for @a"
GetTerminalSize
# Progress Bar in Perl (more features shown here)
perl -MTerm::ProgressBar -E "$|++; $max=100_000; $progress = Term::ProgressBar->new({count => $max, name => 'File-1', term_width => 50, remove => 1}); $progress->minor(0); my $next_update = 0; for (0..$max){ my $is_power = 0; for (my $i = 0; 2**$i <=...


#############################################################
## Perl Modules - Term::ReadKey
#############################################################

# Get terminal width in perl
perl -MTerm::ReadKey= -E "my ($w) = GetTerminalSize(); say $w"

# Read input from the keyword/user without showing the password
perl -MTerm::ReadKey -le 'ReadMode(2); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(0); print "Got [$pass]"'

# Read input from the keyword/user without showing the password (same, but using keywords)
perl -MTerm::ReadKey -le 'ReadMode(noecho); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(restore); print "Got [$pass]"'
perl -MTerm::ReadKey -e 'ReadMode(2); while($c=ReadKey(0), ord($c) !~ /^(?:10|13)$/x){ $pass .= $c  } ReadMode(0); print "[$pass]\n"'

# Read input from the keyword/user without showing the password (same, but more compact)
perl -MTerm::ReadKey -le 'ReadMode(2); $pass = ReadLine(0); chomp $pass; ReadMode(0); print "Got [$pass]"'
perl -MTerm::ReadKey -le 'ReadMode(2); $_ = ReadLine(0); chomp; ReadMode(0); print "[$_]"'

# Read input from the keyword/user without showing the password (same, but on windows)
perl -MTerm::ReadKey -le "ReadMode 2; $pass = ReadLine 0; chomp $pass; ReadMode 0; print qq([$pass])"

# Read input from the keyword/user without showing the password. replace characters with a star "*"
perl -MTerm::ReadKey -e 'ReadMode(4); while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode(0); print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 3; while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode 0; print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 4; while($c=ReadKey(0),$o=ord($c),$o!=10){ if($o==127 or $o==8){chop $p; print "\b \b"}elsif($o < 32){}else{$p.=$c; print "*"}} ReadMode 0; print "[$p]\n"'


#############################################################
## Perl Modules - Term::ReadLine::Gnu
#############################################################

# Given input, return the possible completion words.
# Like compgen.
compgen -W "cat cake bat bake" -- c
perl -MTerm::ReadLine -E 'my $term = Term::ReadLine->new("my"); my $attribs = $term->Attribs; $attribs->{completion_word} = [qw( cat cake bat bake )]; my @matches = $term->completion_matches( shift//"", $attribs->{list_completion_function} ); $term->...


#############################################################
## Perl Modules - Text::CSV

cheats.txt  view on Meta::CPAN

# YCM does not seem to work on android.
# Use COC instead.


#############################################################
## Vim Other
#############################################################

# Join lines (Vim)
J

# Repeat last text-changing command (Vim)
.

# Undo last change (Vim)
u

# Undo all changes to line (Vim)
U

# Redo last command (Vim)
<Control> + r

# Diplay file name, number of lines (and percent) (Vim)
<Control> + g

# Type a control character in Vim
Control-V <RET>

# Convert binary to hex (Vim)
:%!xxd

# Comment a block of lines (Vim)
<Control> + v
# Scroll down with arrow keys
<Shift> + i
# Change first line to have a comment
ESC
# all other lines will have same change (comments added)

# Scroll down half a page (Vim)
<Control> + D

# Scroll up half a page (Vim)
<Control> + U

# Find documentaion for a lookahead (Vim)
:h \@

# View Vim variables (Vim)
:set

# History is not working (Vim)
# Check permissions of ~/.viminfo

# View man page (Vim,help)
:h

# Search for spaces (Vim)
/\s\+
# \+ since all are taken literally unless escaped

# If accidentally pressed <Control> + s (Vim)
# that will freeze the terminal. This is due to  "flow control"
# Do this to undo the effect:
<Control> + q
#
# To permanently disable this from occurring put this in .bashrc
stty -ixon

# Stop all output to terminal/xterm (Vim)
<Control> + s

# Restart output to terminal/xterm (Vim)
<Control> + q

# ERROR: the command is not available in this version (Vim)
sudo apt-get install vim

# Compare files (Vim)
vimdiff    file1 file2           # vertical split
vimdiff -o file1 file2           # horizontal split

# Open multiple files in split screens (Vim(
vim -O file1 file2               # vertical split
vim -o file1 file2               # horizontal split

# View history of searches (Vim)
q/

# View history of commands (Vim)
q:

# Open stream from STDIN (Vim)
echo "abc" | vi -


#############################################################
## Visual Basic Script (.vbs)
#############################################################

# Remove RSIGaurd process (.vbs)
Dim strComputer
DIm objWMIService
Dim colProcessList
Dim objProcess
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'RSIGuard.exe'")
For Each objProcess in colProcessList
   objProcess.Terminate()
Next
#
# Same with perl
perl -e "kill -9,`tasklist`=~/RSIGuard\D+(\d+)/g"

# Convert .msg files to .txt files (extract text from outlook, .vbs)
Set ol  = CreateObject("Outlook.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
inputString = "S:\controls\cert\<USER>\msg"
REM inputString = InputBox("Enter the full path to the .msg folder: ")



( run in 1.627 second using v1.01-cache-2.11-cpan-97f6503c9c8 )