Community Code Library

Discover Community Snippets

Explore a vast collection of code snippets shared by users.

Languages:
43 snippets found
node logo
javascript
5/21/2026

Production REST Client — GET / POST / PUT / DELETE + Retry & Timeout

Mattia Cerioni
(async () => {
  // dummy data
  const BASE_URL = "https://jsonplaceholder.typicode.com";
  const API_KEY  = "demo_key_123";

  // helper 
  async function apiFetch(endpoint, options = {}, retries = 3) {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 5000);

    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        const res = await fetch(`${BASE_URL}${endpoint}`, {
          ...options,
          signal: controller.signal,
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${API_KEY}`,
            "Accept": "application/json",
            ...options.headers,
          },
        });

        clearTimeout(timeout);

        if (!res.ok) {
          const error = await res.json().catch(() => ({ message: res.statusText }));
          throw new Error(`HTTP ${res.status}: ${error.message}`);
        }

        return await res.json();

      } catch (err) {
        const isLast = attempt === retries;
        if (err.name === "AbortError") throw new Error("Request timed out");
        if (isLast) throw err;
        console.log(`!Attempt ${attempt} failed, retrying in ${attempt}s...`);
        await new Promise(r => setTimeout(r, 1000 * attempt));
      }
    }
  }

  // req's
  try {
    // 1. GET list
    console.log("── GET users");
    const users = await apiFetch("/users?_limit=3");
    users.forEach(u => console.log(`  ${u.id}. ${u.name} <${u.email}>`));

    // 2. GET single
    console.log("\n── GET single");
    const post = await apiFetch("/posts/1");
    console.log(`  Title : ${post.title}`);
    console.log(`  Body  : ${post.body.slice(0, 60)}...`);

    // 3. POST create
    console.log("\n── POST create");
    const created = await apiFetch("/posts", {
      method: "POST",
      body: JSON.stringify({ title: "My Post", body: "Hello World", userId: 1 }),
    });
    console.log(`  Created ID : ${created.id}`);
    console.log(`  Title      : ${created.title}`);

    // 4. PUT update
    console.log("\n── PUT update");
    const updated = await apiFetch("/posts/1", {
      method: "PUT",
      body: JSON.stringify({ id: 1, title: "Updated Title", body: "New body", userId: 1 }),
    });
    console.log(`  New title : ${updated.title}`);

    // 5. DELETE
    console.log("\n── DELETE post");
    await apiFetch("/posts/1", { method: "DELETE" });
    console.log(`  Deleted successfully`);

    // 6. Parallel fetch
    console.log("\n── Parallel fetch");
    const [comments, todos] = await Promise.all([
      apiFetch("/comments?_limit=2"),
      apiFetch("/todos?_limit=2"),
    ]);
    console.log(`  Comments : ${comments.map(c => c.email).join(", ")}`);
    console.log(`  Todos    : ${todos.map(t => `[${t.completed ? "x" : " "}] ${t.title.slice(0, 30)}`).join("\n             ")}`);

  } catch (err) {
    console.error("✖ Error:", err.message);
  }
})();
c logo
c
3/1/2026

Appunti Puntatori e Memoria Dinamica

MATTIA CERIONI
/*appunti sui puntatori*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int array[4]; //4 x 4 byte
	printf("%lu \r\n", sizeof(array)); //%lu long integer
	                                  //(senza val < 0)

    /*------------------------------------------------------------------------*/

	//preallocazione di memoria da usare in elaborazione
	int *p1 = malloc(sizeof(*p1)); //inserisco quanta memoria sto allocando (con malloc) per p1
	int *p2 = calloc(1, sizeof(*p2)); //num celle e dimensione ogni cella e uso p2 come array
	*p1 = 10;
	*p2 = 10;
	printf("%d %d", *p1, *p2);
	
	/*------------------------------------------------------------------------*/

	int *ptrInt = (int*)array; //creo un puntatore all'array
	int *ptr = (int*)calloc(4, sizeof(*ptrInt)); //alloco la memoria
    
    printf("%lu", sizeof(*ptrInt));
    printf("%lu", sizeof(array));

    /*------------------------------------------------------------------------*/
    
    *ptrInt = array[0]; //assegnazione in memoria ad un array di interi
    ptrInt[1] = 4;  //ptrInt++ e inserisco il valore 4 
    ptrInt[2] = 6; //ptrInt++ e inserisco il valore 6
                  //(accedo alla cella dell'indirizzo)
    
    /*------------------------------------------------------------------------*/
    
    int *arr1, *arr2;
    int grandezza = 5; //da prendere in input per elaborazione
    int n = 1;
    
    arr1 = (int*)malloc(n * sizeof(int));
    if(arr1 = NULL)
    {
        //allocazione fallita
    }
    
    //popolamento
    for(int i = 0; i < grandezza; i++)
        arr1[i] = i;
    
    free(arr1); //deallocazione della memoria con parametro puntatore
    
	return 0;
}
mono logo
c#
12/24/2025

wordgameCsharp

StanleyAnyas
using System;
using System.Linq.Expressions;

public class Wordle
{
    public void Run()
    {
        string[] words = File.ReadAllLines("words.txt");
        Random rand = new Random();
        String wordToGuess = words[rand.Next(words.Length)].ToUpper();
        int maxAttempt = 5;
        // Console.WriteLine(words.Length);
        System.Console.WriteLine("Guess the word");
        Console.WriteLine($"the word has {wordToGuess.Length} letters");
        String globalHint = new string('_', wordToGuess.Length);
        String hint = ShowHint(wordToGuess, globalHint);
        Console.WriteLine(hint);
        globalHint = hint;
        Console.WriteLine("Goodluck! You can ask for help with ?h");
        int addGuess = 1;
        while(maxAttempt > 0)
        {
            String userGuess = Console.ReadLine()?.ToUpper()?.Trim() ?? "";
            if(userGuess == "?H")
            {
                if(maxAttempt < 2 || addGuess >= wordToGuess.Length)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    System.Console.WriteLine("You dont have enough attempts for help");
                    Console.ResetColor();
                    continue;
                }
                else
                {
                    String hint2 = ShowHint(wordToGuess, globalHint, addGuess);
                    Console.WriteLine(hint2);
                    globalHint = hint2;
                    addGuess++;
                    maxAttempt--;
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"You now have {maxAttempt} left");
                    Console.ResetColor();
                    continue;
                }
                
            }
            bool[] res = CheckWord(wordToGuess, userGuess);
            String toShow = "";
            for(int i = 0; i < wordToGuess.Length; i++)
            {
                if (res[i])
                {
                    toShow += userGuess[i];
                }
                else
                {
                    toShow += "_";
                }
            }
            if(toShow == wordToGuess)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Congratulations!! you got it");
                Console.WriteLine(wordToGuess);
                Console.ResetColor();
                break;
            }
            else
            {
                maxAttempt--;
                Console.WriteLine(toShow);
                if(maxAttempt <= 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over! You have exhausted your attempts");
                    Console.ResetColor();
                    break;
                }
                Console.WriteLine($"you have {maxAttempt} left");
            }
        }
    }

    static bool[] CheckWord(string wordToGuess, string userGuess)
    {
        int len = wordToGuess.Length;
        bool[] res = new bool[len];

        int minLen = Math.Min(wordToGuess.Length, userGuess.Length);

        for (int i = 0; i < minLen; i++)
        {
            res[i] = wordToGuess[i] == userGuess[i];
        }

        return res;
    }

    static String ShowHint(string wordToGuess, string prevWord, int add = 2)
    {
        char[] prevWordArr = prevWord.ToCharArray();
        int length = wordToGuess.Length;
        char[] hint = new char[length];
        hint = prevWordArr;

        Random rnd = new Random();
        HashSet<int> revealedPositions = new HashSet<int>();
        while (revealedPositions.Count < add)
        {
            int pos = rnd.Next(length);
            if(prevWordArr[pos] != '_' && prevWordArr.Length == 0)
            {
                continue;
            }
            revealedPositions.Add(pos);
        }

        foreach (int pos in revealedPositions)
        {
            hint[pos] = wordToGuess[pos];
        }

        return new string(hint);
    }
}
gcc logo
c++
12/19/2025

liste cpp

Simone
#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
#define DIM 20
using namespace std;

struct s_nodo
{
	int num;
	s_nodo *pnext;
};

s_nodo* caricalista();
void stampalista(s_nodo *ptesta);
s_nodo* fusione(s_nodo *ptesta);
s_nodo* rovescialista(s_nodo *ptesta);

int main()
{
	srand(time(NULL));
	s_nodo *ptesta=new s_nodo;
	s_nodo *ptesta2=new s_nodo;
	
	ptesta=NULL;
	ptesta2=NULL;
	
	ptesta=caricalista();
	cout<<"Lista: "<<endl;
	stampalista(ptesta);
	ptesta2=fusione(ptesta);
	cout<<endl;
	cout<<"Lista >= 60: "<<endl;
	stampalista(ptesta2);
	
	ptesta=rovescialista(ptesta);
	cout<<"Lista invertita: "<<endl;
	stampalista(ptesta);
	ptesta2=rovescialista(ptesta2);
	cout<<"Lista >= 60 invertita: "<<endl;
	stampalista(ptesta2);
	

	
	return 0;
}

s_nodo* caricalista()
{
	s_nodo *ptesta=NULL;
	s_nodo *pprev=NULL;
	
	for(int i=0;i<DIM;i++)
	{
		s_nodo *ptemp=new s_nodo;
		ptemp->num=rand()%91+10;
		ptemp->pnext=NULL;
		if(pprev!=NULL)
		{
			pprev->pnext=ptemp;
		}
		else
		{
			ptesta=ptemp;
		}
		pprev=ptemp;
	}
	return ptesta;
}

void stampalista(s_nodo *ptesta)
{
	while(ptesta!=NULL)
	{
		cout<<"Numero: "<<ptesta->num<<endl;
		ptesta=ptesta->pnext;
	}
	cout<<endl;
}

s_nodo* fusione(s_nodo *ptesta)
{
    s_nodo *ptesta2=NULL;
    s_nodo *pprev=NULL;
    s_nodo *ptemp=ptesta;

    while(ptemp!=NULL)
    {
        if(ptemp->num>=60)
        {
            s_nodo *ptemp2=new s_nodo;
            ptemp2->num=ptemp->num;
            ptemp2->pnext=NULL;
            
            if(pprev != NULL)
            {
            	pprev->pnext=ptemp2;
			}
            else
            {
            	ptesta2=ptemp2;
			}
            pprev=ptemp2;
        }
        ptemp=ptemp->pnext;
    }

    return ptesta2;
}

s_nodo* rovescialista(s_nodo *ptesta)
{
	s_nodo *pprev=NULL;
	s_nodo *curr=ptesta;
    s_nodo *next=NULL;

    while(curr!=NULL)
    {
        next=curr->pnext;
        curr->pnext=pprev;
        pprev=curr;       
        curr=next;       
    }

    return pprev;
}
sqlite logo
sqlite
12/11/2025

Query Azienda

Mattia Cerioni
SELECT impiegati.nome, impiegati.cognome 
FROM impiegati
JOIN assegnazioni ON impiegati.id = assegnazioni.id
JOIN progetti ON a.idDipartimento = progetti.idDipartimento
WHERE progetti.budget > (
    SELECT AVG(progetti.budget) 
    FROM progetti
);
--------------------------------------------------------------------------------
SELECT dipartimenti.nome, COUNT(progetti.id) AS numProgetti
FROM progetti
JOIN dipartimenti ON progetti.idDipartimento = dipartimenti.id
GROUP BY d.nome
HAVING numProgetti > 3;
--------------------------------------------------------------------------------
SELECT impiegati.nome, impiegati.cognome 
FROM impiegati
JOIN assegnazioni ON impiegati.id = assegnazioni.idImpiegato
GROUP BY assegnazioni.idImpiegato
HAVING COUNT(assegnazioni.idProgetto) >= 2;
--------------------------------------------------------------------------------
SELECT * FROM impiegati AS manager
JOIN impiegati ON manager.id = impiegati.idManager
GROUP BY impiegati.idManager 
HAVING AVG(impiegati.stipendio) > 2500;
--------------------------------------------------------------------------------
SELECT * FROM progetti
WHERE progetti.id NOT IN (
    SELECT tasks.idProgetto FROM tasks
    WHERE tasks.priorità = 'Alta'
);
--------------------------------------------------------------------------------
SELECT dipartimenti.nome, SUM(assegnazioni.oreSettimanali), 
FROM assegnazioni
JOIN progetti ON assegnazioni.idProgetto = progetti.id
JOIN dipartimenti ON progetti.idDipartimento = dipartimenti.id
GROUP BY dipartimenti.nome;
--------------------------------------------------------------------------------
SELECT *
FROM impiegati
JOIN assegnazioni ON impiegati.id = assegnazioni.idImpiegato
JOIN progetti ON assegnazioni.idProgetto = progetti.id
WHERE impiegati.idDipartimento = progetti.idDipartimento;
--------------------------------------------------------------------------------
SELECT progetti.id, progetti.titolo
FROM progetti
JOIN (
    SELECT tasks.idProgetto, COUNT(tasks.id) AS numTask 
    FROM tasks
    GROUP BY tasks.idProgetto;
) AS tasksPerProgetti ON progetti.idProgetto = tasksPerProgetti.idProgetto
WHERE tasksPerProgetti.numTask = (
    SELECT MAX(num)
    FROM (
        SELECT COUNT(*) as num
        FROM tasks
        GROUP BY tasks.idProgetto
    )
);