Skip to main content
Loading...

More JavaScript Posts

function filePath(file){
  let folders = file.getParents();
  const parents = [];

  function makePathString(folderArray){
    let path = "";
    folderArray.forEach((folder)=>{
      path += "/" + folder.getName();
    });
    return path;
  }
  
  while (folders.hasNext()) {
    const folder = folders.next(); //This should hopefully remove that folder from the iterator
    parents.unshift(folder);
  }

  return makePathString(parents);
}

function myFunction() {
  const myEmail = Session.getEffectiveUser().getEmail();
  Logger.log("My email is " + myEmail);
  // Log the name of every file in the user's Drive.
  var fileIterator = DriveApp.getFiles();
  const files = []; //List of [File, size] entries
  const filesMaxSize = 10;
  while (fileIterator.hasNext()) {
    var file = fileIterator.next();

    const owner = file.getOwner();

    //Only files I own
    if((!(owner)) || (!(owner.getEmail)) || owner.getEmail() != myEmail){
      continue;
    }

    const entry = [file, file.getSize()];

    function slideUp(arr, index){
      //Let's keep sliding it up so we don't have to sort it at the end.
      for(let i = index; i > 0; --i){ //Stops at 1
        const nextFile = arr[i-1];

        if(nextFile[1] > entry[1]){
          break;
        }else{
          //Swap with the next file to slide the file up
          const temp = arr[i];
          arr[i] = arr[i - 1];
          arr[i - 1] = temp;
        }
      }
    }

    if(files.length < filesMaxSize){
      files.push(entry);

      slideUp(files, files.length - 1);
    }else{
      if(entry[1] > files[files.length - 1][1]){ //If it's bigger than the smallest file in the list.
        files[files.length - 1] = entry;  //Replace the smallest file

        slideUp(files, files.length - 1); //Slide it up
      }
    }
  }

  for(let i = 0; i < filesMaxSize; ++i){
    const file = files[i][0];
    const size = files[i][1];
    Logger.log(size + "\t" + filePath(file) + "/" + file.getName() + "\t" + file.getOwner().getName());
  }
}
class Graph {
  constructor(directed = true) {
    this.directed = directed;
    this.nodes = [];
    this.edges = new Map();
  }

  addNode(key, value = key) {
    this.nodes.push({ key, value });
  }

  addEdge(a, b, weight) {
    this.edges.set(JSON.stringify([a, b]), { a, b, weight });
    if (!this.directed)
      this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
  }

  removeNode(key) {
    this.nodes = this.nodes.filter(n => n.key !== key);
    [...this.edges.values()].forEach(({ a, b }) => {
      if (a === key || b === key) this.edges.delete(JSON.stringify([a, b]));
    });
  }

  removeEdge(a, b) {
    this.edges.delete(JSON.stringify([a, b]));
    if (!this.directed) this.edges.delete(JSON.stringify([b, a]));
  }

  findNode(key) {
    return this.nodes.find(x => x.key === key);
  }

  hasEdge(a, b) {
    return this.edges.has(JSON.stringify([a, b]));
  }

  setEdgeWeight(a, b, weight) {
    this.edges.set(JSON.stringify([a, b]), { a, b, weight });
    if (!this.directed)
      this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
  }

  getEdgeWeight(a, b) {
    return this.edges.get(JSON.stringify([a, b])).weight;
  }

  adjacent(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (a === key) acc.push(b);
      return acc;
    }, []);
  }

  indegree(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (b === key) acc++;
      return acc;
    }, 0);
  }

  outdegree(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (a === key) acc++;
      return acc;
    }, 0);
  }
}


const g = new Graph();

g.addNode('a');
g.addNode('b');
g.addNode('c');
g.addNode('d');

g.addEdge('a', 'c');
g.addEdge('b', 'c');
g.addEdge('c', 'b');
g.addEdge('d', 'a');

g.nodes.map(x => x.value);  // ['a', 'b', 'c', 'd']
[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['a => c', 'b => c', 'c => b', 'd => a']

g.adjacent('c');            // ['b']

g.indegree('c');            // 2
g.outdegree('c');           // 1

g.hasEdge('d', 'a');        // true
g.hasEdge('a', 'd');        // false

g.removeEdge('c', 'b');

[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['a => c', 'b => c', 'd => a']

g.removeNode('c');

g.nodes.map(x => x.value);  // ['a', 'b', 'd']
[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['d => a']

g.setEdgeWeight('d', 'a', 5);
g.getEdgeWeight('d', 'a');  // 5
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'YOUR_BOT_TOKEN';

// When the bot is ready, log a message to the console
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// When a user sends a message, check if they are authenticated
client.on('message', async (msg) => {
  if (!msg.author.bot && !msg.author.authenticated) {
    const filter = (m) => m.author.id === msg.author.id;
    const collector = msg.channel.createMessageCollector(filter, { time: 15000 });

    // Send an authentication message to the user
    msg.author.send('Please authenticate yourself by clicking this link: ' + generateAuthURL(msg.author.id));

    collector.on('collect', async (m) => {
      // Check if the message contains the authentication code
      if (m.content.startsWith('!auth ')) {
        const code = m.content.slice(6);
        const { access_token } = await getAccessToken(code);

        // Set the user's authenticated status and access token
        msg.author.authenticated = true;
        msg.author.access_token = access_token;
        collector.stop();
      }
    });

    collector.on('end', () => {
      if (!msg.author.authenticated) {
        msg.author.send('Authentication timed out.');
      }
    });
  }
});

// Generate an authentication URL for the user
function generateAuthURL(userId) {
  const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
  const scopes = 'identify';
  const clientID = 'YOUR_CLIENT_ID';

  return `https://discord.com/api/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=code&scope=${scopes}&state=${userId}`;
}

// Exchange the authorization code for an access token
async function getAccessToken(code) {
  const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
  const clientID = 'YOUR_CLIENT_ID';
  const clientSecret = 'YOUR_CLIENT_SECRET';

  const res = await fetch('https://discord.com/api/oauth2/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `grant_type=authorization_code&code=${code}&redirect_uri=${redirectURI}&client_id=${clientID}&client_secret=${clientSecret}`,
  });

  return await res.json();
}

client.login(token);