Categorie
Senza categoria

L’Essenziale Git: Perché Ogni Tirocinante Dovrebbe Impararlo Sin dal Primo Giorno

Riflessione del fine settimana su un tema che, nonostante la sua ubiquità nello sviluppo software, spesso passa inosservato per l’importanza cruciale che riveste: l’apprendimento e l’utilizzo di #Git.

Partendo dal sottovalutatissimo valore intrinseco di Git come strumento fondamentale per sviluppatore, architetto software o tirocinante che si avvicina al mondo della programmazione, cercando di evidenziare come è stato il mio approccio e come questo mi aiuti nella gestione degli inevitabili conflitti.

Git non è solo un sistema di controllo versione, ma è anche una base solida per tutto il mondo cloud native e la programmazione basata su pipeline. Nei progetti con tanti attori è tipo acqua nel deserto dell’informatica: essenziale, vitale, insostituibile. Tuttavia, come ogni tecnologia potente, viene con le sue complessità e sfide, in particolare per chi è agli inizi.

La prima sfida con cui ci si scontra è la curva di apprendimento. Git, con la sua vastità di comandi e la sua struttura non sempre intuitiva, può sembrare scoraggiante. Eppure, proprio come per le sfide etiche nell’IA, la #comprensione profonda e l’uso consapevole di Git possono fare la differenza tra un progetto di successo e un caos di codici perduti e opportunità mancate. Il trucco sta nel capire “cosa fa” e “come lo fa”

Riflettendo sul dinamismo e la complessità di Git, credo che tutto possa sintetizzaresi in due concetti: “il ciclo di commit, pull, push” e l’area di “stage”. Questi non sono solo passaggi procedurali, ma riflettono una filosofia di lavoro mirata all’efficienza e alla precisione.

#Commit: Immortala le modifiche nel repository locale. È l’equivalente di annotare i progressi del tuo lavoro (L’area di #stage è il filtro che ti permette di selezionare con precisione quali modifiche includere nel prossimo commit.).
#Pull: Una sorta di Download. necessario prima del Push, aggiorna il lavoro con le modifiche globali. Assicura che il tuo contributo sia sempre in armonia con quello del team, evitando conflitti e dissonanze.
#Push: Upload. La condivisione delle tue modifiche con il mondo. Completa il ciclo di collaborazione, trasformando il lavoro individuale in un contributo collettivo.

Immaginate un mondo in cui ogni sviluppatore, dal più esperto al neofita, padroneggia Git al punto da rendere ogni collaborazione fluida, ogni rollback una manovra semplice, ogni merge una routine priva di stress. Questo non è un’utopia, ma una realtà possibile attraverso l’educazione e la pratica costante.

Categorie
Senza categoria

Sfide Etiche nell’Intelligenza Artificiale: Bias e Discriminazione nei Sistemi AI

Riflessione del fine settimana su un tema che sempre più spesso mi capita di incontrare, tra colleghi e amici: le sfide etiche nell’Intelligenza Artificiale.

Proverò a cimentarmi in un’analisi più o meno dettagliata dei topic “#bias” e della “#discriminazione” nei sistemi #AI, e qualche spunto su soluzioni che affrontiamo nel mondo reale dell’IA.

L’Intelligenza #Artificiale è una delle invenzioni più promettenti del nostro tempo e, nonostante la versione attuale sia nata quasi per caso, si vede il potenziale per trasformare radicalmente alcuni aspetti della società. Parafrasando Ben Parker, però, questa potente tecnologia è anche intrinsecamente complessa e presenta sfide etiche significative. Una particolarmente interessante sta proprio nel bias.

In generale, il termine “bias” identifica a un pregiudizio o a una distorsione sistematica nella percezione, nell’interpretazione o nella decisione. Il problema è che, questo, può influenzare il risultato in modo non oggettivo o imparziale e si applica a una vasta gamma di contesti, dalla psicologia alla statistica, fino all’Intelligenza Artificiale

Il bias nei sistemi AI può manifestarsi in molte forme e si verifica quando gli algoritmi producono risultati discriminanti a causa di dati di addestramento sbilanciati (o disuguaglianze intrinseche nelle informazioni fornite).

I pensieri più estremisti penseranno subito alle ingiustizie in settori chiave come la selezione del personale, la concessione del credito e la sanità e non sbagliano.

Immaginate un sistema AI progettato per assistere nella selezione di candidati per un’opportunità di #lavoro. Se il #dataset utilizzato per l’addestramento di questo sistema contiene principalmente informazioni storiche di candidati maschi che sono stati assunti, il modello potrebbe imparare a favorire automaticamente i candidati maschi nel processo di selezione. Questo è un classico esempio di bias nei sistemi AI. Anche se il sistema è teoricamente basato su algoritmi oggettivi, la sua predisposizione a favore di un gruppo specifico di candidati riflette il pregiudizio intrinseco nei dati di #addestramento, creando un ciclo che perpetua l’ingiustizia.

Uno dei punti di partenza, quindi, è l’esame attento dei dati di addestramento. Se il nostro dataset contiene #disuguaglianze, gli algoritmi apprenderanno a replicarle. Altro esempio? Se chiediamo: “Disegnami un #professore” spesso avremo in risposta l’immagine di un uomo, anziano, la barba lunga, bianco e gli occhiali. La location sarà una biblioteca o uno studio.

È fondamentale comprendere che come #architetti software e programmatori esperti abbiamo una grande responsabilità nel garantire che i sistemi AI che creiamo siano equi e giusti. Si parte dal design degli algoritmi, passando per il dataset, la diversità nel team e il monitoraggio costante per identificare e correggere il bias.

#my2cents

Categorie
Senza categoria

Notepad++ multi-line file tabs

Short -> If what you want is “multi-line file tabs”, you can set it through “Settings–>Preferences–>General–>Tab bar”, check the box “Multi-line”, then you will get it.

Notepad++ è un editor di testo molto apprezzato dagli sviluppatori e dagli appassionati di codifica per la sua versatilità e la vasta gamma di funzionalità. Una di queste funzionalità, spesso poco conosciuta ma molto utile, è la capacità di impostare le schede dei file su più linee, consentendo una gestione più efficiente dei tuoi progetti e migliorando la tua produttività.

Ecco come attivare le schede multi-line in Notepad++:

  1. Aggiorna a una Versione Recente: Assicurati di avere l’ultima versione di Notepad++ installata. Le versioni più recenti tendono ad avere miglioramenti e correzioni di bug.
  2. Apri Notepad++: Avvia l’applicazione Notepad++ sul tuo computer.
  3. Vai a Impostazioni: Nel menu principale, fai clic su “Impostazioni” e seleziona “Preferenze”.
  4. Apri l’Opzione Schede: Nella finestra di dialogo delle Preferenze, espandi la categoria “Generale” sulla sinistra e seleziona “Schede”.
  5. Abilita “Multi-Line”: Nella sezione “Schede”, troverai un’opzione chiamata “Schede multilinea”. Spunta questa opzione per abilitare le schede su più linee.
  6. Configura le Schede: Ora puoi personalizzare ulteriormente l’aspetto delle schede multi-line. Puoi regolare il numero di righe visualizzate per ogni scheda o impostare altre opzioni come la dimensione del testo.
  7. Salva le Impostazioni: Fai clic su “Applica” e poi su “OK” per salvare le tue modifiche.

Una volta abilitate le schede multi-line, scoprirai che è molto più facile gestire più file contemporaneamente. Ogni scheda avrà spazio sufficiente per visualizzare il nome del file e ti permetterà di passare rapidamente tra i documenti aperti. Questa funzionalità è particolarmente utile quando stai lavorando su progetti complessi con numerosi file.

In conclusione, se sei un utente abituale di Notepad++ e desideri aumentare la tua produttività durante la programmazione o la modifica di documenti, considera l’opzione di attivare le schede multi-line. Questa semplice modifica può rendere il tuo flusso di lavoro molto più efficiente e agevole, risparmiandoti tempo prezioso.

Categorie
Senza categoria

Setting Up a Simple Hardhat Project for Ethereum Development #ethereum #hardhat #blockchain #docker

Hardhat is a popular development environment for building and deploying Ethereum smart contracts. In this guide, we’ll walk you through the steps to set up a simple Hardhat project, create a Dockerfile for containerization, and demonstrate how to launch the project using Docker Compose. Additionally, we’ll show you how to deploy a contract to the Goerli test network.

Step 1: Create a Hardhat Project

To create a new Hardhat project, follow these steps:

  1. Open your terminal and create a new directory for your project:
mkdir my-hardhat-project
cd my-hardhat-project
  1. Initialize a new Node.js project and install Hardhat as a development dependency:
npm init -y
npm install --save-dev hardhat
  1. Initialize Hardhat in your project:
npx hardhat

Follow the prompts to create a new Hardhat project configuration. You can choose to create a sample project or customize it according to your requirements.

Config the hardhat.config.js file and select the node (infura, manged, own, …), network, private key,…

require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.20",
  defaultNetwork: "goerli",
  networks: {
    goerli: {
      url: "https://goerli.infura.io/v3/<API>",
      accounts: ["<PRIVATEKEY>"]
    }
  }
};

Write the main api.js code with the endopints:

const express = require('express')
require("dotenv").config()
const contract = require("./artifacts/contracts/CredentialNFT.sol/CredentialNFT.json");
var axios = require('axios');
const fs = require("fs");
const bodyParser = require('body-parser');
const { json } = require('body-parser');
const app = express()
const Web3 = require("web3")
const { ethers, JsonRpcProvider, BigNumber } = require('ethers');
app.use(bodyParser.json());
app.use(express.json());
const port = process.env.PORT || 5000

//:::::::::::::::::::SETUP NETWORK CONFIG:::::::::::::::::::::::::::::::::::::

const contractAddress = process.env.CONTRACT_ADDRESS
const contractAddressProfile = process.env.CONTRACT_ADDRESS_PROFILE
const abi = contract.abi


const hre = require("hardhat");

//:::::::::::::::::::API:::::::::::::::::::::::::::::::::::::

app.post("/mintToken", async (req, res) => {
    
    if (!req.body.metadata || !req.body.publicKey) {
        return res.status(400).json({ error: 'Missing parameter' });
      }
    
      try {
          const [deployer] = await hre.ethers.getSigners();
          const contract = new hre.ethers.Contract(contractAddress, abi, deployer);
          let result = await contract.Mint(req.body.publicKey, req.body.metadata);
          let receipt = await result.wait(); 
          console.log(receipt)
          let tokenID = await contract.getCount();
          res.json({ tokenId: tokenID.toString(), txsHash: receipt.hash});
  
      } catch (e) {
          console.error(e);
          res.writeHead(500);
          res.end("internal problem with contract invocation");
          return;
      }
})

app.post("/mintTokenProfile", async (req, res) => {
    if (!req.body.metadata || !req.body.publicKey) {
      return res.status(400).json({ error: 'Missing parameter' });
    }
  
    try {
        const [deployer] = await hre.ethers.getSigners();
        const contract = new hre.ethers.Contract(contractAddressProfile, abi, deployer);
        let result = await contract.Mint(req.body.publicKey, req.body.metadata);
        let receipt = await result.wait(); // Attendiamo la conferma della transazione
        console.log(receipt)
        let tokenID = await contract.getCount();
        res.json({ tokenId: tokenID.toString(), txsHash: receipt.hash});

    } catch (e) {
        console.error(e);
        res.writeHead(500);
        res.end("internal problem with contract invocation");
        return;
    }
   
})

app.post("/listNFT", async (req, res) => {
    console.log(req)
    if (!req.body.publicKey) {
      return res.status(400).json({ error: 'Missing parameter' });
    }
  
    try {
        const [deployer] = await hre.ethers.getSigners();
        const contract = new hre.ethers.Contract(contractAddressProfile, abi, deployer);
        let result = await contract.ListNFT(req.body.publicKey);
        console.log(result)
        res.send(result);

    } catch (e) {
        console.error(e);
        res.writeHead(500);
        res.end("internal problem with contract invocation");
        return;
    }
   
})
  
app.post("/burnToken", async (req, res) => {
    if (!req.body.token) {
      return res.status(400).json({ error: 'Missing parameter' });
    }
    
    try {
        let result = await myNftContract.burnNFT(Web3.utils.toBigInt(req.body.token));
        let receipt = await result.wait(); // Attendiamo la conferma della transazione
        res.json({ message: "token burn"});

    } catch (e) {
        console.error(e);
        res.writeHead(500);
        res.end("internal problem with contract invocation");
        return;
    }
   
})
  

app.listen(port, () => {
    console.log(`Server running on port ${port}`)

  })

Step 2: Create a Dockerfile

To containerize your Hardhat project, create a Dockerfile in the project root directory with the following content:

FROM node:18-alpine
COPY package.json package.json
COPY package-lock.json package-lock.json
RUN npm ci
COPY artifacts artifacts 
COPY contracts contracts
COPY scripts scripts
COPY .env .env
COPY api.js api.js
COPY hardhat.config.js hardhat.config.js
CMD ["node", "api.js"]

This Dockerfile sets up a Node.js environment, installs project dependencies, and specifies the command to run when the container starts. You may need to customize it based on your project’s requirements.

Step 3: Create a Docker Compose File

To simplify the deployment of your Hardhat project with Docker, create a docker-compose.yml file in the project root directory with the following content:

version: '3'

services:

  hardhat:
    build: ./hardhat-project
    container_name: sace-hardhat
    network_mode: "host"
    restart: always

This Docker Compose file defines a service named hardhat using the Dockerfile in the current directory. The service name and container name can be customized as needed.

Step 4: Deploy a Contract

To deploy a contract, you can use a deploy script. for example in script/deploy.js:

// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
//
// You can also run a script with `npx hardhat run <script>`. If you do that, Hardhat
// will compile your contracts, add the Hardhat Runtime Environment's members to the
// global scope, and execute the script.
const hre = require("hardhat");

async function main() {
  const currentTimestampInSeconds = Math.round(Date.now() / 1000);
  const unlockTime = currentTimestampInSeconds + 60;

  const lockedAmount = hre.ethers.parseEther("0.001");

  const lock = await hre.ethers.deployContract("CredentialNFT", [unlockTime], {
    value: lockedAmount,
  });

  await lock.waitForDeployment();

  console.log(
    `Lock with ${ethers.formatEther(
      lockedAmount
    )}ETH and unlock timestamp ${unlockTime} deployed to ${lock.target}`
  );
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Will deploy the contract in contracts/ folder:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

error notOwner();

contract CredentialNFT is ERC721, ERC721URIStorage {
    // uint256 public mintPrice;
    uint256 private _tokenIdCounter;
    address owner;

    struct token {
        uint256 id;
        string uri;
    }

    constructor(string memory name, string memory symbol) ERC721(name, symbol) {
        owner = msg.sender;
        _tokenIdCounter = 0;
    }

    modifier _onlyOwner() {
        if (msg.sender != owner) {
            revert notOwner();
        }
        _;
    }

    function Mint(
        address to,
        string calldata uri
    ) public returns (uint256) {
        _tokenIdCounter ++;
        uint256 tokenId = _tokenIdCounter;
        _safeMint(to, tokenId);
        _setTokenURI(tokenId, uri);

        return tokenId;
    }


    function burnNFT(uint256 tokenId) public _onlyOwner {

        _burn(tokenId);
    }

    function tokenURI(
        uint256 tokenId
    ) public view override(ERC721, ERC721URIStorage) returns (string memory) {
        return super.tokenURI(tokenId);
    }

    function transfer(
        address from,
        address to,
        uint256 tokenId
    ) public returns (bool) {
        require(ownerOf(tokenId) == from);
        require(to != from);
        safeTransferFrom(from, to, tokenId);
        return true;
    }

    function ListNFT(address addr) public view returns (token[] memory) {
        require(balanceOf(addr)>0);
        token[] memory list = new token[](balanceOf(addr));
        uint count = 0;
        for (uint i = 1; i <= _tokenIdCounter; i++) {
           
            if (addr == ownerOf(i)) {
               
                string memory _uri = tokenURI(i);
                token memory t = token({
                    id: i,
                    uri: _uri
                });
                list[count] = t;
                count++;
            }
        }
        return list;
    }

    function getCount() public view returns (uint256) {
        return _tokenIdCounter;
    }

     function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721URIStorage) returns (bool) {
        return ERC721.supportsInterface(interfaceId) || ERC721URIStorage.supportsInterface(interfaceId);
    }
}

Deploy to the Goerli test network using Hardhat, using the following command:

npx hardhat run scripts/deploy.js --network=goerli

Step 5: Build and Launch with Docker Compose

Now that you have set up the Dockerfile and Docker Compose configuration, you can build and launch your Hardhat project using Docker Compose:

  1. Build the Docker image from your project directory:
docker-compose build
  1. Launch your Hardhat project in a Docker container:
docker-compose up

Your Hardhat project will run inside the Docker container, and you can access it as specified in your Dockerfile.

Conclusion

You’ve successfully set up a simple Hardhat project, created a Dockerfile for containerization, and demonstrated how to deploy a contract to the Goerli test network using Docker Compose. This setup allows you to develop, test, and deploy Ethereum smart contracts in a consistent and reproducible environment.

Categorie
Senza categoria

ERROR: jakarta.ws.rs.ProcessingException: The timeout period of 30000ms has been exceeded while executing. #Quarkus #Java

As a developer working on web services, you may encounter a timeout error when using Jakarta WS RS. This error occurs when the timeout period is exceeded while executing an HTTP request. Fortunately, there is a solution to this problem.

The Error

The error message you might encounter looks like this:

ERROR: jakarta.ws.rs.ProcessingException: The timeout period of 30000ms has been exceeded while executing

This error indicates that an HTTP request took longer to complete than the specified timeout period (in this case, 30000 milliseconds or 30 seconds).

The Solution

To resolve this issue and adjust the timeout settings for your HTTP client in Jakarta WS RS, you can create a custom HttpClientOptions provider. This allows you to configure the timeout values according to your requirements.

Here’s the code for creating a custom HttpClientOptions provider:

package net.distributedsourcing.service;

import io.vertx.core.http.HttpClientOptions;
import jakarta.ws.rs.ext.ContextResolver;
import jakarta.ws.rs.ext.Provider;

@Provider
public class CustomHttpClientOptions implements ContextResolver<HttpClientOptions> {

    @Override
    public HttpClientOptions getContext(Class<?> arg0) {
        HttpClientOptions options = new HttpClientOptions();

        // Configure your desired timeout values here
        options.setIdleTimeout(90);
        options.setConnectTimeout(90);
        options.setReadIdleTimeout(90);
        options.setSslHandshakeTimeout(90);
        options.setTcpUserTimeout(90);
        options.setWriteIdleTimeout(90);

        return options;
    }
}

In this code, we create a custom ContextResolver that provides a customized HttpClientOptions object. You can adjust the timeout values in the getContext method according to your specific needs. Setting these timeout values to an appropriate duration can help prevent timeout errors in your Jakarta WS RS application.

Conclusion

By creating a custom HttpClientOptions provider and adjusting the timeout settings, you can effectively resolve the Jakarta WS RS ProcessingException timeout error. This allows you to fine-tune your application’s HTTP client behavior and avoid timeouts during HTTP requests.

Categorie
Senza categoria

[Solved] Fix errore apertura Sicurezza di Windows in Windows 11 #workaround

Aggiorni a Windows 11 e l’app Sicurezza di Windows sembra non presente nel sistema. Provi ad aprire l’app da “Privacy” > “Sicurezza di Windows”

e riceve l’errore “Avrai bisogno di una nuova app per aprire questo file windowsdefender”… cosa sta succedendo?

Microsoft sta ancora analizzando il problema, ma in attesa di un fix “ufficiale” puoi risolvere facilmente con il #workaround:

  • Apri PowerShell da amministratore (o il nuovo Windows Terminal preinstallato).
  • Esegui il comando Get-AppxPackage Microsoft.SecHealthUI -AllUsers | Reset-AppxPackage e dai invio.
  • Ora l’applicazione è nuopvamente raggiungibile. Semplice no?

Categorie
Senza categoria

Mic and Cam off by default in Google Meet

A couple of weeks ago, I was in a meeting. We focused everybody on the slide deck the Client was presenting and everybody had their mic and cam turned off. Well, everybody but me 🤦‍♂️

A couple of minutes in and some colleagues notified me that my camera was on and I was messing with the presentation.

I turned off the damn thing; I apologized, and I moved on. It was a malfunction. Shit happens and nobody remembered it 5 minutes later.

I looked for a solution to start every Google Meet call with my camera and my mic off and a Google Search later, I found Hangremote

https://chrome.google.com/webstore/detail/hangremote/naabbdmohmekdgecllphidjiaobnekcc

The extension is open source, the source code is on GitHub, and it implements two simple functions from Google’s Hangout:

popup

You can manage the most important buttons and you can check the two options: “No microphone at start” and “No camera at start”.

To test it, open a simple meeting page and see! You’ll have no a camera preview but the red button!!!!

Now all my meetings start with no camera and no mic.

Use it and don’t freak out anymore.

Categorie
Senza categoria

Docker: Share Docker Images Without Registry

3 min read

The ideal docker work flow for transferring docker images is through docker registry. This is the simplest way and we need 2 commands

  • YOU push the image to docker registry using docker push command
  • OTHERS pull the image using docker pull command.

However there might be a situation wherein we cannot use docker registry to transfer docker image to production. Say for example the production systems does not have access to non-production servers where registry is hosted, or during development we want to test the docker image quickly.

In such situations, we can transfer the docker image from one machine to another by exporting the image as a .tar file.

SAVE a docker image

Save the docker image is simple as using docker save command.

docker save --output saved-image.tar my-image:latest

Alternatively, we can also use redirection to a file.

docker save my-image:latest > saved-image.tar

Both commands will create a “saved-image.tar” in current directory.

TRANSFER a docker image

This is up to you, You can share the .tar file to target using any of the file transfer protocols like FTP, SCP, HTTP…

LOAD a docker image

Now you have the .tar file in the target machine, and a working docker version on it. Login to target machine and LOAD the image into local registry using docker load command.

docker load --input saved-image.tar

Alternatively, we can also use redirection from a file.

docker load < saved-image.tar

Last but not the least, Verify that the image is available on target machine by executing docker images command.

References

Here the Docker Official documentation for docker save and docker load commands.

Categorie
Programmazione Sicurezza

API Security

Network growing need for a more secure network, and that need is growing infinitely right now. Lots of data have been passed over the WEB, and some of them are extremely sensitive.

image: https://www.seobility.net

Once a week we can ear about a company getting hacked, thousand of sensitive data exposed, a risk to the reputation of the company.

API are an integral business strategy across industries and doesn’t appear to slow down. Each API is different, and it is difficult to prevent all vulnerabilities. As you can simply understand, an API used to gather information doesn’t need the same precaution requested for an API that’s sending a sensitive medical data across the network. And so? The answer is worst-case scenario.

First of all, we want to ensure that you authenticate the web server before any info has been transferred. Authentication and authorization are used together but are not the same thing:

  • We use Authentication to truly determine the identity of an end-user; we can use username and a password, certificates, hardware keys, etc
  • Authorization control access and determinate what resources or data the identified user has access to.

Many attacks might happen, many methods and targets, so let’s see vulnerabilities by target area:

  • Network (DDOS)
  • Operating System and Driver
  • Application layer (Session hijacking)
  • API (injection attacks, incomplete access control)

And now a check-list to implement a secure API:

  • Use Encryption to hide the information from those who may not view it.
  • Use SSL to encrypt the http message.
  • Signatures are used to ensure that API requests, or responses, haven’t been hacked within transit.
  • The API Gateway is a core piece of the infrastructure that enforces API security
  • Create Quotas; with quotas request we protect API from change behaviour activities (If a user calls the API once a minute, it is difficult that you will receive thousand requests per second)
  • Use a sniffer to analyze the call home traffic
  • Add some security scans to new or existing functional tests.

Categorie
Linux

Guida intergalattica per Repository Git

Git rappresenta uno standard per gestire il versioning del codice sorgente (SOLO IL CODICE SORGENTE 🤣), per versatilità e semplicità.

Git è un SCM distribuito, non c’è un solo server centrale con l’unica versione ufficiale ma ad ogni clone creiamo un repository collegato con tanto di history dei commit.

git clone <http://…>

Ogni modifica è dichiarata al tramite il comando commit che si occupa di tracciare in un pacchetto (o versione) tutti i file presenti nello stage in quel momento, con un messaggio che lo rende facilmente identificabile nella history.

git commit -m “messaggio”

first of all… GITIGNORE –> https://www.gitignore.io/

git flow

Esistono tre luoghi in cui un file può essere: l’albero, l’indice e la copia di lavoro. Quando si aggiunge un file a una cartella, lo si aggiunge alla copia di lavoro. Quando fai qualcosa come git add file lo aggiungi all’indice. E quando lo commetti, lo aggiungi all’albero. Probabilmente ti aiuterà a conoscere i tre flag più comuni in git reset:

git reset [- <mode> ] [ <commit> ]

Questo modulo reimposta la diramazione attuale su <commit> e eventualmente aggiorna l’indice (reimpostandolo all’albero di <commit> ) e l’albero di lavoro in base a <mode> , che deve essere uno dei seguenti:
–soft Non tocca affatto il file indice né l’albero di lavoro (ma reimposta la testa su <commit> , proprio come fanno tutte le modalità). Questo lascia tutti i tuoi file modificati “Modifiche da impegnare”, come direbbe lo stato di git.

–misto Reimposta l’indice ma non l’albero di lavoro (cioè, i file modificati sono conservati ma non contrassegnati per il commit) e riporta ciò che non è stato aggiornato. Questa è l’azione predefinita.

–difficile Reimposta l’indice e l’albero di lavoro. Qualsiasi modifica ai file tracciati nell’albero di lavoro poiché <commit> viene scartata.

Ora, quando fai qualcosa come git reset HEAD – ciò che stai facendo è git reset HEAD --mixed e “resetterà” l’indice allo stato in cui era prima di iniziare ad aggiungere file / aggiungere modifiche all’indice (via git add ) In questo caso, la copia di lavoro e l’indice (o la fase di staging) erano sincronizzati, ma dopo il ripristino l’utente HEAD e l’indice erano sincronizzati.

git rm d’altra parte rimuove un file dalla directory di lavoro e dall’indice e quando si esegue il commit, il file viene rimosso dall’albero. git rm --cached tuttavia rimuove il file dal solo indice e lo mantiene nella copia di lavoro. Questo è l’esatto opposto di git add file In questo caso, hai fatto l’indice per essere diverso dal HEAD e il lavoro, in esso che il HEAD ha la versione precedentemente impegnata del file, la copia di lavoro ha avuto la modifica di las if any o content da HEAD del file e hai rimosso il file dall’indice. Un commit ora sincronizzerà l’indice e l’albero e il file verrà rimosso.

.gitignore does not work

Cambiato il .gitignore ma non vedi le modifiche? Piccola magia

git ls-files –deleted -z | git update-index –assume-unchanged -z –stdin

Git Stash ??

Il nostro lavoro potrebbe dover subire dei rallentamenti o Change Request improvvise e Git ci permette di gestire diversi “Branch” proprio per poter condurre contemporaneamente versioni diverse dello stesso applicativo. Per garantire la consistenza dei dati ci viene impedito di cambiare branch se abbiamo delle modifiche “in canna”, se il lavoro è incompleto, una commit potrebbe rendere lo stato inconsistente ma non vogliamo perdere le modifiche fatte… che fare? Possiamo utilizzare il comando stash

git stash

Ora, “messe da parte” le modifiche fatte al codice, si può cambiare stato (commit o branch) per poi sfruttare la pop per ripristinarli.

git stash
git pull
git stash pop

Official –> https://git-scm.com/docs/git-stash

Rename a Branch

If you want to rename a branch while pointed to any branch, do:

git branch -m <oldname> <newname>

If you want to rename the current branch, you can do:

git branch -m <newname>

Git Branch simple

in the new version of git you can use

git checkout <branch>

this simply checkout in a new local branch if does not exists