Mateus Felipe

Today I Learned

Find-And-Replace Vim

How to fast replace all mathing strings on vim

vimeditoridecli

For basic find-and-replace on vim, we can use the :substitute (:s) command.

The general form of the substitute command is as follow:

:[range]s/{pattern}/{string}/[flags] [count]

The command search each line in [range] for a {pattern}, and replaces it with a {string}.
[count] is a positive integer that multiplies the command.

If no [range] and [count] are given, only the pattern found in the current line is replaced.
The current line is the line where the cursor is placed.

For example, to search for the first occurrences of the string "foo" in the current line, and replace it with "bar", you should use:

:s/foo/bar

To replace all occurrences of the search pattern in the current line, add the g flag:

:s/foo/bar/g

If you want to search and replace the pattern in the intire file, use the percentage character % as a range.
This caracter indicates a range from the first to the last line of the file:

:%s/foo/bar/g

We can also use | as parameter separator:

:s|foo|bar

To show confirmation for each substituition, use c flag:

:s/foo/bar/gc

To ignore case sensitivity, use i flag:

:s/foo/bar/gi

There is much more options, look at the ref link for more...

ref: https://linuxize.com/post/vim-find-replace/

Application-Only Volume on MOCP

How to use a "application-only" volume on MOCP for change volume on mocp without affect system

mocplinuxalsasoundplayer

I was using MOCP on linux for a while to listenning some musics that I have downloaded on my machine, but the only defect of MOCP is the volume controll... until now...

The default volume controll of MOCP controlls the volume from ALSA hardware mixer setting, which change the volume from all system. That is a pain when you want to listennig musics as background music, while listenning another sounds too (like noisekun.com).

Today I discovered that there is a way to make mocp volume controll independent from system volume.

You may see that on volume bar (lower left corner) was writen "Master":
screenshot of mocp volume bar (https://i.imgur.com/9YpA3DE.png)

This mean that the volume controll reflect the system volume, so we need to change this with the key X. Now our bar is:
screenshot of mocp volume bar (https://i.imgur.com/jaAFNpo.png)

And the volume is independent of system volume.

If your volume bar is writen "S.Off", you can type W to change to "Soft"

ref: https://moc.daper.net/node/1512

Rust Box

What is the "Box" in Rust Lang

rustboxmemoryheapstack

Reading some Rust code examples in documentation and blogs, I can see the use of Box<T> declaration. Like:

struct Schema {
    commands: Vec<Box<dyn Migration>>,
}
struct Schema {
    commands: Vec<Box<dyn Migration>>,
}

According to the official Rust documentation: "All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box<T>. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed."

ref: https://doc.rust-lang.org

Random Strings in Rust

How to generate a random fixed size string in Rust

rustrandstringgenerate

For generate a random string with fixed size in Rust, we can use Alphanumeric trait from rand crate:

use rand::{distributions::Alphanumeric, Rng}; // 0.8
 
fn main() {
  let s: String = rand::thread_rng()
    .sample_iter(&Alphanumeric)
    .take(7)
    .map(char::from)
    .collect();
  println!("{}", s);
}
 
use rand::{distributions::Alphanumeric, Rng}; // 0.8
 
fn main() {
  let s: String = rand::thread_rng()
    .sample_iter(&Alphanumeric)
    .take(7)
    .map(char::from)
    .collect();
  println!("{}", s);
}
 

ref: https://stackoverflow.com/questions/54275459/how-do-i-create-a-random-string-by-sampling-from-alphanumeric-characters

Rust + SQLite

Connect SQLite in a Rust app

rustsqlitedbsql

For run SQL queries on SQLite database from Rust, we can use the sqlite3 crate:

let connection = sqlite::open(":memory:").unwrap();
 
connection
  .execute(
    "
    CREATE TABLE users (name TEXT, age INTEGER);
    INSERT INTO users (name, age) VALUES ('Alice', 42);
    INSERT INTO users (name, age) VALUES ('Bob', 69);
    ",
  )
  .unwrap();
Open a connection, create a table, and insert some rows.
let connection = sqlite::open(":memory:").unwrap();
 
connection
  .execute(
    "
    CREATE TABLE users (name TEXT, age INTEGER);
    INSERT INTO users (name, age) VALUES ('Alice', 42);
    INSERT INTO users (name, age) VALUES ('Bob', 69);
    ",
  )
  .unwrap();
Open a connection, create a table, and insert some rows.

connection
  .iterate("SELECT * FROM users WHERE age > 50", |pairs| {
    for &(column, value) in pairs.iter() {
      println!("{} = {}", column, value.unwrap());
    }
    true
  })
  .unwrap();
Select some rows and process them one by one as plain text:
connection
  .iterate("SELECT * FROM users WHERE age > 50", |pairs| {
    for &(column, value) in pairs.iter() {
      println!("{} = {}", column, value.unwrap());
    }
    true
  })
  .unwrap();
Select some rows and process them one by one as plain text:

And more...

ref: https://docs.rs/sqlite3/latest/sqlite3/

Handshake Combinations

Math behind the calculation of the number of handshakes from N persons

mathmatemáticaformulacombinationscombinatória

Given nn people, how many handshakes will be given by all the people greeting each other?

We can determine this using the formula:

n(n1)2\frac{n(n-1)}{2}

Where nn is the number of people that will handshake.

ref: solution for https://www.hackerrank.com/challenges/handshake/problem

Disable Node Warnings

How to disable node warnings with env variable

nodewarningsincovenience

When we run a node script, we can see incovenie warnings like:

(node:3174) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:3174) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

For disable this warnings, just pass NODE_NO_WARNINGS=1 as environment variable before node command or script, e.g.:

NODE_NO_WARNINGS=1 node index.js
NODE_NO_WARNINGS=1 node index.js

On package.json script:

// ...
  "script": {
    "test": "NODE_NO_WARNINGS=1 jest --watch"
  }
// ...
// ...
  "script": {
    "test": "NODE_NO_WARNINGS=1 jest --watch"
  }
// ...

Position Sticky

Use position sticky with tailwindcss

tailwindcsscssui

We can use sticky class when using tailwind to make an element fixed on screen while the parent element is visible.

Code:

<div class="relative">
  <h1 class="sticky top-0">Element</h1>
</div>
<div class="relative">
  <h1 class="sticky top-0">Element</h1>
</div>

CSS Equivalent:

.parent-element {
  position: relative;
}
.element {
  position: sticky;
  top: 0;
}
.parent-element {
  position: relative;
}
.element {
  position: sticky;
  top: 0;
}

Visual example: https://www.w3schools.com/howto/howto_css_sticky_element.asp

Mock module inside test

How to mock module implementation inside a test with jest

reactnext.jstestsjestzustandreact-testing-librarymock

Sometimes you are testing a component and need to mock a module (in this case I needed to mock a zustand store), but with the exemple of "next/navigation" mock, you are mocking the module for entire test suit on the file that you declare the jest.mock(). But, if you want to mock a specific implementation for each test? So first, with need to declare the module mock, without pass the implementation function:

jest.mock('../../stores/sounds-state-store')
jest.mock('../../stores/sounds-state-store')

In this case we are mocking "../../stores/sounds-state-store" module

And, inside each test, we will use the jest.Mock.mockImplementation() function to mock the implementation of module inside it/test scope:

the store we want to mock is useSoundsStateStore, from '../../stores/sounds-state-store'

useSoundsStateStore.mockImplementation(
  () =>
    [{ active: true, id: 'd4ad48e', loaded: true, volume: 1 }] as SoundState[]
)
useSoundsStateStore.mockImplementation(
  () =>
    [{ active: true, id: 'd4ad48e', loaded: true, volume: 1 }] as SoundState[]
)

Full code:

// other imports...
import { SoundState, useSoundsStateStore } from '../../stores/sounds-state-store'
 
jest.mock('../../stores/sounds-state-store')
 
describe('Clear Button', () => {
  // tests...
 
  it('should not be disabled', async () => {
    ;(useSoundsStateStore as unknown as jest.Mock).mockImplementation(
      () =>
        [
          { active: true, id: 'd4ad48e', loaded: true, volume: 1 }
        ] as SoundState[]
    )
 
    render(<ClearButton />)
 
    const button = await screen.findByRole('button', { name: /clear/i })
 
    expect(button.getAttribute('disabled')).toBeNull()
  })
 
  // tests...
})
// other imports...
import { SoundState, useSoundsStateStore } from '../../stores/sounds-state-store'
 
jest.mock('../../stores/sounds-state-store')
 
describe('Clear Button', () => {
  // tests...
 
  it('should not be disabled', async () => {
    ;(useSoundsStateStore as unknown as jest.Mock).mockImplementation(
      () =>
        [
          { active: true, id: 'd4ad48e', loaded: true, volume: 1 }
        ] as SoundState[]
    )
 
    render(<ClearButton />)
 
    const button = await screen.findByRole('button', { name: /clear/i })
 
    expect(button.getAttribute('disabled')).toBeNull()
  })
 
  // tests...
})

Note that we use:

;(useSoundsStateStore as unknown as jest.Mock).mockImplementation()
;(useSoundsStateStore as unknown as jest.Mock).mockImplementation()

instead of:

useSoundsStateStore.mockImplementation()
useSoundsStateStore.mockImplementation()

Because it's a typescript project, and we need to tell the ts compiler that useSoundsStateStore have jest.Mock functions on this scope.

references:

Mock "next/navigation" with Jest

How to fix error "invariant expected app router to be mounted" when test Next.js hooks/components

reactnext.jstestsjestreact-testing-librarymocknext/navigation

Next.js: 14.0.3

When you try to test a component or hook that uses some function from "next/navigation" module (like useRouter, useSearchParams, useSearchParams, etc.), you may come across the error:

● Test suite failed to run
 
  invariant expected app router to be mounted
 
    5 |
    6 | export default function useQueryState(key: string, defaultValue: string = '') {
  > 7 |   const router = useRouter()
      |                           ^
    8 |   const searchParams = useSearchParams()
    9 |   const pathname = usePathname()
   10 |
● Test suite failed to run
 
  invariant expected app router to be mounted
 
    5 |
    6 | export default function useQueryState(key: string, defaultValue: string = '') {
  > 7 |   const router = useRouter()
      |                           ^
    8 |   const searchParams = useSearchParams()
    9 |   const pathname = usePathname()
   10 |

This happening because the "next/navigation" just works when app router was monted, to solve this, you need to mock the entire module. Put this before all your describes and it/tests:

jest.mock('next/navigation', () => ({
  useRouter: jest.fn(() => ({
    replace: jest.fn()
  })),
  useSearchParams: jest.fn(() => ({
    get: jest.fn()
  })),
  usePathname: jest.fn()
}))
jest.mock('next/navigation', () => ({
  useRouter: jest.fn(() => ({
    replace: jest.fn()
  })),
  useSearchParams: jest.fn(() => ({
    get: jest.fn()
  })),
  usePathname: jest.fn()
}))

references: https://github.com/vercel/next.js/discussions/48937

Enable Locales on GNOME

Enable some locales to use when they not appear on "Region & Language" menu

desktophow-tolanguagesconfiggnome

When we go to Region & Language menu to change locale (language and units) of a newly installed system with GNOME, may not have the language you are looking for. For the most cases is a question of enable it on /etc/locale.gen.

For this, just edit the file /etc/locale.gen with root privileges:

$ sudo vim /etc/locale.gen

And uncomment the language that you looking for, e.g:

for

#pt_BR.UTF-8 UTF-8

remove the #, and save

pt_BR.UTF-8 UTF-8

After edit the locale file, regenerate locales with command:

sudo locale-gen

That's it! Just go to Region & Language and select your language.

referencies:

Gnome (Debian 11): How to install en*DK formats (date, numbers, units)?: https://unix.stackexchange.com/questions/679315/gnome-debian-11-how-to-install-en-dk-formats-date-numbers-units [_archive*]

Black Wallpaper Bug on XFCE4

Black wallpaper on xfce4 when restart the computer

bugdesktophow-toxfce

This problem consists of black background insted the wallpaper on xfce4, apparently is the xfdesktop daemon that was not starting on login. To fix it, wee just need to setup this daemon to auto start on login:

  1. Go to Session and Startup > Application Autostart
  2. Then click on Add
  3. Will appear a window, enter some name, like "Wallpaper Daemon" and the description, "Daemon to load the xfce4 wallpaper", on the command field, add the command xfdesktop --replace.
  4. After save the config, restart the computer.

references:

Desktop background appears black when using XFCE: https://unix.stackexchange.com/questions/151471/desktop-background-appears-black-when-using-xfce [archive]

Oak Over Https

Integrando Oak com certificados SSL

sslcryptographysecure-internetback-enddeno

Dependências

Primeiro devemos certificar que temos o programa openssl

dpkg -l |grep openssl
dpkg -l |grep openssl

deve aparecer algo como isto

ii libgnutls-openssl27:amd64   2.12.23-12ubuntu2.4   amd64   GNU TLS library - OpenSSL wrapper

ii openssl   1.0.1f-1ubuntu2.16   amd64   Secure Sockets Layer toolkit - cryptographic utility
ii libgnutls-openssl27:amd64   2.12.23-12ubuntu2.4   amd64   GNU TLS library - OpenSSL wrapper

ii openssl   1.0.1f-1ubuntu2.16   amd64   Secure Sockets Layer toolkit - cryptographic utility

senão tiver o openssl instalado, instale com o comando:

(debian based)

apt-get install openssl
apt-get install openssl

Gerar Chaves

Para gerar a chave privada e o certificado rode o comando:

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

Depois gere a chave descriptografada:

openssl rsa -in keytmp.pem -out key.pem
openssl rsa -in keytmp.pem -out key.pem

ja pode excluir o arquivo keytmp.pem, ele não será mais necessário.

Usar Oak com a chave e o certificado

Para usar Oak com HTTPS devemos passar os atributos secure, certFile e keyFile.
como o exemplo a seguir:

await App.listen({
  port: 8000,
  secure: true,
  certFile: './cert.pem',
  keyFile: './key.pem',
})
await App.listen({
  port: 8000,
  secure: true,
  certFile: './cert.pem',
  keyFile: './key.pem',
})

Referências

How To Create an HTTPS Server on Localhost using Express: https://medium.com/@nitinpatel_20236/how-to-create-an-https-server-on-localhost-using-express-366435d61f28 [archive]

oak docs: https://github.com/oakserver/oak [archive]

OpenSSL Tutorial: How Do SSL Certificates, Private Keys, & CSRs Work?: https://phoenixnap.com/kb/openssl-tutorial-ssl-certificates-private-keys-csrs [archive]