Tuesday, September 10, 2024

Language detection API

curl 'https://platform.text.com/api/detect_language' -X POST -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.7,ro;q=0.3' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Referer: https://platform.text.com/tools/language-detector' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Origin: https://platform.text.com' -H 'DNT: 1' -H 'Sec-GPC: 1' -H 'Connection: keep-alive' -H 'Cookie: metrics_session=true' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-origin' -H 'Priority: u=0' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'TE: trailers' --data-raw $'{"text":"Das ist ein Text.","threshold":0.7,"clean_up_whitespaces":true}'

curl 'https://api.openl.io/tools/detect-language' -X POST -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.7,ro;q=0.3' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Content-Type: application/json' -H 'Origin: https://openl.io' -H 'DNT: 1' -H 'Sec-GPC: 1' -H 'Connection: keep-alive' -H 'Referer: https://openl.io/' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-site' -H 'Priority: u=0' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'TE: trailers' --data-raw $'{"role":"free","text":"Das ist ein Text."}' # with daily limit

1‍. fastText

fastText is a tool for easily learning about words and organizing sentences. Anybody can use fastText, including professionals, students, and people who aren't experts. fastText concentrates on arranging text and learning about words.

It's been developed so people can quickly try different methods and improve them without needing special equipment. fastText can process over one billion words very quickly on any multicore processor in a few minutes. It has pre-made models learned from Wikipedia in over 157 different languages.

‍2. lingua-py

This is a python open source library for language detection. A total of 75 languages can be detected.

‍3. LangDetect

This library is a Python version of Google's language-detection library, capable of identifying more than 50 languages. Developed by Nakatani Shuyo at Cybozu Labs, Inc.

4. langid.py

Langid.py is a simple language identification tool that is based on the Python programming language.

5. polyglot

Polyglot is a natural language pipeline that supports massive multilingual applications. It includes language identification as one of its components.

‍6. CLD2 (Compact Language Detector 2)

CLD2 is a library for language detection, optimized for speed and accuracy. It's developed by Google and used in various Google products.

 

 

Wednesday, September 4, 2024

Boilerplate Mongoose MongoDB

MyApp.js

require('dotenv').config();
// const MongoClient = require("mongodb").MongoClient;
const mongoose = require('mongoose');
const uri = process.env['MONGO_URI'];
// mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
// mongoose.connection.on('open', function (ref) {
//     console.log('Connected to mongo server.');

// mongoose.connection.db.listCollections().toArray(function (err, names) {
//         console.log(names);
//     });
// })
/// create a connection to the DB    
mongoose.set('strictQuery', true);
mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;

// Check DB Connection
db.once('open', () => {
  (async () => {
    const data = await mongoose.connection.db.admin().command({
      listDatabases: 1,
    });
    console.log(data);
  })();
  console.log('Connected to MongoDB');
});

// Check for DB errors
db.on('error', (err) => {
  console.log('DB Connection errors', err);
});
// dbs = mongoose.connection.db.listCollections().toArray()
// console.log(uri, mongoose.connection.readyState, dbs);

// const mongo_username = process.env["MONGO_USERNAME"];
// const mongo_password = process.env["MONGO_PASSWORD"];
// const uri = `mongodb+srv://${mongo_username}:${mongo_password}@cluster0-zrtwi.gcp.mongodb.net/crmdb?retryWrites=true&w=majority`;
// const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// collection = client.db("sample_training").collection("people");
// console.log(collection)
// mongooseclient = mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

// const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// baza = mongooseclient.then((db) => db.db("sample_training"));
// const collections = client.db('sample_training').collection('people');
// const databases = db.listCollections().toArray();
// console.log('current db', baza)

// 2. Create a Model
const Schema = mongoose.Schema;

const personSchema = new Schema({
  name:  {type: String, required: true},
  age: Number,
  favoriteFoods: [String]
});

const Person = mongoose.model('Person', personSchema);

// let Person;

const createAndSavePerson = (done) => {
  done(null /*, data*/);
};

const createManyPeople = (arrayOfPeople, done) => {
  done(null /*, data*/);
};

const findPeopleByName = (personName, done) => {
  done(null /*, data*/);
};

const findOneByFood = (food, done) => {
  done(null /*, data*/);
};

const findPersonById = (personId, done) => {
  done(null /*, data*/);
};

const findEditThenSave = (personId, done) => {
  const foodToAdd = "hamburger";

  done(null /*, data*/);
};

const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  done(null /*, data*/);
};

const removeById = (personId, done) => {
  done(null /*, data*/);
};

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";

  done(null /*, data*/);
};

const queryChain = (done) => {
  const foodToSearch = "burrito";

  done(null /*, data*/);
};

/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

//----- **DO NOT EDIT BELOW THIS LINE** ----------------------------------

exports.PersonModel = Person;
exports.createAndSavePerson = createAndSavePerson;
exports.findPeopleByName = findPeopleByName;
exports.findOneByFood = findOneByFood;
exports.findPersonById = findPersonById;
exports.findEditThenSave = findEditThenSave;
exports.findAndUpdate = findAndUpdate;
exports.createManyPeople = createManyPeople;
exports.removeById = removeById;
exports.removeManyPeople = removeManyPeople;
exports.queryChain = queryChain;

/*
require('dotenv').config();


// 1. Install and Set Up Mongoose
const mongoose = require('mongoose');

const uri = process.env['MONGO_URI'];

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });


// 2. Create a Model
const Schema = mongoose.Schema;

const personSchema = new Schema({
  name:  {type: String, required: true},
  age: Number,
  favoriteFoods: [String]
});

const Person = mongoose.model('Person', personSchema);


// 3. Create and Save a Record of a Model
const createAndSavePerson = (done) => {
  var janeFonda = new Person({
    name: "Jane Fonda",
    age: 84,
    favoriteFoods: ["eggs", "fish", "fresh fruit"]
  });

  janeFonda.save(function(err, data) {
    if (err) return console.error(err);
    done(null, data)
  });
};


// 4. Create Many Records with model.create()
var arrayOfPeople = [
  {name: "Frankie", age: 74, favoriteFoods: ["Del Taco"]},
  {name: "Sol", age: 76, favoriteFoods: ["roast chicken"]},
  {name: "Robert", age: 78, favoriteFoods: ["wine"]}
];

const createManyPeople = (arrayOfPeople, done) => {
  Person.create(arrayOfPeople, function (err, people) {
    if (err) return console.log(err);
    done(null, people);
  });
};


// 5. Use model.find() to Search Your Database
const findPeopleByName = (personName, done) => {
  Person.find({name: personName}, function (err, personFound) {
    if (err) return console.log(err);
    done(null, personFound);
  });
};


// 6. Use model.findOne() to Return a Single Matching Document from Your Database
const findOneByFood = (food, done) => {
  Person.findOne({favoriteFoods: food}, function (err, data) {
    if (err) return console.log(err);
    done(null, data);
  });
};


// 7. Use model.findById() to Search Your Database By _id
const findPersonById = (personId, done) => {
  Person.findById(personId, function (err, data) {
    if (err) return console.log(err);
    done(null, data);
  });
};


// 8. Perform Classic Updates by Running Find, Edit, then Save
const findEditThenSave = (personId, done) => {
  const foodToAdd = 'hamburger';

  // .findById() method to find a person by _id with the parameter personId as search key.
  Person.findById(personId, (err, person) => {
    if(err) return console.log(err);

    // Array.push() method to add "hamburger" to the list of the person's favoriteFoods
    person.favoriteFoods.push(foodToAdd);

    // and inside the find callback - save() the updated Person.
    person.save((err, updatedPerson) => {
      if(err) return console.log(err);
      done(null, updatedPerson)
    })
  })
};


// 9. Perform New Updates on a Document Using model.findOneAndUpdate()
const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  Person.findOneAndUpdate({name: personName}, {age: ageToSet}, {new: true}, (err, updatedDoc) => {
    if(err) return console.log(err);
    done(null, updatedDoc);
  })
};


// 10. Delete One Document Using model.findByIdAndRemove
const removeById = (personId, done) => {
  Person.findByIdAndRemove(
    personId,
    (err, removedDoc) => {
      if(err) return console.log(err);
      done(null, removedDoc);
    }
  );
};


// 11. Delete Many Documents with model.remove()
const removeManyPeople = (done) => {
  const nameToRemove = "Mary";
  Person.remove({name: nameToRemove}, (err, response) => {
    if(err) return console.log(err);
    done(null, response);
  })
};


// 12. Chain Search Query Helpers to Narrow Search Results
const queryChain = (done) => {
  const foodToSearch = "burrito";

  Person.find({ favoriteFoods: foodToSearch })
  .sort({ name: 1 })
  .limit(2)
  .select({ age: 0 })
  .exec(function(err, data) {
    if(err) return console.log(err);
    done(null, data);
  });

};



/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

//----- **DO NOT EDIT BELOW THIS LINE** ----------------------------------

exports.PersonModel = Person;
exports.createAndSavePerson = createAndSavePerson;
exports.findPeopleByName = findPeopleByName;
exports.findOneByFood = findOneByFood;
exports.findPersonById = findPersonById;
exports.findEditThenSave = findEditThenSave;
exports.findAndUpdate = findAndUpdate;
exports.createManyPeople = createManyPeople;
exports.removeById = removeById;
exports.removeManyPeople = removeManyPeople;
exports.queryChain = queryChain;

*/

server.js

/********************************************
 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/

const express = require("express");
const app = express();
let mongoose;
try {
  mongoose = require("mongoose");
} catch (e) {
  console.log(e);
}
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");
const router = express.Router();

const enableCORS = function (req, res, next) {
  if (!process.env.DISABLE_XORIGIN) {
    const allowedOrigins = ["https://www.freecodecamp.org"];
    const origin = req.headers.origin;
    if (!process.env.XORIGIN_RESTRICT || allowedOrigins.indexOf(origin) > -1) {
      console.log(req.method);
      res.set({
        "Access-Control-Allow-Origin": origin,
        "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
        "Access-Control-Allow-Headers":
          "Origin, X-Requested-With, Content-Type, Accept",
      });
    }
  }
  next();
};

// global setting for safety timeouts to handle possible
// wrong callbacks that will never be called
const TIMEOUT = 10000;

app.use(bodyParser.urlencoded({ extended: "false" }));
app.use(bodyParser.json());

app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "views", "index.html"));
});

router.get("/file/*?", function (req, res, next) {
  if (req.params[0] === ".env") {
    return next({ status: 401, message: "ACCESS DENIED" });
  }
  fs.readFile(path.join(__dirname, req.params[0]), function (err, data) {
    if (err) {
      return next(err);
    }
    res.type("txt").send(data.toString());
  });
});

router.get("/is-mongoose-ok", function (req, res) {
  if (mongoose) {
    res.json({ isMongooseOk: !!mongoose.connection.readyState });
  } else {
    res.json({ isMongooseOk: false });
  }
});

const Person = require("./myApp.js").PersonModel;

router.use(function (req, res, next) {
  if (req.method !== "OPTIONS" && Person.modelName !== "Person") {
    return next({ message: "Person Model is not correct" });
  }
  next();
});

router.post("/mongoose-model", function (req, res, next) {
  // try to create a new instance based on their model
  // verify it's correctly defined in some way
  let p;
  p = new Person(req.body);
  res.json(p);
});

const createPerson = require("./myApp.js").createAndSavePerson;
router.get("/create-and-save-person", function (req, res, next) {
  // in case of incorrect function use wait timeout then respond
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  createPerson(function (err, data) {
    clearTimeout(t);
    if (err) {
      return next(err);
    }
    if (!data) {
      console.log("Missing `done()` argument");
      return next({ message: "Missing callback argument" });
    }
    Person.findById(data._id, function (err, pers) {
      if (err) {
        return next(err);
      }
      res.json(pers);
      pers.remove();
    });
  });
});

const createPeople = require("./myApp.js").createManyPeople;
router.post("/create-many-people", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    // in case of incorrect function use wait timeout then respond
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    createPeople(req.body, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      Person.find({}, function (err, pers) {
        if (err) {
          return next(err);
        }
        res.json(pers);
        Person.remove().exec();
      });
    });
  });
});

const findByName = require("./myApp.js").findPeopleByName;
router.post("/find-all-by-name", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  Person.create(req.body, function (err, pers) {
    if (err) {
      return next(err);
    }
    findByName(pers.name, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      res.json(data);
      Person.remove().exec();
    });
  });
});

const findByFood = require("./myApp.js").findOneByFood;
router.post("/find-one-by-food", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    findByFood(pers.favoriteFoods[0], function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      res.json(data);
      p.remove();
    });
  });
});

const findById = require("./myApp.js").findPersonById;
router.get("/find-by-id", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person({ name: "test", age: 0, favoriteFoods: ["none"] });
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    findById(pers._id, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      res.json(data);
      p.remove();
    });
  });
});

const findEdit = require("./myApp.js").findEditThenSave;
router.post("/find-edit-save", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    try {
      findEdit(pers._id, function (err, data) {
        clearTimeout(t);
        if (err) {
          return next(err);
        }
        if (!data) {
          console.log("Missing `done()` argument");
          return next({ message: "Missing callback argument" });
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

const update = require("./myApp.js").findAndUpdate;
router.post("/find-one-update", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    try {
      update(pers.name, function (err, data) {
        clearTimeout(t);
        if (err) {
          return next(err);
        }
        if (!data) {
          console.log("Missing `done()` argument");
          return next({ message: "Missing callback argument" });
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

const removeOne = require("./myApp.js").removeById;
router.post("/remove-one-person", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    let p = new Person(req.body);
    p.save(function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        removeOne(pers._id, function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          console.log(data);
          Person.count(function (err, cnt) {
            if (err) {
              return next(err);
            }
            data = data.toObject();
            data.count = cnt;
            console.log(data);
            res.json(data);
          });
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

const removeMany = require("./myApp.js").removeManyPeople;
router.post("/remove-many-people", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    Person.create(req.body, function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        removeMany(function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          Person.count(function (err, cnt) {
            if (err) {
              return next(err);
            }
            if (data.ok === undefined) {
              // for mongoose v4
              try {
                data = JSON.parse(data);
              } catch (e) {
                console.log(e);
                return next(e);
              }
            }
            res.json({
              n: data.n,
              count: cnt,
              ok: data.ok,
            });
          });
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

const chain = require("./myApp.js").queryChain;
router.post("/query-tools", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    Person.create(req.body, function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        chain(function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          res.json(data);
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

app.use("/_api", enableCORS, router);

// Error handler
app.use(function (err, req, res, next) {
  if (err) {
    res
      .status(err.status || 500)
      .type("txt")
      .send(err.message || "SERVER ERROR");
  }
});

// Unmatched routes handler
app.use(function (req, res) {
  if (req.method.toLowerCase() === "options") {
    res.end();
  } else {
    res.status(404).type("txt").send("Not Found");
  }
});

const listener = app.listen(process.env.PORT || 3000, function () {
  console.log("Your app is listening on port " + listener.address().port);
});

/********************************************
 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/

MongoDB and Mongoose Challenges

This is the boilerplate for the MongoDB and Mongoose lessons. Instructions for completing these lessons start at https://www.freecodecamp.org/learn/apis-and-microservices/mongodb-and-mongoose/

package.json

{
  "name": "fcc-mongo-mongoose-challenges",
  "version": "0.0.1",
  "description": "A boilerplate project",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "dotenv": "^8.2.0",
    "express": "^4.12.4",
    "mongodb": "^6.1.0",
    "mongoose": "^5.11.15"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/freeCodeCamp/boilerplate-mongomongoose.git"
  },
  "keywords": [
    "node",
    "mongoose",
    "express"
  ],
  "license": "MIT"
}
sample.env

MONGO_URI= 

views/index.html

<!-- This is a static file -->
<!-- served from your routes in server.js -->

<!-- You might want to try something fancier: -->
<!-- html/nunjucks docs: http://mozilla.github.io/nunjucks/ -->
<!-- jade: http://jade-lang.com/ -->
<!-- haml: http://haml.info/tutorial.html -->
<!-- hbs(handlebars): http://handlebarsjs.com/expressions.html -->

<!DOCTYPE html>
<html>
  <head>
    <title>MongoDB & Mongoose | freeCodeCamp.org</title>
    <link
      rel="shortcut icon"
      href="https://cdn.freecodecamp.org/universal/favicons/favicon-32x32.png"
      type="image/x-icon"
    />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body {
        background-color: #ddd;
        color: #333;
        font-family: sans-serif;
        text-align: center;
      }
    </style>
  </head>

  <body>
    <h1>MongoDB & Mongoose</h1>
  </body>
</html>

 

Boilerplate NodeJS Express File Metadata

index.js

var express = require('express');
var cors = require('cors');
require('dotenv').config();

var app = express();

//Import multer for getting file upload
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

app.use(cors());
app.use('/public', express.static(process.cwd() + '/public'));

app.get('/', function (req, res) {
    res.sendFile(process.cwd() + '/views/index.html');
});

app.post('/api/fileanalyse', upload.single('upfile'), function (req, res, next) {
  res.json({name: req.file.originalname, type: req.file.mimetype, size: req.file.size});
});

const port = process.env.PORT || 3000;
app.listen(port, function () {
  console.log('Your app is listening on port: ' + port)
});

readme.md

File Metadata Microservice

This is the boilerplate for the File Metadata Microservice project. Instructions for building your project can be found at https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice

sample.env

PORT=3000

package.json

{
  "name": "file_metadata",
  "version": "0.0.1",
  "description": "API project for freeCodeCamp",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.16.4",
    "multer": "^1.4.5-lts.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/freeCodeCamp/boilerplate-project-filemetadata"
  },
  "keywords": [
    "node",
    "express"
  ],
  "license": "MIT"
}
 

views/index.html

<!DOCTYPE html>

<html>
   <head>
      <title>File Metadata</title>
      <link rel="shortcut icon" href="https://cdn.freecodecamp.org/universal/favicons/favicon-32x32.png" type="image/x-icon"/>
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
      <link href="/public/style.css" rel="stylesheet" type="text/css">
   </head>

   <body>
      <div class="container">
        <h2>API Project: File Metadata Microservice</h2>

        <h3>Usage:</h3>
        <p>
          Please Upload a File ...
        </p>
        <div class="view">
          <h4 id="output"></h4>
          <form enctype="multipart/form-data" method="POST" action="/api/fileanalyse">
            <input id="inputfield" type="file" name="upfile">
            <input id="button" type="submit" value="Upload">
          </form>
        </div>
      </div>
      <div class="footer">
        <p>
          by
          <a href="http://www.freecodecamp.com">freeCodeCamp</a>
        </p>
      </div>
   </body>
</html>

public/style.css

/****** Main Styling ******/

body {
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  color: #222;
  background-color: #ECF0F1;
  text-align: center;
}

.container {
  padding: 0;
  margin-top: 40px;
}

.footer {
  margin-top: 60px;
}

a {
  color: #2574A9;
}

input {
  display: block;
  position: relative;
  margin: 10px auto;
}

input#button {
  width: 230px;
}

.view {
  position:relative;
  margin: auto;
  margin-top: 40px;
  border: 1px  solid  #aaa;
  padding: 20px;
  width: 60%;
  min-width: 400px;
}
 

uploads/text.txt

This is a test.


Boilerplate NPM

 server.js

 /******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/

'use strict';

var fs = require('fs');
var express = require('express');
var app = express();

if (!process.env.DISABLE_XORIGIN) {
  app.use(function(req, res, next) {
    var allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    var origin = req.headers.origin || '*';
    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){
         console.log(origin);
         res.setHeader('Access-Control-Allow-Origin', origin);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
    next();
  });
}

app.use('/public', express.static(process.cwd() + '/public'));

app.route('/_api/package.json')
  .get(function(req, res, next) {
    console.log('requested');
    fs.readFile(__dirname + '/package.json', function(err, data) {
      if(err) return next(err);
      res.type('txt').send(data.toString());
    });
  });
 
app.route('/')
    .get(function(req, res) {
          res.sendFile(process.cwd() + '/views/index.html');
    })

// Respond not found to all the wrong routes
app.use(function(req, res, next){
  res.status(404);
  res.type('txt').send('Not found');
});

// Error Middleware
app.use(function(err, req, res, next) {
  if(err) {
    res.status(err.status || 500)
      .type('txt')
      .send(err.message || 'SERVER ERROR');
  }  
})

//Listen on port set in environment variable or default to 3000
const listener = app.listen(process.env.PORT || 3000, function () {
  console.log("Node.js listening on port " + listener.address().port);
});

package.json

{"author": "TCL",
    "description": "A boilerplate project",
    "keywords": [ "boilerplate", "nodejs", "test", "freecodecamp"],
    "license": "MIT",
    "version": "0.0.1",
    "name": "fcc-learn-npm-package-json",
    "dependencies": {"express": "^4.14.0"},
    "main": "server.js",
    "scripts": {
        "start": "node server.js"
    },
    "repository": {
        "type": "git",
        "url": "https://idontknow/todo.git"
    }
}

readme.md

# Backend Challenges boilerplate - package.json
[![Run on Repl.it](https://repl.it/badge/github/freeCodeCamp/boilerplate-npm)](https://repl.it/github/freeCodeCamp/boilerplate-npm)

views/index.html

<!DOCTYPE html>
<html>

   <head>
      <title>Backend Challenges | Free Code Camp</title>
      <link rel="shortcut icon" href="https://cdn.hyperdev.com/us-east-1%3A52a203ff-088b-420f-81be-45bf559d01b1%2Ffavicon.ico" type="image/x-icon"/>
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
      <link href="/public/style.css" rel="stylesheet" type="text/css">
   </head>

   <body>
      <div class="container">
         <h1>Manage Node.js projects and npm packages using package.json</h1>
         <h3>Part 1 of Free Code Camp Backend Challenges</h3>
      </div>
   </body>

</html>

public/style.css

/****** Main Styling ******/

body {
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    color: #222;
    background-color: #ECF0F1;
    text-align: center;
}

.container {
    padding: 0;
    margin-top: 40px;
}

.footer {
    margin-top: 60px;
}

ol {
    list-style-position: inside;
}
ul {
    list-style-type: none;
}

a {
    color: #2574A9;
}
/****** Logo Div Styling ******/

img {
    margin: 20px auto 0 auto;
    display: block;
}


Monday, September 2, 2024

Boilerplate NPM NodeJS Express

MyApp.js

require('dotenv').config()
let bodyParser = require('body-parser')
let express = require('express');
let app = express();
let viewpath = __dirname + '/views/'
let indexpath = viewpath + 'index.html'
let publicpath = __dirname + '/public'
app.use('/public', express.static(publicpath));
app.use(logger);
app.use(bodyParser.urlencoded({extended: false}));

function logger (req, res, next) {
  var string = req.method + " " + req.path + " - " + req.ip;
    console.log(string);
  next();
}

function stringresponse (req, res) {
  res.send('Hello Express');
}

function jsonresponse (req, res) {
  let data = {"message": "Hello json"};
    // console.log(process.env.MESSAGE_STYLE == "uppercase")
    if (process.env.MESSAGE_STYLE == "uppercase") {
        data['message'] = data['message'].toUpperCase()
    }
    res.json(data);
}

function fileresponse (req, res) {
  // console.log(req.method, req.path, req.ip);
    res.sendFile(indexpath);
}

app.get('/', fileresponse)
app.get('/json', jsonresponse)
app.get('/now', function(req, res, next) {
  let timenow = new Date().toString()
    req.time = timenow;  // Hypothetical synchronous operation
  next();
}, function(req, res) {
  res.json({'time': req.time});
});
app.get('/:word/echo', function(req, res, next) {
    req.echo = req.params.word;  // Hypothetical synchronous operation
  next();
}, function(req, res) {
  res.json({'echo': req.echo});
});

app.route('/name').get(getnamehandler).post(postnamehandler)
function getnamehandler(req, res) {
    let reqquery = req.query;
    let first = reqquery['first']
    let last = reqquery['last']
    let fullname = first + ' ' + last
    console.log('get req.query', reqquery);
  res.json({'name': fullname});
};

function postnamehandler(req, res) {
    let reqbody = req.body;
    let first = reqbody['first']
    let last = reqbody['last']
    let fullname = first + ' ' + last
    console.log('post req.body', fullname);
  res.json({'name': fullname});
};

 module.exports = app;

server.js

/******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/
 
const bGround = require('fcc-express-bground');
const myApp = require('./myApp');
const express = require('express');
const app = express();

if (!process.env.DISABLE_XORIGIN) {
  app.use((req, res, next) => {
    const allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    const origin = req.headers.origin || '*';
    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){
         console.log(origin);
         res.setHeader('Access-Control-Allow-Origin', origin);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
    next();
  });
}

const port = process.env.PORT || 3000;
bGround.setupBackgroundApp(app, myApp, __dirname).listen(port, () => {
  bGround.log(`Node is listening on port ${port}...`);
});

/******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/
 views/index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Hello HTML</title>
        <link rel="stylesheet" href="/public/style.css">
    </head>
    <body>
        <h1>Hello, HTML.</h1>
        <p>Do not use until Challenge #12</p>
     <form action="/name" method="post">
      <label>First Name :</label>
      <input type="text" name="first" value="John"><br>
      <label>Last Name :</label>
      <input type="text" name="last" value="Doe"><br><br>
      <input type="submit" value="Submit">
    </form>
    </body>

</html>

public/style.css

/* the 'body' selector is required for the tests to pass */
/* You can change the style attributes if you want */
body {
  background-color: #222;
  color: #ddd;
  text-align: center;
  font-family: sans-serif;
}

h1 {
  font-size: 4em;
}

input[type=text], label {
  margin-bottom: 8px;
}

package.json

{
  "name": "fcc-learn-node-with-express",
  "version": "0.1.0",
  "dependencies": {
    "body-parser": "^1.15.2",
    "cookie-parser": "^1.4.3",
    "dotenv": "^16.0.1",
    "express": "^4.14.0",
    "fcc-express-bground": "https://github.com/freeCodeCamp/fcc-express-bground-pkg.git"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  }
}

readme.json

Basic Node and Express

This is the boilerplate code for the Basic Node and Express Challenges. Instructions for working on these challenges start at https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/

Boilerplate Project Header Parser NodeJS Express

// index.js
// where your node app starts

// init project
require('dotenv').config();
var express = require('express');
var app = express();

// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC
var cors = require('cors');
app.use(cors({ optionsSuccessStatus: 200 })); // some legacy browsers choke on 204

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

// your first API endpoint...
app.get('/api/whoami', function (req, res) {
    res.json({
            ipaddress: req.get('x-forwarded-for'),
            language: req.get('accept-language'),
    software: req.get('user-agent')
    });
});

app.get('/api/test', function (req, res) {
    res.json({
        userAgent: req.get('user-agent')
    });
});


// listen for requests :)
var listener = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

views/index.html

<!DOCTYPE html>

<html>

   <head>
      <title>Request Header Parser</title>
      <link rel="shortcut icon" href="https://cdn.hyperdev.com/us-east-1%3A52a203ff-088b-420f-81be-45bf559d01b1%2Ffavicon.ico" type="image/x-icon"/>
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
      <link href="style.css" rel="stylesheet" type="text/css">
   </head>

   <body>
      <div class="container">
        <h2>Request Header Parser Microservice</h2>

        <h3>Example Usage:</h3>
        <p>
          <a href="api/whoami">[base url]/api/whoami</a>
        </p>

        <h3>Example Output:</h3>
        <p>
          <code>{"ipaddress":"::ffff:159.20.14.100","language":"en-US,en;q=0.5",<br>"software":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0"}</code>
        </p>
      </div>
      <div class="footer">
        <p>
          by <a href="https://www.freecodecamp.org">freeCodeCamp</a>
        </p>
      </div>
   </body>


</html>

public/style.css

body {
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    color: #222;
    background-color: #FaFaFa;
    text-align: center;
    line-height: 1.4em;
}

.container {
    padding: 0;
    margin-top: 40px;
}

h3 {
  margin-top: 30px;
}

.footer {
    margin-top: 40px;
}

code {
  font-family: monospace;
  padding: 2px;
  color: black;
  background-color: #fff;
}

a {
    color: #2574A9;
}

readme.md

# Request Header Parser Microservice

This is the boilerplate for the Request Header Parser Microservice project. Instructions for building your project can be found at https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice

You should provide your own project, not the example URL.
Waiting: A request to /api/whoami should return a JSON object with your IP address in the ipaddress key.
Waiting: A request to /api/whoami should return a JSON object with your preferred language in the language key.
Waiting: A request to /api/whoami should return a JSON object with your software in the software key.


API Project: Request Header Parser Microservice
Example Usage:
[base url]/api/whoami
Example Output:

{"ipaddress":"159.20.14.100","language":"en-US,en;q=0.5",
"software":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0"}

Sunday, September 1, 2024

Boilerplate Project NodeJs Express Timestamp

// index.js
// where your node app starts

// init project
var express = require('express');
var app = express();

// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC
var cors = require('cors');
app.use(cors({optionsSuccessStatus: 200}));  // some legacy browsers choke on 204

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});


app.get("/api/:time?", function (req, res) {
  let date;
  if (req.params.time) {
    // Check if it is a Unix timestamp
    if (!isNaN(req.params.time)) {
      date = new Date(parseInt(req.params.time));
    } else {
      date = new Date(req.params.time);
    }
  } else {
    // If no parameter, use the current date and time
    date = new Date();
  }

  if (!isNaN(date.getTime())) {
    // If date is valid, return the Unix timestamp and UTC string
    res.json({unix: date.getTime(), utc: date.toUTCString()});
  } else {
    // If date is not valid, return an error message
    res.json({error: "Invalid Date"});
  }
});

// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

views/index.html

<!DOCTYPE html>

<html>
   <head>
      <title>Timestamp Microservice | freeCodeCamp.org</title>
      <link rel="shortcut icon" href="https://cdn.freecodecamp.org/universal/favicons/favicon-32x32.png" type="image/x-icon"/>
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
      <link href="style.css" rel="stylesheet" type="text/css">
   </head>

   <body>
    <h1>Timestamp Microservice</h1>
    <hr />
    <div class="container">
      <h3>Example Usage:</h3>
      <ul>
        <li><a href="api/2015-12-25">[project url]/api/2015-12-25</a></li>
        <li><a href="api/1451001600000">[project url]/api/1451001600000</a></li>
      </ul>

      <h3>Example Output:</h3>
      <p>
        <code>{"unix":1451001600000, "utc":"Fri, 25 Dec 2015 00:00:00 GMT"}</code>
      </p>
    </div>
    <div class="footer">
      <p>
        By <a href="https://www.freecodecamp.org/">freeCodeCamp.org</a>
      </p>
    </div>
  </body>
</html>

public/style.css

/****** Main Styling ******/

body {
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    color: #222;
    background-color: #FaFaFa;
    text-align: center;
    line-height: 1.4em;
}a

.container {
    padding: 0;
    margin-top: 40px;
}

h3 {
  margin-top: 30px;
}

hr {
    margin: 25px;
}

.footer {
    margin-top: 40px;
}

code {
  font-family: monospace;
  padding: 2px;
  color: black;
  background-color: #fff;
}

ul {
    list-style-type: none;
}

li {
  margin-bottom: 0.5em;
}

a {
    color: #2574A9;
}

package.json

{
  "name": "fcc-api-projects-boilerplate",
  "version": "0.0.1",
  "description": "An FCC Backend Challenge",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.12.4",
    "cors": "^2.8.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/freeCodeCamp/boilerplate-project-timestamp.git"
  },
  "bugs": {
    "url": "https://github.com/freeCodeCamp/freeCodeCamp/issues"
  },
  "homepage": "https://github.com/freeCodeCamp/boilerplate-project-timestamp#readme",
  "author": "freeCodeCamp <team@freecodecamp.org>",
  "keywords": [
    "node",
    "express",
    "freeCodeCamp"
  ],
  "license": "MIT"
}

readme.md

Timestamp Microservice

This is the boilerplate code for the Timestamp Microservice project. Instructions for building your project can be found at https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/timestamp-microservice

Timestamp Microservice Example Usage:

[project url]/api/2015-12-25
[project url]/api/1451001600000

Example Output:

{"unix":1451001600000, "utc":"Fri, 25 Dec 2015 00:00:00 GMT"} app.get("/api/:time", function (req, res) { console.log(req.params.time); let unixtime; if (Date.parse(req.params.time) > 0) { unixtime = new Date(req.params.time).getTime() / 1000; } else { unixtime = req.params.time; } const utctime = new Date(req.params.time).toUTCString(); console.log(utctime); res.json({unix: unixtime, utc: utctime}); });

 

ReplIT Video Recorder in Flask

from flask import Flask
app = Flask(__name__)
@app.route('/')
def main():
    return """
    
<!DOCTYPE html>
<html>
  <head>
    <title>recorder</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="WebRTC getUserMedia MediaRecorder API">
    <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style>
      button{
        margin: 10px 5px;
      }
      li{
        margin: 10px;
      }
      body{
        width: 90%;
        max-width: 960px;
        margin: 0px auto;
      }
      #btns{
        display: none;
      }
      h1{
        margin: 100px;
      }
    </style>
  </head>
  <body>
    <h1>MediaRecorder API</h1>

    <p> For now it is supported only in Firefox(v25+) and Chrome(v47+)</p>
    <div id='gUMArea'>
      <div>
      Record:
        <input type="radio" name="media" value="video" checked id='mediaVideo'>Video
        <input type="radio" name="media" value="audio">audio
      </div>
      <button class="btn btn-default"  id='gUMbtn'>Request Stream</button>
    </div>
    <div id='btns'>
      <button  class="btn btn-default" id='start'>Start</button>
      <button  class="btn btn-default" id='stop'>Stop</button>
    </div>
    <div>
      <ul  class="list-unstyled" id='ul'></ul>
    </div>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
    'use strict'

let log = console.log.bind(console),
  id = val => document.getElementById(val),
  ul = id('ul'),
  gUMbtn = id('gUMbtn'),
  start = id('start'),
  stop = id('stop'),
  stream,
  recorder,
  counter=1,
  chunks,
  media;


gUMbtn.onclick = e => {
  let mv = id('mediaVideo'),
      mediaOptions = {
        video: {
          tag: 'video',
          type: 'video/webm',
          ext: '.mp4',
          gUM: {video: true, audio: true}
        },
        audio: {
          tag: 'audio',
          type: 'audio/ogg',
          ext: '.ogg',
          gUM: {audio: true}
        }
      };
  media = mv.checked ? mediaOptions.video : mediaOptions.audio;
  navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => {
    stream = _stream;
    id('gUMArea').style.display = 'none';
    id('btns').style.display = 'inherit';
    start.removeAttribute('disabled');
    recorder = new MediaRecorder(stream);
    recorder.ondataavailable = e => {
      chunks.push(e.data);
      if(recorder.state == 'inactive')  makeLink();
    };
    log('got media successfully');
  }).catch(log);
}

start.onclick = e => {
  start.disabled = true;
  stop.removeAttribute('disabled');
  chunks=[];
  recorder.start();
}


stop.onclick = e => {
  stop.disabled = true;
  recorder.stop();
  start.removeAttribute('disabled');
}

function makeLink(){
  let blob = new Blob(chunks, {type: media.type })
    , url = URL.createObjectURL(blob)
    , li = document.createElement('li')
    , mt = document.createElement(media.tag)
    , hf = document.createElement('a')
  ;
  mt.controls = true;
  mt.src = url;
  hf.href = url;
  hf.download = `${counter++}${media.ext}`;
  hf.innerHTML = `donwload ${hf.download}`;
  li.appendChild(mt);
  li.appendChild(hf);
  ul.appendChild(li);
}

    </script>
  </body>
</html>

    """
app.run('0.0.0.0')

ReplIT FlaskMockUp

from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions

app = FlaskAPI(__name__)

notes = {
    0: 'do the shopping',
    1: 'build the codez',
    2: 'paint the door',
}

def note_repr(key):
    return {
        'url': request.host_url.rstrip('/') + url_for('notes_detail', key=key),
        'text': notes[key]
    }


@app.route("/", methods=['GET', 'POST'])
def notes_list():
    """
    List or create notes.
    """
    if request.method == 'POST':
        note = str(request.data.get('text', ''))
        idx = max(notes.keys()) + 1
        notes[idx] = note
        return note_repr(idx), status.HTTP_201_CREATED

    # request.method == 'GET'
    return [note_repr(idx) for idx in sorted(notes.keys())]


@app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE'])
def notes_detail(key):
    """
    Retrieve, update or delete note instances.
    """
    if request.method == 'PUT':
        note = str(request.data.get('text', ''))
        notes[key] = note
        return note_repr(key)

    elif request.method == 'DELETE':
        notes.pop(key, None)
        return '', status.HTTP_204_NO_CONTENT

    # request.method == 'GET'
    if key not in notes:
        raise exceptions.NotFound()
    return note_repr(key)
    
app.run(host='0.0.0.0', port=8080)