Uma boa prática na hora de criar os construtores de uma classe, é reaproveitar os setters dos atributos para manter a validação.
Imagine que temos a classe Carro, com seus respectivos setters:
Perceba que temos uma validação no método setAno(int ano), que impede que o usuário defina um ano menor que 0 (negativo) e maior que 2025.
Agora vamos criar o construtor para a classe:
Criando o construtor desse jeito, podemos instanciar a classe passando os seguintes parâmetros:
Perceba que podemos passar o valor negativo como parâmetro do construtor, e isso é válido, já que o construtor não possui validação, apenas o setter do ano setAno(int ano).
Parra corrigir isso, é só chamarmos os setters no construtor, para manter a validação:
Edit multiple line on Vim
How to edit multiple lines at once on vim/neovim/lunarvim
Java is a 100% POO language, so to starts a Java software, our main function need to be a class method.
The filename need to be the same of the class that was declared in this file.
So the basic structure of Java file is:
Where Program is the class name of this file and main the method name, i.e., the main function that will be executed.
public means that our main() method can be used by all files that imports Program
static means that our main() method can be called without instantiate the class Program
void means that our main() method doesn't return anything
args is the argument that our main() method receives. In this case, an array of String objects. This is the way that Java receives the arguments passed by the command line.
System.out.println() is the way that Java print something in the console.
System is a class that Java provides to us native methods to interact with the system
out is a static object of System class that represents the output stream
println() is a method of out object that prints a string and a new line (Alternative: print(), that prints only the string without a new line)
And, the filename need to be Program.java because our class is named Program.
Os modelos de Single Tenant e Multi Tenant são duas abordagens diferentes para a arquitetura de um SaaS, e dizem respeito a como o serviço/infraestrutura é oferecido ao cliente.
SaaS: Software as a Service
Single = Um software que é utilizado por UMA empresa, cada cliente possui um instância do software, incluindo a infraestrutura e banco de dados.
Multi = Um software que é utilizado por VÁRIAS empresas, todos os clientes compartilham a mesma instância do software, incluindo a infraestrutura e banco de dados.
Multi Tenant NÃO QUER DIZER subdomínios.
Multi Tenant NÃO QUER DIZER um banco de dados por empresa.
Dica JavaScript: Otimize Chamadas Assíncronas com Promise.all
Executar await em chamadas assíncronas de forma sequencial, como em getProducts() seguido por getOrders(), faz com que a segunda chamada espere a conclusão da primeira, aumentando o tempo total de execução.
Optar por Promise.all nesse caso, permite que as chamadas sejam feitas em paralelo, reduzindo o tempo de espera e melhorando a performance da sua aplicação.
❌ worse
✅ better
Mas o Promise.all deve ser usado com cuidado, porque se uma das requisições falhar, todas vão falhar.
You implement this trait when you want to specify how a particular type is to be converted into an iterator. Most notably, if a type implements IntoIterator it can be used in a for loop.
For example, Vec implements IntoIterator... thrice!
Each variant is slightly different.
This one consumes the Vec and its iterator yields values (T directly):
The other two take the vector by reference (don't be fooled by the signature of into_iter(self) because self is a reference in both cases) and their iterators will produce references to the elements inside Vec.
What is the difference between iter and into_iter?
into_iter is a generic method to obtain an iterator, whether this iterator yields values, immutable references or mutable references is context dependent and can sometimes be surprising.
iter and iter_mut are ad-hoc methods. Their return type is therefore independent of the context, and will conventionally be iterators yielding immutable references and mutable references, respectively.
This is a usefull pattern on Rust match when you want to match slices of a vector.
Imagine this problem: We want to implement a function which takes an vector containing the names of people that like an item. It must return the display text as shown in the examples:
We can solve this with:
Where rest @ .. will catch all the rest of the vector items.
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...
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":
This mean that the volume controll reflect the system volume, so we need to change this with the key X. Now our bar is:
And the volume is independent of system volume.
If your volume bar is writen "S.Off", you can type W to change to "Soft"
Reading some Rust code examples in documentation and blogs, I can see the use of Box<T> declaration. Like:
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."
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:
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'
Full code:
Note that we use:
instead of:
Because it's a typescript project, and we need to tell the ts compiler that useSoundsStateStore have jest.Mock functions on this scope.
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:
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:
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.
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:
Go to Session and Startup > Application Autostart
Then click on Add
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.