Cantina

algoritmo "Controle_de_Vendas_Cantina"
var
produtos: vetor[1..5] de caractere
estoque: vetor[1..5] de inteiro
vendas: vetor[1..5] de inteiro
preco: vetor[1..5] de real
i: inteiro
maisVendido: inteiro
maiorVenda: inteiro
totalItens: inteiro
faturamento: real
inicio
// Cadastro dos produtos
produtos[1] <- "Coxinha"
produtos[2] <- "Pastel"
produtos[3] <- "Refrigerante"
produtos[4] <- "Suco"
produtos[5] <- "Sanduiche"
// Preços dos produtos
preco[1] <- 6.00
preco[2] <- 5.00
preco[3] <- 4.50
preco[4] <- 4.00
preco[5] <- 7.50
totalItens <- 0
faturamento <- 0
maiorVenda <- 0
maisVendido <- 1
escreval("=== CONTROLE DE VENDAS DA CANTINA ===")
// Entrada dos dados
para i de 1 ate 5 faca
escreval("")
escreval("Produto: ", produtos[i])
escreva("Informe a quantidade em estoque: ")
leia(estoque[i])
enquanto estoque[i] < 0 faca
escreval("Valor invalido. Digite novamente.")
leia(estoque[i])
fimenquanto
escreva("Informe a quantidade vendida: ")
leia(vendas[i])
enquanto (vendas[i] < 0) ou (vendas[i] > estoque[i]) faca
escreval("Quantidade invalida.")
escreva("Informe novamente: ")
leia(vendas[i])
fimenquanto
// Atualiza estoque
estoque[i] <- estoque[i] - vendas[i]
// Calcula total de itens vendidos
totalItens <- totalItens + vendas[i]
// Calcula faturamento
faturamento <- faturamento + (vendas[i] * preco[i])
// Identifica produto mais vendido
se vendas[i] > maiorVenda entao
maiorVenda <- vendas[i]
maisVendido <- i
fimse
fimpara
// Exibição dos resultados
escreval("")
escreval("========== RELATORIO ==========")
para i de 1 ate 5 faca
escreval("")
escreval("Produto: ", produtos[i])
escreval("Quantidade vendida: ", vendas[i])
escreval("Estoque atual: ", estoque[i])
// Verificação de reposição
se estoque[i] <= 5 entao
escreval("ATENCAO: Produto precisa de reposicao!")
senao
escreval("Estoque suficiente.")
fimse
fimpara
escreval("")
escreval("Total de itens vendidos: ", totalItens)
escreval("Faturamento total: R$ ", faturamento:8:2)
escreval("Produto mais vendido: ", produtos[maisVendido])
escreval("Quantidade vendida: ", maiorVenda)
fimalgoritmo

Leave a comment

Copy index structure from one colletion to another

const src = db.src;
const dest = db.dst;

src.getIndexes().forEach(function(idx) {
  if (idx.name !== '_id_') { // ignora o índice padrão
    const key = idx.key;
    const options = Object.assign({}, idx);
    delete options.v;
    delete options.key;
    delete options.ns;
    print(`Criando índice ${idx.name} em ${dest.getName()} ...`);
    dest.createIndex(key, options);
  }
});

Leave a comment

Delete MongoDB empty collections

db.getCollectionNames().forEach(function (collName) {
    var stats = db.runCommand({ collStats: collName });
    if (stats.count === 0) {
        print("Apagando collection vazia: " + collName);
        db.getCollection(collName).drop();
    }
});

Leave a comment

Network interface traffic monitoring

#!/bin/bash

INTERFACE="eth0"
INTERVAL=5

get_bytes() {
    cat /sys/class/net/$INTERFACE/statistics/$1
}

echo "Monitoring $INTERFACE traffic (Ctrl+C to stop)"
echo "Time                RX MB/s    TX MB/s"

rx_bytes_old=$(get_bytes rx_bytes)
tx_bytes_old=$(get_bytes tx_bytes)

while true; do
    sleep $INTERVAL
    
    rx_bytes_new=$(get_bytes rx_bytes)
    tx_bytes_new=$(get_bytes tx_bytes)
    
    rx_rate=$(( (rx_bytes_new - rx_bytes_old) / INTERVAL / 1024 / 1024 ))
    tx_rate=$(( (tx_bytes_new - tx_bytes_old) / INTERVAL / 1024 / 1024 ))
    
    printf "%s %8d %8d\n" "$(date '+%H:%M:%S')" $rx_rate $tx_rate
    
    rx_bytes_old=$rx_bytes_new
    tx_bytes_old=$tx_bytes_new
done

Leave a comment

MySQL replication status check

-- On Master
SHOW MASTER STATUS;

-- On Slave
SHOW SLAVE STATUS\G

-- Check replication lag
SELECT 
    CASE 
        WHEN Slave_IO_Running = 'Yes' AND Slave_SQL_Running = 'Yes' 
        THEN 'OK' 
        ELSE 'ERROR' 
    END as Replication_Status,
    Seconds_Behind_Master as Lag_Seconds,
    Last_IO_Error,
    Last_SQL_Error
FROM 
    (SHOW SLAVE STATUS) as slave_status;

Leave a comment

Another way to init a restored AWS EBS

#!/bin/bash

DEVICE="/dev/md1"
BLOCK_SIZE="1M"
THREADS=4

# Check if device exists
if [ ! -b "$DEVICE" ]; then
  echo "$DEVICE not available."
  exit 1
fi

echo "Start sequential reading $DEVICE..."

pv "$DEVICE" --rate-limit 500M | dd of=/dev/null bs=$BLOCK_SIZE iflag=direct status=progress

echo "Done reading."

Leave a comment

Python script to monitor GPIO

pip3 install inotify_simple

import os
import time
import stat
from datetime import datetime
from inotify_simple import INotify, flags

LOG_FILE = "/cache/gpio.log"
WATCH_FILES = [
    "/sys/class/gpio/gpio64/value",
    "/sys/class/gpio/gpio69/value"
]

def log(msg):
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    with open(LOG_FILE, "a") as f:
        f.write(f"[{ts}] {msg}\n")

def get_inode(path):
    return os.stat(path).st_ino

def find_processes_writing_to_inode(inode):
    result = []
    for pid in filter(str.isdigit, os.listdir("/proc")):
        fd_path = f"/proc/{pid}/fd"
        try:
            for fd in os.listdir(fd_path):
                full_fd_path = os.path.join(fd_path, fd)
                try:
                    target = os.readlink(full_fd_path)
                    if not target.startswith("/sys/class/gpio/"):
                        continue
                    if os.stat(full_fd_path).st_ino == inode:
                        exe = os.readlink(f"/proc/{pid}/exe")
                        result.append(f"PID={pid} EXE={exe}")
                except Exception:
                    continue
        except Exception:
            continue
    return result if result else ["<nenhum processo visível>"]

def main():
    inotify = INotify()
    watch_flags = flags.MODIFY

    watches = {}
    inodes = {}

    for path in WATCH_FILES:
        wd = inotify.add_watch(path, watch_flags)
        watches[wd] = path
        inodes[path] = get_inode(path)

    log("Monitoramento iniciado nos arquivos GPIO.")

    while True:
        for event in inotify.read(timeout=500):  # timeout opcional
            path = watches[event.wd]
            inode = inodes[path]
            value = open(path).read().strip()
            log(f"{path} modificado. Novo valor: {value}")
            writers = find_processes_writing_to_inode(inode)
            for proc in writers:
                log(f"  Processo: {proc}")

if __name__ == "__main__":
    main()

Leave a comment

Listing long running queries in MongoDB

db.currentOp().inprog.forEach(
  function(op) {
    if(op.secs_running > 5) printjson(op);
  }
)

Killing it

killLongRunningOps = function(maxSecsRunning) {
    currOp = db.currentOp();
    for (oper in currOp.inprog) {
        op = currOp.inprog[oper-0];
        if (op.secs_running > maxSecsRunning && op.op == "query" && !op.ns.startsWith("local")) {
            print("Killing opId: " + op.opid
                    + " running for over secs: "
                    + op.secs_running);
            db.killOp(op.opid);
        }
    }
};

Thanks to: https://gist.githubusercontent.com/kylemclaren/3c09a4dda5991cf0bf9c/raw/6655b80a3e1bdd0fc6aa6142cb5baf17296b225e/killLongRunningOps.js

Leave a comment

OpenVPN old server

mkdir ~/easy-rsa
ln -s /usr/share/easy-rsa/* ~/easy-rsa/
cd ~/easy-rsa/
./easyrsa init-pki
./easyrsa build-ca nopass
cd ~/easy-rsa/
./easyrsa build-server-full vpn_server nopass
cd ~/easy-rsa/
./easyrsa sign-req server vpn_server
cd ~/easy-rsa/
./easyrsa gen-dh
cd ~/easy-rsa/pki/
openvpn --genkey tls-crypt-v2-server private/vpn_server.pem
ls ~/easy-rsa/pki/private/
cd /etc/openvpn/server
ls
vi server.conf
sudo vi server.conf
sudo apt install vim
cd ~/easy-rsa/pki/
sudo cp ca.crt /etc/openvpn/server/
sudo cp dh.pem /etc/openvpn/server/
cd ~/easy-rsa/pki/private/
sudo cp vpn_server.key /etc/openvpn/server/
sudo cp vpn_server.pem /etc/openvpn/server/
cd ~/easy-rsa/pki/issued/
sudo cp vpn_server.crt /etc/openvpn/server/
sudo vi /etc/sysctl.conf
sudo sysctl -p
sduo iptables -L -n
sudo iptables -L -n
sudo systemctl start openvpn-server@server.service

Leave a comment

Parallel copy with rsync

#!/bin/bash

# define path
SRC="/src_path/dir"
DST="/dst_path/dir"
THREADS=5

# create path
mkdir -p "$DST"

# create skel
rsync -a -f"+ */" -f"- *" "$SRC/" "$DST/"

# copy with threads
find "$SRC" -type f | /usr/local/bin/parallel -j $THREADS rsync -av --progress {} "$DST/{/}"

echo "done"

Leave a comment

Create your own website, free on WordPress.com.Create your own website.
Start free