Saturday, December 2, 2023

Friday, November 10, 2023

Vim search for the escaped string of a line


command! -nargs=1 SH let @/ = '\V'.escape(<q-args>, '\')|set hlsearch

nnoremap <C-y> _vg_y<Esc>:SH <C-r>"<CR>


_    go to first non-space character in line

g_   go to last non-space character in line

v    start visual selection

y     copy selection

<C-r>" paste copied selection 

Saturday, August 26, 2023

Fuzzy Finder FZF with Syntax Highlight Preview

FZF is nice cli program that allow quick file navigation that find files as you type.

BAT is nice replacement for cat with highlight features

sudo apt install fzf

sudo apt install bat

Using fzf together with batcat to source code files and preview it with syntax highlight

fzf --preview 'batcat --style=numbers --color=always --line-range :500 {}'


.bashrc

source /usr/share/doc/fzf/examples/key-bindings.bash


if type rg &> /dev/null; then

  export FZF_DEFAULT_COMMAND='rg --files'

  export FZF_DEFAULT_OPTS='-m --height 50% --border'

fi


alias findz="fzf --preview 'batcat --style=numbers --color=always --line-range :500 {}'"


_fzf_comprun() {

  local command=$1

  shift


  case "$command" in

    cd)           fzf --preview 'tree -C {} | head -200'   "$@" ;;

    export|unset) fzf --preview "eval 'echo \$'{}"         "$@" ;;

    ssh)          fzf --preview 'dig {}'                   "$@" ;;

    *)            fzf --preview 'batcat -n --color=always {}' "$@" ;;

  esac

}

export FZF_CTRL_R_OPTS="

  --preview 'echo {}' --preview-window up:3:hidden:wrap

  --bind 'ctrl-/:toggle-preview'

  --bind 'ctrl-y:execute-silent(echo -n {2..} | pbcopy)+abort'

  --color header:italic

  --header 'Press CTRL-Y to copy command into clipboard'"


export FZF_ALT_C_OPTS="--preview 'tree -C {}'"


Usage:

vim $(fzf)

Ctrl+R   # open command history

Alt+C   # show directories and cd to it

Vim **<tab>  #open file list and open with vim

cd **<tab> # open directory list and cd to it


(fzf.vim) .vimrc

command! -bang -nargs=* Rg call fzf#vim#grep("rg --column --line-number --no-heading --color=always --smart-case ".shellescape(<q-args>), 1, {'options': '--delimiter : --nth 4..'}, <bang>0)

set grepprg=rg\ --vimgrep\ --smart-case\ --follow

command! -bang -nargs=? -complete=dir Files

    \ call fzf#vim#files(<q-args>, {'options': ['--layout=reverse', '--info=inline', '--preview', '~/.vim/bundle/fzf.vim/bin/preview.sh {}']}, <bang>0)

"Open Files in the bottom

"let g:fzf_layout = { 'up':  '40%'}

"let g:fzf_layout = { 'down':  '40%'}

Monday, October 17, 2022

Show a vertical column markers in vim (very usefull to check identation)

To show a background line in the whole column 9 and 17

:set colorcolumn=9,17
or short
:set cc=9,17

To change the color to blue
:highlight ColorColumn ctermbg=blue


show line in the cursor column
exe 'set cc='.col('.')
Source: https://superuser.com/questions/249779/how-to-setup-a-line-length-marker-in-vim-gvim

Friday, July 1, 2022

Vim find and repeat search

 For example,

use

f<space>  to go to the next space

; to repeat search and go to the othe next space;


f(  find next (

;;;  go to the fourth ( 

XPRA

 https://xpra.org/

XPRA is a screen for graphical x window apps.

Friday, September 3, 2021

Create diagram images from text commands


https://plantuml.com/ + https://pandoc.org/ (other similar tools)

 https://graphviz.org/doc/info/command.html

Ex: echo 'digraph { a -> b }' | dot -Tsvg > output.svg

echo 'digraph { a -> b }' | dot -Tsvg -Gfontcolor=red -Glabel="My favorite letters"

Saturday, August 28, 2021

Linux command line navigation

Ctrl + a    

Go to the beginning of the line

Ctrl + e

Go to the end of the line

Ctrl + f    

Move cursor on character forward 

Ctrl + b

Move cursor on character backward

Alt + f

Move cursor one word forward

Alt + b

Move cursor one word backward

Ctrl + xx

Go to the beginning of the line and back to current position

Ctrl + u

Deletes the whole line of the text

Ctrl + d

Deletes character under cursor

Alt + d

Delete all characters after the cursor


Saturday, August 14, 2021

Learning about how to build a computer

 https://nandgame.com/

https://www.nand2tetris.org/

Saturday, June 19, 2021

Saturday, May 29, 2021

XV6 - Very Simple Unix implementation for educational purposes from MIT

In linux terminal 1

$ sudo apt-get install qemu-kvm qemu virt-manager virt-viewer
$ git clone git@github.com:mit-pdos/xv6-public.git
$ cd xv6-public
$ make
$ make qemu
$ make qemu-nox-gdb

In linux terminal 2

$ gdb kernel
> target remote localhost:26000
> b exec
> c
> file _cat
> b main
> c

In linux terminal 1

$ cat README

look gdb stoped in breakpoint in terminal 2

Thursday, May 27, 2021

Copy and paste Shortcuts

Linux

COPY

To copy you may have different scenarios

  • Mode 1
    • In graphical applications you may use Ctrl + C
    • In terminal you may use Ctr + Shift + C
    • Right click menu Copy
  • Mode 2
    • In any application you can just select a text

Monday, May 17, 2021

Gerar gráfico atualizado da cotação do dólar turismo no Google Sheets.


Importar tabela de variação em Real do Dólar Turismo de diversas casas de Cambio em São Paulo

Por exemplo na célula A1 colocar a fórmula (isso irá importar um array de valores em formato ["5.10",".."])
=IMPORTXML("https://www.melhorcambio.com/dolar_hoje/get_turismo.php?idmoeda=8&idcidade=2&periodo=2m","//body")

Para distribuir os valores em varias linha e então poder utilizar para plotar um gráfico

Na célula A2 colocar a fórmula
=TRANSPOSE(SPLIT(REGEXREPLACE(A1, "[\[\]""]",""),","))

Para obter somente o valor atual do dólar turismo utilizar a fórmula
=IMPORTXML("https://www.melhorcambio.com/cotacao/compra/dolar-turismo/sao-paulo","//h3/span")

Wednesday, March 31, 2021

C/C++ manpages quick access from VIM

Vim has by default a helpful shortcut to open the man page of the word under cursor, Shift + k, (or captital K), but very frequently we have shell commands with the same name of a C function, and for example

man printf actually opens the man page for the command, not the C function, but

man 3 printf opens the man pages of the C function, so to open this same man page in Vim, you need to use Shift + 3k (3K)

and for example readlink C function it's man 2 readlink, so in Vim it is Shift + 2k (2K)

Install C++ man pages libstdc++-10-doc


Wednesday, March 10, 2021

gdb print wchar_t *

wchar.gdb

define wchar_print 
        echo "

        set $i = 0
        while (1 == 1)
            set $c = (char)(($arg0)[$i++])
            if ($c == '\0')
                loop_break
            end
            printf "%c", $c
        end

        echo "\n
end


$ gdb -x wchar.gdb  ./myprogram
> wchar_print  mywidevar

or with modern gdb

> set target-wide-charset UTF-16
> p (wchar_t*) mywidevar


Source: https://www.generacodice.com/en/articolo/370005/How-can-I-display-Unicode-strings-while-debugging-on-linux

Monday, March 1, 2021

(Debug) GDB with full colored dashboard

$ pip install pygments

$ wget -P ~ https://git.io/.gdbinit

If gdb version prior to 7.7 and python prior to 2.7 execute this

$ mkdir -p ~/.gdbinit.d/
$ wget 'https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=blob_plain;f=gdb/python/lib/gdb/FrameDecorator.py' -O ~/.gdbinit.d/FrameDecorator.py
$ sed -i '1s/^/python gdb.COMPLETE_EXPRESSION = gdb.COMPLETE_SYMBOL\n/' .gdbinit
$ sed -i "s/gdb_breakpoint.temporary/None/g" .gdbinit

$ cat >>~/.gdbinit <<EOF
python

import imp
gdb.FrameDecorator = imp.new_module('FrameDecorator')
gdb.FrameDecorator.FrameDecorator = FrameDecorator
end
EOF

You can also send module to be shown on different terminals

start gdb 

$ gdb my_program

in another terminal

$ tty
> /dev/pts/3

in gdb to move Registers to this other terminal 

> dashboard breakpoints -output /dev/pts/3
> dashboard variables -output /dev/pts/3
> dashboard -layout variables stack source breakpoints

to Get help 

>>> help dashboard

Wednesday, February 24, 2021

Testing keyboard keys

Online in browser
https://keycode.info/

On Windows
install
https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/ 
and use spy++ that comes with it

On Linux
$ xev


Creating your own Windows Keyboard testing application  copy paste this code and
       
       
#include <iostream> 
#include <windows.h> 
#include <winuser.h>

#pragma comment(lib,"user32.lib")  //Use this line to get compiled on Visual Studio Code quick

using namespace std;

int Record (int key_stroke, char *file);
void Hide();

int main() {
 //   Hide();
    char i;

    while (1) {
        for(i = 8; i <= 190; i++) {
            if (GetAsyncKeyState(i) == -32767)
                Record(i, "keys.log");
        }
    }
    system("pause");
    return 0;
}


int Record (int key_stroke, char *file) {
    if ((key_stroke == 1) || (key_stroke == 2))
        return 0;

    FILE * OUTPUT_FILE;
    OUTPUT_FILE = fopen(file, "a+");

    cout << key_stroke << endl;

    if (key_stroke == 13) fprintf(OUTPUT_FILE, "%s", "\n");
    else if (key_stroke == 32) fprintf(OUTPUT_FILE, "%s", " ");
    else if (key_stroke == 190 || key_stroke == 110)  fprintf(OUTPUT_FILE, "%s", ".");
    else if (key_stroke == 8)          fprintf(OUTPUT_FILE, "%s", "BACKSPACE");
    else if (key_stroke == VK_TAB)     fprintf(OUTPUT_FILE, "%s", "TAB");
    else if (key_stroke == VK_SHIFT)   fprintf(OUTPUT_FILE, "%s", "SHIFT");
    else if (key_stroke == VK_CONTROL) fprintf(OUTPUT_FILE, "%s", "CTRL");
    else if (key_stroke == VK_ESCAPE)  fprintf(OUTPUT_FILE, "%s", "ESC");
    else if (key_stroke == VK_END)     fprintf(OUTPUT_FILE, "%s", "END");
    else if (key_stroke == VK_HOME)    fprintf(OUTPUT_FILE, "%s", "HOME");
    else if (key_stroke == VK_LEFT)    fprintf(OUTPUT_FILE, "%s", "LEFT");
    else if (key_stroke == VK_UP)      fprintf(OUTPUT_FILE, "%s", "UP");
    else if (key_stroke == VK_RIGHT)   fprintf(OUTPUT_FILE, "%s", "RIGHT");
    else if (key_stroke == VK_DOWN)    fprintf(OUTPUT_FILE, "%s", "DOWN");
    else fprintf (OUTPUT_FILE, "%s", &key_stroke);

    fclose(OUTPUT_FILE);
    return 0;
}


void Hide() {
    HWND HiddenWindow;
    AllocConsole();
    HiddenWindow = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(HiddenWindow, 0);
}
       
              
 
To Compile it in Visual Studio Code Follow the instruction in the website bellow https://code.visualstudio.com/docs/cpp/config-msvc 

Open Developer Command Prompt for VS 2017 start VS Code from it code . 
create
       
 
  task.json
  {
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "cl.exe build active file",
            "command": "cl.exe",
            "args": [
                "/Zi",
                "/EHsc",
                "/Fe:",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "${file}"
            ],
            "problemMatcher": [
                "$msCompile"
            ],
            "group": "build"
        },
        {
            "type": "cppbuild",
            "label": "C/C++: cl.exe build active file",
            "command": "cl.exe",
            "args": [
                "/Zi",
                "/EHsc",
                "/nologo",
                "/Fe:",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "${file}"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$msCompile"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ]
}             
 
       
 
  create launch.json
  
  {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "cl.exe build and debug active file",
        "type": "cppvsdbg",
        "request": "launch",
        "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "preLaunchTask": "cl.exe build active file"
      }
    ]
  }
              
 

Tuesday, February 9, 2021

Open an Online Development Enviroment in a container with the git repository code

https://www.gitpod.io/


Open your browser with addres like this

gitpod.io/#type_here_the_git(hub/lab/bitbucket)url

...............................................
https://codeanywhere.com/

...............................................
https://azure.microsoft.com/pt-br/services/visual-studio-online/
...............................................

https://codesandbox.io/
...............................................

https://online.visualstudio.com/
...............................................

https://analyticsindiamag.com/top-8-alternatives-of-github-codespaces/
...............................................

github1s

for example to access this repo inside Visual Studio Editor
https://github.com/Spiderpig86/Cirrus.
replace github.com by github1s.com
https://github1s.com/Spiderpig86/Cirrus.


For arduino 
https://codebender.cc/


Tuesday, January 26, 2021

Vagrant - Start a VirtualBox Machine as easy as using a docker image

In this example we will download a Windows VM image from Peru repository and run it in the Virtual Box on Linux host machine

Download vagrant
$ wget https://releases.hashicorp.com/vagrant/2.2.14/vagrant_2.2.14_linux_amd64.zip

Unzip it
$ unzip vagrant_2.2.14_linux_amd64.zip

Install Virtual Box if you don't have it yet
$ sudo apt install virtualbox



Create a directory where you Valgrant file will be created
$ mkdir windows-server-2019-standard-x64-eval 
$ cd windows-server-2019-standard-x64-eval 

Download the image
$ vagrant init peru/windows-server-2019-standard-x64-eval

Start it up
$ VAGRANT_DEFAULT_PROVIDER=virtualbox vagrant up


Source: https://medium.com/notonlycss/how-to-run-a-windows-machine-on-mac-913c28ded1a3

Friday, October 30, 2020

Change command prompt color on windows

 color /?


color a    - changes the color to green

Draw diagrams online for free

Draw.io online

 https://app.diagrams.net/

Sunday, October 4, 2020

Sunday, September 27, 2020

Coin Change Problem

 #include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

// recursive

int count(vector<int> &coins, int m, int n) {

    if (n == 0) 

        return 1;

    if (n < 0)

        return 0;

     if (m <= 0 && n >= 1)

        return 0;

    return count(coins, m-1, n) + count(coins, m, n-coins[m-1]);

}

// recursive with memoization

unsigned long dp[51][251];// global array initialized to 0 

unsigned long countDP1(vector<int> & coins,  int i, int n)

{

    if(n == 0)

        return 1; //no coins

    if(n < 0) 

        return 0; //no negative money      

    if(i == coins.size()) //no more options of coins

        return 0;

    if(dp[i][n]!=0)

        return dp[i][n];

        //leave it or take it

    return dp[i][n] = countDP1(coins,i+1, n) + countDP1(coins,i, n-coins[i]);

}


//loop with 2D memoization space O(n*m) time O(n*m)

unsigned long countDP2(vector<int> &coins, int m, int n ) 

    int i, j; 

    unsigned long table[n + 1][m],  x, y; 

    for (i = 0; i < m; i++) 

          table[0][i] = 1;  

     for (i = 1; i < n + 1; i++) 

    { 

        for (j = 0; j < m; j++) 

        { 

            // Count of solutions including coins[j] 

            x = (i-coins[j] >= 0) ? table[i - coins[j]][j] : 0; 

            // Count of solutions excluding coins[j] 

            y = (j >= 1) ? table[i][j - 1] : 0; 

            // total count 

            table[i][j] = x + y; 

        } 

    } 

    return table[n][m - 1]; 

}

// loop with 1D memoization space O(n) time O(n*m)

unsigned long countDP( vector<int> &coins, int m, int n ) 

      unsigned long table[n + 1]; 

    memset(table, 0, sizeof(table)); 

      table[0] = 1; 

      for(int i=0; i< m; i++) 

        for(int j=coins[i]; j <= n; j++) 

            table[j] += table[j-coins[i]]; 

      return table[n]; 


// Complete the ways function below.

unsigned long ways(int n, vector<int> coins) {

    return countDP(coins, coins.size(), n);

    //return countDP1(coins, 0, n);

}


int main()

{

    ofstream fout(getenv("OUTPUT_PATH"));

    string nm_temp;

    getline(cin, nm_temp);

    vector<string> nm = split_string(nm_temp);

    int n = stoi(nm[0]);

    int m = stoi(nm[1]);

    string coins_temp_temp;

    getline(cin, coins_temp_temp);

    vector<string> coins_temp = split_string(coins_temp_temp);

    vector<int> coins(m);

    for (int i = 0; i < m; i++) {

        int coins_item = stoi(coins_temp[i]);

        coins[i] = coins_item;

    }

    unsigned long res = ways(n, coins);

    fout << res << "\n";

    fout.close();

    return 0;

}

vector<string> split_string(string input_string) {

    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {

        return x == y and x == ' ';

    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {

        input_string.pop_back();

    }

    vector<string> splits;

    char delimiter = ' ';

    size_t i = 0;

    size_t pos = input_string.find(delimiter);


    while (pos != string::npos) {

        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;

        pos = input_string.find(delimiter, i);

    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;

}


Wednesday, September 23, 2020

Subset of non-adjacent elements with the maximum sum

int maxSubsetSum(vector<int> arr) {
    int cmax = 0, curr_plus_previous_not_adj;

    int previous_not_adj = arr[0];
    int previous_adj = max(arr[1], previous_not_adj);

    for(int i = 2; i < arr.size(); i++) {
            curr_plus_previous_not_adj = max(arr[i], arr[i] + previous_not_adj);
            cmax = max(curr_plus_previous_not_adj, previous_adj);
            previous_not_adj = previous_adj;
            previous_adj = cmax;
    }
    return cmax;
}

Monday, September 21, 2020

Fibonacci - Dynamic Programming + Optmized versions

f (1) = 1
f (2) = 1
f (3) =  f(1) + f (2)
f (4) =  f(2) + f (3)
f (n) =  f(n-2) + f(n-1)

         f(1)        f(2)
            \         /   |
              f(3)      |
                |    \    |
                |     f(4)
                |     /   |         
                f (5)   |
                  |    \  |
                  |    f(6)
                  |     /
                 f(7)

To solve the fibonacci problem the naive solution is simple as the following

unsigned long fibonacci(int n) {
        if (n < 2)
                return 1;

        return  fibonacci(n-2) + fibonacci(n-1);
}

Using the naive recursive approach we will end up doing the same recursive call more than once, for example to calculate to calculate f(4) and f (3), we calculate f(2) , to calculate f(4) and f(5) we calculate f(3), to calculate f(5) and f(6) we use f(4) and so on.

T(n) = T(n-1) + T(n-2) + c
= 2T(n-1) + c //from the approximation T(n-1) ~ T(n-2)
= 2*(2T(n-2) + c) + c
= 4T(n-2) + 3c
= 8T(n-3) + 7c
= 2^k * T(n - k) + (2^k - 1)*c

Let's find the value of k for which: n - k = 0
k = nT(n) = 2^n * T(0) + (2^n - 1)*c
= 2^n * (1 + c) - c

The complexity time of this algorithm will be  O (2^n)

Using Dynamic programming (recursion + memoization) we can reduce this time, simply saving already calculated results in a dictionary and avoid repetitive recursion calls by just consulting the dictionary.

The Dynamic programming version of fibonacci that runs in O(n) time.

unsigned long fibonacci(int n, unordered_map<unsigned long,unsigned long> &map) {
        if (map.find(n) != map.end()) {
                return map[n];
        }
        if (n < 2)
                return 1;

        map[n] = fibonacci(n-2, map) + fibonacci(n-1, map);

        return map[n];
}

Optimized version saving space
Time: O(n) , Space O(1)
int fib(int n)
{
    int a = 0, b = 1, c, i;
    if( n == 0)
            return a;
    for(i = 2; i <= n; i++)
    {
        c = a + b;
        a = b;
        b = c;
    }
    return b;


And finally the most optmized version of fibonacci,
Time: O(1) , Space(1)

int fib(int n) {
double phi = (1 + sqrt(5)) / 2;
return round(pow(phi, n) / sqrt(5));
}

Sunday, July 26, 2020

Listen the world - Websites to listen to radio around the world with a diferent interface

Watch a video from a car riding in the city you choose and listen to a local radio
https://driveandlisten.herokuapp.com/

Point to  a place  in the Globe similar to Google Earth, and listen to the radio of that place
http://radio.garden/



Friday, July 17, 2020

Well Done Explanation of XSS (Cross-site-scripting)

Recommended reading about how XSS works, how to avoid this kind of attack.

https://excess-xss.com/


Blog Archive