Jump to content

The under 100 line challenge!

fletch to 99

Chris Domas won this game a couple years ago.  Every program you've ever used could be simplified to under 20 lines of code and a data table.

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

A bulk microbenchmarking tool -with documentation.

import java.io.{File, PrintWriter}

import ichi.bench.Thyme
import ichi.bench.Thyme.{Benched, Comparison}

import scala.util.{Failure, Success, Try}

/** A tool for bulk benchmarking of collections of functions/methods on collections of inputs
  *
  * This class takes an arbitrary collection of functions and inputs and generates two files,
  * one containing the detailed benchmarking log and one containing a table of the raw data.
  *
  * @author Dash Lambda
  */
class BulkBench(tst: Thyme = Thyme.warmedBench(verbose = println)){
  /** Takes both a collection of functions and a collection of inputs and benchmarks all of the functions across all of the inputs.
    * @param title A string used for tagging and organizing logs
    * @param id A number used for tagging and organizing logs
    * @param inputs The collection of input values
    * @param funcs The collection of functions
    */
  def benchRun[T](title: String, id: Int, inputs: Vector[T])(funcs: Vector[(String, T => Any)]): Unit = {
    val datFile = new PrintWriter(new File(s"Bench_${title}_${id}_${inputs.head}-${inputs.last}_Lump.txt"))
    val logFile = new PrintWriter(new File(s"Bench_${title}_${id}_${inputs.head}-${inputs.last}_Log.txt"))
    
    def logWriter(str: String = ""): Unit = {println(str); logFile.println(str)}
    
    datFile.print(s"Inputs ${funcs.map(_._1).mkString(" ")}")
    logWriter(s"Benching: $title\nID: $id")
    
    for(inp <- inputs){
      benchAllLog(id, inp, logWriter, datFile)(funcs)
      logFile.flush()
      datFile.flush()
    }
    
    logFile.close()
    datFile.close()
  }
  
  /** Takes a single input and benches all functions at that input.
    * @param id A number used for tagging and organizing logs
    * @param inp The input value used to benchmark the functions
    * @param logWriter A method that prints a string to the log files
    * @param dataLog A PrintWriter for writing the raw data
    * @param funcs The collection of functions to benchmark
    */
  def benchAllLog[T](id: Int, inp: T, logWriter: String => Unit, dataLog: PrintWriter)(funcs: Vector[(String, T => Any)]): Unit = {
    logWriter(s"\n\nInput: $inp")
    dataLog.print(s"\n$inp")
    
    for((name, func) <- funcs){
      logWriter(s"\n--$name--")
      benchSingleTry(func(inp)) match{
        case Success(result) =>
          logWriter(result.toString)
          dataLog.print(s" ${1000*result.runtime}")
        case Failure(e) =>
          logWriter(s"Failed: $e")
          dataLog.print(" -1")
      }
    }
  }
  
  /** Takes a single zero-argument function and benchmarks it, handling errors/exceptions
    * @param func The function to benchmark
    * @return Try wrapper containing the benchmark results if successful and an error if not
    */
  def benchSingleTry(func: => Any): Try[Benched] = trySafe{
    val benchResult = Benched.empty
    tst.benchWarm(tst.Warm(func))(benchResult)
    benchResult
  }
  
  /** Try an operation/function and return the result
    *
    * This try statement, unlike Scala's usual Try{}, catches errors as well as exceptions.
    * The purpose is to allow the benchmark to continue in the event of a stack overflow or out of memory error,
    * logging such an error as a failure.
    * @param func The function/operation to try
    * @return Try-wrappered result of the operation/function
    */
  def trySafe[T](func: => T): Try[T] = try{ Success(func) } catch{ case e: Throwable => Failure(e) }
}

object BulkBench{
  def apply(): BulkBench = new BulkBench
  def apply(tst: Thyme): BulkBench = new BulkBench(tst)
}

... The code block tool really needs Scala syntax highlighting.

 

On 6/17/2019 at 10:10 AM, Gmoneyinthebank said:

Chris Domas won this game a couple years ago.  Every program you've ever used could be simplified to under 20 lines of code and a data table.

Well, yeah. In a lot of languages you could also just use braces and semicolons to write everything in a single line.

 

Hell, you could write any program in a single line using only 8 characters. But there's a very good reason people don't use Brainfuck.

 

I see these sort of challenges as less of a pure measure of length and more as an exercise in elegance or creative efficiency.

"Do as I say, not as I do."

-Because you actually care if it makes sense.

Link to comment
Share on other sites

Link to post
Share on other sites

43 minutes ago, Gmoneyinthebank said:

Did you watch the video?

Nothing new. I have already been working with that for a very long time. This is how all the ERP i have worked with works. All window, logic run from the database and is running live code. The biggest problem is speed and maintaining the bloody thing. For ERP at least you don't modify it that often. That's also partially how one of the major canada tax submission software works.

Link to comment
Share on other sites

Link to post
Share on other sites

A purely functional Brainfuck interpreter:

Spoiler

import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}

object BFFunctional {
  def bfRun(prog: String): Option[String] = bfRun(prog, true)
  def bfRun(prog: String, log: Boolean): Option[String] = bfi("", prog.filter("<>+-.,[]".contains(_)), List[Int](), List[Int](0), 0, 0, log, "")
  
  @tailrec
  def bfi(plog: String, psrc: String, dlog: List[Int], dsrc: List[Int], dir: Int, cnt: Int, cons: Boolean, result: String): Option[String] = dir match{
    case 1 => (psrc.headOption, cnt) match{
      case (Some(']'), 0) => bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, 0, 0, cons, result)
      case (Some(']'), _) => bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt - 1, cons, result)
      case (Some('['), _) => bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt + 1, cons, result)
      case (Some(_), _) => bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt, cons, result)
      case _ => None
    }
    case -1 => (plog.headOption, cnt) match{
      case (Some('['), 0) => bfi(plog, psrc, dlog, dsrc, 0, 0, cons, result)
      case (Some('['), _) => bfi(plog.tail, plog.head +: psrc, dlog, dsrc, dir, cnt - 1, cons, result)
      case (Some(']'), _) => bfi(plog.tail, plog.head +: psrc, dlog, dsrc, dir, cnt + 1, cons, result)
      case (Some(_), _) => bfi(plog.tail, plog.head +: psrc, dlog, dsrc, dir, cnt, cons, result)
      case _ => None
    }
    case 0 => psrc.headOption match{
      case Some(op) => op match{
        case '>' => if(dsrc.tail.nonEmpty) bfi(psrc.head +: plog, psrc.tail, dsrc.head +: dlog, dsrc.tail, dir, cnt, cons, result) else bfi(psrc.head +: plog, psrc.tail, dsrc.head +: dlog, List(0), dir, cnt, cons, result)
        case '<' => if(dlog.nonEmpty) bfi(psrc.head +: plog, psrc.tail, dlog.tail, dlog.head +: dsrc, dir, cnt, cons, result) else None
        case '+' => bfi(psrc.head +: plog, psrc.tail, dlog, (dsrc.head + 1) +: dsrc.tail, dir, cnt, cons, result)
        case '-' => bfi(psrc.head +: plog, psrc.tail, dlog, (dsrc.head - 1) +: dsrc.tail, dir, cnt, cons, result)
        case ']' => if(dsrc.head == 0) bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt, cons, result) else bfi(plog.tail, plog.head +: psrc, dlog, dsrc, -1, 0, cons, result)
        case '[' => if(dsrc.head == 0) bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, 1, 0, cons, result) else bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt, cons, result)
        case '.' => if(cons) print(dsrc.head.toChar); bfi(psrc.head +: plog, psrc.tail, dlog, dsrc, dir, cnt, cons, result :+ dsrc.head.toChar)
        case ',' => Try(scala.io.StdIn.readInt) match{
          case Success(inp) => bfi(psrc.head +: plog, psrc.tail, dlog, inp +: dsrc.tail, dir, cnt, cons, result)
          case Failure(_) => bfi(plog, psrc, dlog, dsrc, dir, cnt, cons, result)
        }
      }
      case _ => Some(result)
    }
  }
}

 

And three esoteric language translators:

Spoiler

package translators

import scala.annotation.tailrec
import scala.collection.immutable

trait BFTranslator {
  def name: String
  
  def keys: Vector[String]
  def vals: Vector[String]
  
  final lazy val syntax = buildMap(keys, vals)
  final lazy val revSyntax = buildMap(vals, keys)
  
  protected final lazy val builder = immutable.HashMap.newBuilder[String, String]
  protected final def buildMap(ks: Vector[String], vs: Vector[String]): immutable.HashMap[String, String] = {
    builder ++= ks.zip(vs)
    val res = builder.result
    builder.clear
    res
  }
  
  def apply(prog: String): String
  def unapply(prog: String): String
}

class GenericBFTranslator(val name: String, val keys: Vector[String], val vals: Vector[String]) extends BFTranslator{
  def apply(prog: String): String = translate(prog, syntax)
  def unapply(prog: String): String = translate(prog, revSyntax)
  
  private def translate(prog: String, syn: immutable.HashMap[String, String]): String = {
    val keys = syn.keys.toVector.sortWith(_.length > _.length)
    
    @tailrec
    def tHelper(log: String, src: String): String = {
      keys.find(key => key == src.take(key.length)) match{
        case Some(h) => tHelper(log ++ syn(h), src.drop(h.length))
        case None if src.nonEmpty => tHelper(log :+ src.head, src.tail)
        case None if src.isEmpty => log
      }
    }
    
    tHelper("", prog)
  }
}

object GenericBFTranslator{
  def apply(name: String, syntax: immutable.HashMap[String, String]): GenericBFTranslator = {
    val kv = syntax.toVector.unzip
    new GenericBFTranslator(name, kv._1, kv._2)
  }
  
  def apply(name: String, pairs: IndexedSeq[(String, String)]): GenericBFTranslator = {
    val kv = pairs.toVector.unzip
    new GenericBFTranslator(name, kv._1, kv._2)
  }
}

object BrainPuff extends BFTranslator{
  final val name = "BrainPuff"
  
  final lazy val keys: Vector[String] = Vector("*gasp*", "*pomf*", "pf", "bl", "b", "t", "!", "?")
  final lazy val vals: Vector[String] = Vector("[", "]", "+", "-", ">", "<", ".", ",")
  
  def apply(prog: String): String = keys.foldLeft(prog){(str, key) => str.replaceAllLiterally(key, syntax(key))}
  def unapply(prog: String): String = revSyntax.keys.foldLeft(prog){(str, key) => str.replaceAllLiterally(key, revSyntax(key))}
}

object Ook extends BFTranslator{
  final val name = "Ook"
  
  final lazy val keys: Vector[String] = Vector("Ook! Ook.", "Ook. Ook!", "Ook. Ook?", "Ook? Ook.", "Ook. Ook.", "Ook! Ook!", "Ook! Ook?", "Ook? Ook!")
  final lazy val vals: Vector[String] = Vector(".", ",", ">", "<", "+", "-", "[", "]")
  
  def apply(prog: String): String = {
    @tailrec
    def tHelper(log: String, src: String): String = keys.find(_ == src.take(9)) match{
      case Some(key) => tHelper(log ++ syntax(key), src.drop(9))
      case None if src.sizeIs > 9 => tHelper(log :+ src.head, src.tail)
      case None => log ++ src
    }
    
    tHelper("", prog)
  }
  def unapply(prog: String): String = vals.foldLeft(prog){case (str, key) => str.replaceAllLiterally(key, revSyntax(key))}
}

 

 

"Do as I say, not as I do."

-Because you actually care if it makes sense.

Link to comment
Share on other sites

Link to post
Share on other sites

In exactly 100 lines, a WhiteSpace interpreter:

package interpreters

import scala.annotation.tailrec
import scala.collection.immutable
import scala.io.StdIn
import scala.util.Try

object WhiteSpace extends Interpreter {
  def apply(log: Boolean)(progRaw: String): Try[String] = {
    val prog = formatProg(progRaw)
    apply(prog, getCalls(prog), log)
  }
  
  def apply(prog: Vector[(String, Long)], callAddrs: immutable.HashMap[Long, Int], log: Boolean): Try[String] = {
    def binOp(func: (Long, Long) => Long)(stack: List[Long]): List[Long] = stack match{case n1 +: n2 +: ns => func(n1, n2) +: ns}
    def printWrap(tok: String): String = {if(log) print(tok); tok}
    
    @tailrec
    def wsi(pc: Int, stack: List[Long], heap: immutable.HashMap[Long, Long], callStack: List[Int], result: String): String = {
      val (op, num) = prog(pc)
      op match{
        case "push" => wsi(pc + 1, num +: stack, heap, callStack, result)
        case "dup" => stack match{case n +: ns => wsi(pc + 1, n +: n +: ns, heap, callStack, result)}
        case "swap" => stack match{case n1 +: n2 +: ns => wsi(pc + 1, n2 +: n1 +: ns, heap, callStack, result)}
        case "discard" => stack match{case _ +: ns => wsi(pc + 1, ns, heap, callStack, result)}
        case "add" => wsi(pc + 1, binOp(_+_)(stack), heap, callStack, result)
        case "subt" => wsi(pc + 1, binOp(_-_)(stack), heap, callStack, result)
        case "mult" => wsi(pc + 1, binOp(_*_)(stack), heap, callStack, result)
        case "intDiv" => wsi(pc + 1, binOp(_/_)(stack), heap, callStack, result)
        case "mod" => wsi(pc + 1, binOp(_%_)(stack), heap, callStack, result)
        case "store" => stack match{case n1 +: n2 +: ns => wsi(pc + 1, ns, heap.updated(n2, n1), callStack, result)}
        case "get" => stack match{case n +: ns => wsi(pc + 1, heap(n) +: ns, heap, callStack, result)}
        case "label" => wsi(pc + 1, stack, heap, callStack, result)
        case "call" => wsi(callAddrs(num), stack, heap, (pc + 1) +: callStack, result)
        case "jump" => wsi(callAddrs(num), stack, heap, callStack, result)
        case "jumpZero" => if(stack.head == 0) wsi(callAddrs(num), stack.tail, heap, callStack, result) else wsi(pc + 1, stack.tail, heap, callStack, result)
        case "jumpNeg" => if(stack.head < 0) wsi(callAddrs(num), stack.tail, heap, callStack, result) else wsi(pc + 1, stack.tail, heap, callStack, result)
        case "return" => callStack match{case a +: as => wsi(a, stack, heap, as, result)}
        case "endProg" => result
        case "outChar" => stack match{case n +: ns => wsi(pc + 1, ns, heap, callStack, result ++ printWrap(n.toChar.toString))}
        case "outNum" => stack match{case n +: ns => wsi(pc + 1, ns, heap, callStack, result ++ printWrap(n.toString))}
        case "readChar" => wsi(pc + 1, StdIn.readChar.toLong +: stack, heap, callStack, result)
        case "readNum" => wsi(pc + 1, StdIn.readLong +: stack, heap, callStack, result)
      }
    }
    
    Try{wsi(0, List[Long](), immutable.HashMap[Long, Long](), List[Int](), "")}
  }
  
  def getCalls(vec: Vector[(String, Long)]): immutable.HashMap[Long, Int] = mkMap(vec.zipWithIndex.filter{case ((op, _), _) => op == "label"}.map{case ((_, num), ind) => (num, ind)})
  def formatProg(prog: String): Vector[(String, Long)] = {
    val syntax: Vector[(String, String)] = Vector[(String, String)](
      ("  ", "push"),
      (" \n ", "dup"),
      (" \n\t", "swap"),
      (" \n\n", "discard"),
      ("\t   ", "add"),
      ("\t  \t", "subt"),
      ("\t  \n", "mult"),
      ("\t \t ", "intDiv"),
      ("\t \t\t", "mod"),
      ("\t\t ", "store"),
      ("\t\t\t", "get"),
      ("\n  ", "label"),
      ("\n \t", "call"),
      ("\n \n", "jump"),
      ("\n\t ", "jumpZero"),
      ("\n\t\t", "jumpNeg"),
      ("\n\t\n", "return"),
      ("\n\n\n", "endProg"),
      ("\t\n  ", "outChar"),
      ("\t\n \t", "outNum"),
      ("\t\n\t ", "readChar"),
      ("\t\n\t\t", "readNum"))
    val nonArgOps: Vector[String] = Vector[String]("dup", "swap", "discard", "add", "subt", "mult", "intDiv", "mod", "store", "get", "return", "endProg", "outChar", "outNum", "readChar", "readNum")
    val synKeys = syntax.map(_._1).sortWith(_.length > _.length)
    val synMap: immutable.HashMap[String, String] = mkMap(syntax)
    
    def isNotLF(c: Char): Boolean = (c == ' ') || (c == '\t')
    def longNum(str: String): Long = str.takeWhile(isNotLF).reverse.zipWithIndex.map{case (c, i) => if(c == '\t') Math.pow(2, i).toLong else 0L}.sum
  
    @tailrec
    def fHelper(ac: Vector[(String, Long)], src: String): Vector[(String, Long)] = {
      synKeys.find(src.startsWith) match{
        case Some(key) =>
          val tag = synMap(key)
          if(nonArgOps.contains(tag)) fHelper(ac :+ ((tag, 0L)), src.drop(key.length))
          else{
            val tail = src.drop (key.length)
            val lNum = longNum (tail)
            fHelper (ac :+ ((tag, lNum)), tail.dropWhile (isNotLF).tail)
          }
        case None => if(src.nonEmpty) fHelper(ac, src.tail) else ac
      }
    }
    
    val conditioned = prog.replaceAll("(\r\n|\r)", "\n").filter("\t\n ".contains(_))
    fHelper(Vector[(String, Long)](), conditioned)
  }
}

It inherits one space-saving method, which is only relevant because for some reason Scala 2.13 deprecates inline initialization of maps with collections:

def mkMap[A, B](vec: Vector[(A, B)]): immutable.HashMap[A, B] = {
  val builder = immutable.HashMap.newBuilder[A, B]
  builder ++= vec
  builder.result
}

 

"Do as I say, not as I do."

-Because you actually care if it makes sense.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Function to find the largest number composed of distinct digits that is divisible by all those digits, in arbitrary base:

def getLargestNum(base: SafeLong): SafeLong = {
  def chkNum(digits: Vector[SafeLong])(num: SafeLong): Boolean = {
    val lst = LazyList.iterate((num%base, num/base)){case (_, src) => (src%base, src/base)}.take(digits.length).map(_._1)
    lst.diff(digits).isEmpty
  }
  
  def chkChunk(combo: Vector[SafeLong]): Option[SafeLong] = {
    val lcm = combo.reduce(_.lcm(_))
    val ulim = combo.zipWithIndex.map{case (n, i) => n*(base ** i)}.reduce(_+_)
    Iterator.iterate(ulim - (ulim%lcm))(_ - lcm).takeWhile(_ > 0).find(chkNum(combo))
  }

  val baseDigits: Vector[SafeLong] = Vector.range(1, base.toInt).map(SafeLong(_))
  def chkBlock(digits: Iterator[Vector[SafeLong]]): Option[SafeLong] = digits.map(chkChunk).collect{case Some(n) => n}.maxOption
  Iterator.from(base.toInt - 1, -1).map(len => chkBlock(baseDigits.combinations(len))).collect{case Some(n) => n}.next
}

"Do as I say, not as I do."

-Because you actually care if it makes sense.

Link to comment
Share on other sites

Link to post
Share on other sites

This is mine, although there are easier ways to accomplish the same task this was a way to practice some python and have some fun.

It can be used to convert M4a files to mp3. This can take a while (70 min for 266 songs). I will add multiple threads later on and you wouldn't be using this tool if things were time critical

 

https://github.com/IsaacWP121/M4a-to-MP3/tree/master

 

This is quite simple as it was made in 2 hours by a teen. Don't roast me to hard ?

I'm a python programmer and I play trombone

Link to comment
Share on other sites

Link to post
Share on other sites

These might just be the most beautiful 10 lines of code I've written thus far. It's that encryption cracker from earlier in the thread, but way more Scala-y.

def getHash(str: String): String = MessageDigest
  .getInstance("SHA-256")
  .digest(str.getBytes("UTF-8"))
  .map("%02x".format(_)).mkString

def crackLazy(charSet: Seq[Char], len: Int, num: Int)(hash: String): Option[String] = charSet
  .flatMap(Vector.fill(len)(_))                           //Duplicate characters so they can be used any number of times
  .combinations(len)                                      //Generate distinct sets of characters
  .flatMap(_.permutations.map(_.mkString))                //Generate all permutations for each character set
  .grouped(num)                                           //Partition into bite-size chunks
  .map(_.to(ParVector).find(str => getHash(str) == hash)) //Convert each chunk into a ParVector and search it
  .collectFirst{case Some(res) => res}                    //Get the first hit if one is found

"Do as I say, not as I do."

-Because you actually care if it makes sense.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
#include <iostream>

using namespace std;

int main(){
    string username;
    string pin;
    string pinCheck;

    cout << "enter username\n";
    getline(cin, username);

    cout << username << ", please enter your new Password!\n";
    getline(cin, pin);

    system("clear");

    cout << username << ", Please login with your password\n";
    cout << "Password : ";
    getline(cin, pinCheck);

    if (pin != pinCheck){
        cout << "validation error\n";
    } else {
        cout << "validation success\n";
    }

    return 0;
}

Under the MIT licence. I made it.

Check it out on GitHub: https://github.com/SafyreLyons/Fake-Login-App

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Github

just reads keyboard presses and mouse clicks, when the window is focused.

Not the most useful but certainly has its uses ?

36 lines (counting whitespace lines) at the time of posting, plan on adding more later

This Signature is brought to you by Binary.
To check out the products we featured in the Signature check the links below.

Link to comment
Share on other sites

Link to post
Share on other sites

Get all of a GitHub users stars and save them in JSON. Written in Python 3, the user is specified in the last line of the code, written in 60 lines of code.

stars.py

Link to comment
Share on other sites

Link to post
Share on other sites

#include <iostream>
#include <fstream>
#include <chrono>
#include <ctime>

using namespace std;
string sID;
string sfn;
string sln;
auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());

int main();

int edit(){
    cout << "Student ID :";
    cin >> sID;
    cout << "New grade :";
    char grd;
    cin >> grd;

    ofstream file;
    file.open(sID, ios::app);
    file << "\n-------------------" << endl << "Time " << ctime(&timenow) << "GRADE : " << grd;
    file.close();
    main();
    return 0;
}

int add(){
    cout << "--Add Student--" << endl;
    cout << "Student's first name :";
    cin >> sfn;
    cout << "Last name :";
    cin >> sln;
    cout << "Five digit student ID :";
    cin >> sID;

    ofstream file;
    file.open(sID);
    file << "Name: " << sln << ", " << sfn << " || ID: " << sID << "\nGrade: A - " << ctime(&timenow);
    file.close();
    system("clear");
    main();
    return 0;
}

int ass(){
    cout << "\n-------------------" << endl << "Name of assingment :";
    string asse;
    cin >> asse;
    cout << "for student (by 5 digit ID):";
    cin >> sID;

    ofstream file;
    file.open(sID, ios::app);
    file << "\n-------------------" << endl << "Time " << ctime(&timenow) << "ASSIGNMENT ADDED : " << asse;
    file.close();
    main();

    return 0;
}

int main(){
    system("clear");
    cout <<
    "1 - Add a student" << endl <<
    "2 - Add assignment" << endl <<
    "3 - Edit a grade " << endl <<
    "4 - Quit"
    << endl;
    int opt;
    cout << "option :";
    cin >> opt;
    if(opt == 1){
        add();
    }

    if(opt == 2){
        ass();
    }

    if(opt == 3){
        edit();
    }

    if(opt == 4){
        return 1;
    }

    if(opt > 4 || opt < 1){
        main();
    }
    return 0;
}

94 lines of code. It's close but it works.

Link to comment
Share on other sites

Link to post
Share on other sites

I also made the same idea as my bank manager app but in 70-ish lines

#include <iostream>
#include <fstream>
using namespace std;
int main();
int rMNum[2] = {1, 2};
int rFNum[2] = {3, 4};
string name;
string sch;
int randdex = rand() % 2;
int id = rand() % 100000;
int add(){
    system("clear");
    char mf;
    cout << "Female or male student?";
    cin >> mf;
    if(mf = 'f'){
        cout << "Name: ";
        cin >> name;
        cout << "School name: ";
        cin >> sch;
        int roomNum = rFNum[randdex];
        ofstream file;
        file.open(name);
        file << name << " from " << sch << " || ID: " << id << " room: " << roomNum;
        file.close();
    }else if (mf = 'm'){
        cout << "Name: ";
        cin >> name;
        cout << "School name: ";
        cin >> sch;
        int roomNum = rMNum[randdex];
        ofstream file;
        file.open(name);
        file << name << " from " << sch << " || ID: " << id << " room: " << roomNum;
        file.close();
        int RandIndex = rand() % 4;
    } else {
        add();
    }
    return 0;
}
int del(){
    system("clear");
    cout << "This does not delete the person's file but rather the data in it";
    cout << "Name: ";
    cin >> name;
    ifstream file;
    file.open(name, ofstream::out | ofstream::trunc);
    return 0;
}
int main(){
    system("clear");
    cout << "Pick an option" << endl <<
    "--------------" << endl <<
    "1 --> Add new student" << endl <<
    "2 --> Delete existing student" << endl <<
    "3 --> Quit" << endl;
    int op;
    cin >> op;
    if(op == 1){
        add();
    } 
    if (op == 2){
        del();
    } 
    if (op == 3){
        return 1;
    }
    if(op > 3 || op<1){
        main();
    }
    return 0;
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I was following the white rabbit again....

 

Matrix console FX, windows, 100 lines.

 

Code

Spoiler

/* Console Matrix Effect, needs work, 100 lines, KeyboardCowboy, 8/13/2019 */
#include <time.h>
#include <algorithm>
#include <stdio.h>
#include <windows.h>
#define ESC "\x1b"
#define CSI "\x1b["
#define DEFINE_CONSOLEV2_PROPERTIES
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
using namespace std;
bool EnableVTMode();
class Matrix {
public:
    Matrix(int y) {maxY = y; reset(); _step = rand()%maxY;}
    int getSize(void) {return length;}
    void reset(void);
    void gen(void);
    void step() {gen(); _step++;}
    int getNext(int &val, int y);
private:
    int maxY, length, _step, garb, *p;
};
int Matrix::getNext(int &val, int y) {
    garb = y-_step;
    if((garb >= 0) && (garb < length)) {
        val = p[garb];
        return garb; }
    if(_step > maxY) {
        delete[] p;
        reset(); }
    return 0;
}
void Matrix::reset(void) {
    length = rand()%(maxY-5)+3;
    p = new int[length];
    memset(p, 32, length*sizeof(int));
    _step = 0-length;
}
void Matrix::gen() {
    rotate(&p[0], &p[0]+1, &p[length]); //rot left
    p[length-1] = rand()%222+33;
}
int main() {
    int buf = 0, col = 0, tempSize = 0, rgbIndex = 0;
    srand (time(NULL));
    /* Borrowed Microsoft Code */
    bool fSuccess = EnableVTMode(); //First, enable VT mode
    if (!fSuccess) {
        printf("Unable to enter VT processing mode. Quitting.\n");
        return -1; }
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hOut == INVALID_HANDLE_VALUE) {
        printf("Couldn't get the console handle. Quitting.\n");
        return -1; }
    /* Borrowed Microsoft Code */
    CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo;
    GetConsoleScreenBufferInfo(hOut, &ScreenBufferInfo);
    COORD Size;
    Size.X = ScreenBufferInfo.srWindow.Right - ScreenBufferInfo.srWindow.Left + 1;
    Size.Y = ScreenBufferInfo.srWindow.Bottom -  ScreenBufferInfo.srWindow.Top + 1;
    printf(CSI "?1049h");   // Enter the alternate buffer
    printf(CSI "2J");       // Clear screen
    printf(ESC "[?25l");    // Hide cursor
    /* Welcome to the Matrix */
    Matrix *neo[(int)Size.X];
    for(int i = 0; i < (int)Size.X; i++)
        neo[i] = new Matrix((int)Size.Y);
    while(1) {
        for(int j = 0; j < (int)Size.X; j++) {
            for(int i = 0; i < (int)Size.Y; i++) {
                tempSize = neo[j]->getSize();
                rgbIndex = 255/(tempSize);
                col = neo[j]->getNext(buf, i);
                if(col) {
                    if(col == tempSize-1)
                        printf("\x1b[38;2;200;255;200m\x1b[%d;%dH%c", i+1, j+1, buf); //RGB, Working
                    else
                        printf("\x1b[38;2;0;%d;0m\x1b[%d;%dH%c", col*rgbIndex, i+1, j+1, buf); //RGB, Working
                } }
            neo[j]->step();
            //Sleep(20);
        } }
    return 0;
}
/* Borrowed Microsoft Code */
bool EnableVTMode() {
    // Set output mode to handle virtual terminal sequences
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hOut == INVALID_HANDLE_VALUE)
        return false;
    DWORD dwMode = 0;
    if (!GetConsoleMode(hOut, &dwMode))
        return false;
    dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    if (!SetConsoleMode(hOut, dwMode))
        return false;
    return true;
}

 

ScreenShot

Spoiler

image.png.7912797c948f2ab65c903102442cf044.png

-- Runs kinda slow.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Ive been using Python more recenty, though I also like Java and C++..... heres my backend which returns cool facts about space!

 

from flask import Flask, render_template
from flask_restful import Api, Resource, reqparse
import random
import json
from numpy import *
from threading import Thread

#setting up flask
app = Flask(__name__)
api = Api(app)

#----------

#reading stored array, allows for less junk in main.py and makes it easier to expand
with open('galaxy.json', 'r') as filehandle:  
    galaxy = json.load(filehandle)


#----------

#class for specific galaxy fact
class GalaxySpecific(Resource):
    def get(self, id):
        for data in galaxy:
            if(id == data["id"]):
                return data, 200
        return "Fact not found", 404

#class for random galaxy fact
class GalaxyRandom(Resource):
    def get(self):
        return random.choice(galaxy)

#class for all galaxy facts
class GalaxyIndex(Resource):
    def get(self):
        return galaxy

#----------

#routing to index page
@app.route('/')
def index():
    return render_template('index.html')

#routing to 404 page
@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404

#routing to the facts client
@app.route('/client/')
def client():
	return render_template('client.html')

#----------

#adding galaxy api resources
api.add_resource(GalaxySpecific, "/galaxy/spec/<string:id>")
api.add_resource(GalaxyRandom, "/galaxy/rand/")
api.add_resource(GalaxyIndex, "/galaxy/index/")

#----------

#running webserver
def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():  
    t = Thread(target=run)
    t.start()

keep_alive()

 

and heres where it pulls the facts from:

 

[ {
    "id": "1", "fact": "Light year is a measure of distance, not time. It is the distance that light travels during one Earth year ( The speed of light is 300,000km/s, which means that this is a very, tremendously, amazingly huge distance of over 9.5 trillion km)"
}

,
{
    "id": "2", "fact": "AU, or astronomical unit is the distance between the Sun and the Earth, and it measures 8 light minutes and 19 light seconds, or 149.597 million kilometers in humans-can-achieve-it units."
}

,
{
    "id": "3", "fact": "To top it off, a unit called parsec is even longer than a light year. Measuring 3.26 light years, it is a function of an astronomical unit and a parallax angle of 1 degree. Its name is derived from \u201cparallax of one arcsecond\u201d"
}

,
{
    "id": "4", "fact": "The biggest known star currently is UY Scuti, a bright red supergiant, located 9500 light years away in the Scutum constellation. It is more than 1,708 times the size of the Sun. If UY Scuti was placed in our system instead of the Sun, it would engulf everything up to the orbit of Saturn."
}

,
{
    "id": "5", "fact": "The most massive star, and one of the hottest that we know of, is the RMC 136a1, with the mass of 315 Suns and the temperature of over 50000 K! It is just a brisk walk away of 163,000 light-years, sitting in the Large Magellanic cloud."
}

,
{
    "id": "6", "fact": "Universe is estimated to be 13.82 billion years old. Even though we know its age we don\u2019t really know its size since it\u2019s always expanding, so the light actually didn\u2019t have time to reach us yet from the furthest reaches of space. Current estimates, based on a phenomenon called redshift, are that it is at least 46 billion light years across."
}

,
{
    "id": "7", "fact": "Galaxies can collide. In fact, our own milky way is due a collision with Andromeda galaxy. Not to worry though, this is going to happen in over 4 billion years from now, and even when it happens, galactic distances are so vast that the chances of a star or a planet hitting each other are almost non-existent."
}

,
{
    "id": "8", "fact": "There are over 500 billion galaxies in the universe, by current estimates made by Hubble space telescope, but that number is probably to rise as we develop better telescope technology."
}

,
{
    "id": "9", "fact": "There are over 300 billion stars in our galaxy, the Milky Way. In the observable universe the estimate is that there are 70 billion trillion (7 x 1022) stars. Don\u2019t even try to wrap your head around that number."
}

,
{
    "id": "10", "fact": "A popular comparison that can illustrate these numbers is this: There are more stars in the universe than there are grains of sand on all the beaches and deserts on Earth."
}

,
{
    "id": "11", "fact": "Milky Way is our home galaxy. It\u2019s a spiral galaxy, with the supermassive black hole in its center and it spans between 100-200 thousand light-years. (It\u2019s kinda hard to measure such distances, so the current estimates are really rough)."
}

,
{
    "id": "12", "fact": "Milky Way has two major spiral arms that start at the central bar of stars, and slowly taper off. Our Solar system is located in one minor spiral arm called the Orion arm."
}

,
{
    "id": "13", "fact": "The biggest galaxy is over 30 times bigger than our own modest Milky Way. The IC 1101 is a supergiant elliptical galaxy and it spans over 5.8 million light years, with more than a 100 trillion stars that call it home. The Largest Galaxy In the Known Universe: IC 1101."
}

,
{
    "id": "14", "fact": "Galaxies come in different sizes, but also different shapes. The three main types of galaxies are elliptical, spiral and irregular. The Hubble classification is a bit more complex \u2013 Elipticals, spirals, lenticulars and irregulars, of which each category has subcategories."
}

,
{
    "id": "15", "fact": "The first spiral galaxy we discovered, besides our own, is the Whirlpool Galaxy (M51). It is estimated to be 23 million years away from the Milky Way."
}

,
{
    "id": "16", "fact": "Measuring distances to galaxies is tricky. We try to find a single star in that galaxy and measure the distance to it. If the galaxy is too far away to distinguish individual stars, astronomers find supernovae, which are much brighter than ordinary stars, and measure that distance."
}

,
{
    "id": "17", "fact": "There are 8 planets in our solar system. In order, from the closest to the Sun to the furthest, they are: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus and Neptune."
}

,
{
    "id": "18", "fact": "For a long time the little, distant Pluto was listed as a planet, but it has its own classification now: a dwarf planet."
}

,
{
    "id": "19", "fact": "The planets are separated into the planets of the inner solar system, and the outer system. There is a huge difference between these planets, both in their size and their composition. The planets of the outer system are known as the giant planets (or Jovian planets), while the inner planets are called the terrestrial planets."
}

,
{
    "id": "20", "fact": "The inner planets are fairly small, with the Earth being the biggest among them. They are pretty dense, with a rocky composition, iron-nickel cores and few or no satellites. Each of these has some sort of surface features, such as impact craters, volcanoes and canyons."
}

,
{
    "id": "21", "fact": "Revolution is what we call one complete circle that a planet makes around the Sun, and rotation is a single full circle around the planet\u2019s axis. Earth\u2019s rotation is what we call a day, and its Revolution is one year."
}

,
{
    "id": "22", "fact": "Mercury is the planet closest to the Sun. It has a year of 88 days, and a day that lasts almost 60 Earth days. On the side that is facing towards the Sun it has a scorching surface temperature of over 700K (423 C), but on the other side it\u2019s surprisingly freezing with temperatures below 0 C."
}

,
{
    "id": "23", "fact": "The reason for this huge temperature difference is because of Mercury\u2019s long day. The dark side is so cold that there are even hints that there might be actual traces of water ice."
}

,
{
    "id": "24", "fact": "Even though the Mercury is the planet nearest to the Sun, Venus is actually the hottest. That is because Venus has an extremely dense carbon-dioxide atmosphere, which creates the strongest green-house effect known to man."
}

,
{
    "id": "25", "fact": "The pressure on the surface of Venus is as high as it is at the depth of 1 kilometer in Earth\u2019s oceans. The temperature is at least 735 K (462 \u00b0C), and its surface features look as what we normally think Hell looks like."
}

,
{
    "id": "26", "fact": "The Earth is actually closest to the Sun during January and farthest during July. The seasons we experience are due to the tilt of the Earth\u2019s axis, which makes certain areas get more sunshine at the different parts of its revolution."
}

,
{
    "id": "27", "fact": "Earth\u2019s orbit starts at an altitude of 2000 km. If we were to build a staircase from the sea level to orbit, it would take two weeks to climb."
}

,
{
    "id": "28", "fact": "The only natural satellite that orbits the Earth is Moon. It is one of the largest and densest satellites, but it doesn\u2019t have any atmosphere. The Moon is in synchronous orbit around the Earth, which means that we always see the same side of the Moon."
}

,
{
    "id": "29", "fact": "Distance to the Moon from Earth is 384,402 km (238,856 mi). You could fit all the planets of our system in there, with room to spare."
}

,
{
    "id": "30", "fact": "Moon gravity is 1/6 of Earths. If there was a pool on the Moon, swimmers could jump out of the water like dolphins, launching themselves more than a meter high."
}

,
{
    "id": "31", "fact": "There is no dark side of the Moon. The side that we don\u2019t see is illuminated by the Sun as often as the side that we face."
}

,
{
    "id": "32", "fact": "Every year there are at least 2 lunar (Moon) eclipses, but it can happen that there are no solar eclipses. While the solar eclipses are rare, they still occur at least once every 18 months. The reason why we feel it\u2019s much rarer than that is because they can be seen only from a fairly small area on the Earth."
}

,
{
    "id": "33", "fact": "Lunar eclipse happens when the Moon passes into the Earth\u2019s umbra (shadow), which means that Earth is blocking the sunlight that usually falls on the Moon. This event can happen up to four times per year."
}

,
{
    "id": "34", "fact": "During the lunar eclipse, we still see the Moon, but it has a weak reddish tint. We sometimes call it the Blood Moon. Blood Moon during the lunar eclipse."
}

,
{
    "id": "35", "fact": "A Blue Moon is not really blue. It\u2019s just a name for a second full moon that happens in one month, every now and then."
}

,
{
    "id": "36", "fact": "The solar eclipse occurs when the Moon passes right in front of the Sun, and it casts its shadow on Earth. The area of Earth that is in the Moon\u2019s shadow is the only part on Earth where that particular eclipse can be seen. This is the only time when we can see the Sun\u2019s corona from the Earth."
}

,
{
    "id": "37", "fact": "Mars is the fourth planet from the Sun, and it is the second smallest planet in our solar system. It has much weaker gravity than Earth: with the gravity of 38%, a 100 kg person would weight only 38kg on Mars!"
}

,
{
    "id": "38", "fact": "The red planet is also known for having some of the most impressive surface features. It is the home of Olympus Mons, the largest volcano in the solar system, and Valles Marineris a vast network of Canyons, second only to the rift valleys on Earth."
}

,
{
    "id": "39", "fact": "Olympus Mons is almost 22 km high, more than 2.5 times as tall as our highest mountain Mont Everest. Vertical comparison of Olympus Mons with Mount Everest (shown sea-level-to-peak) and Mauna Kea on Earth (measurement is sea-level to peak, not base to peak)."
}

,
{
    "id": "40", "fact": "Mars has two tiny moons: Phobos and Deimos. It is believed that these moons are actually asteroids that have been caught up in the Mars\u2019s asteroid field. The names of these satellites mean Fear and Dread, which is very suitable for the companions of the roman god of war."
}

,
{
    "id": "41", "fact": "The outer planets are Jupiter, Saturn, Uranus and Neptune. These humongous planets are also known as Jovian planets, in honor of Jupiter, the biggest of them. These planets together make up 99% of the mass that is orbiting the Sun."
}

,
{
    "id": "42", "fact": "Jupiter and Saturn are made of primarily hydrogen and helium, while the Uranus and Neptune have more icy components \u2013 a reason why these two are often called the ice giants."
}

,
{
    "id": "43", "fact": "Each of the outer planets has rings around it, but only the Saturn\u2019s\u2019 are visible to us from Earth. These rings are composed of small chunks of ice and rock, and they are surprisingly thin (less than a kilometer thick). If Saturn\u2019s rings were a meter long, they would be 10000 times thinner than a razorblade. In this simulated image of Saturn's rings, color is used to present information about ring particle sizes in different regions based on the measured effects of three radio signals."
}

,
{
    "id": "44", "fact": "The Saturn has seven distinct rings. It is unknown why these rings are so prominent, but it is believed that it has something to do with the large number of moons that orbit Saturn. The rings have a radius of about 250000 km. If one was to drive a car on one of the Saturn\u2019s rings, at the speed of 100 km/h, it would take over 14 weeks to finish one lap."
}

,
{
    "id": "45", "fact": "The biggest moon that is orbiting Saturn is Titan. It is the only natural satellite that has dense atmosphere, mostly composed of nitrogen. Due to its low surface temperature of 94 K (\u2212179.2 \u00b0C), it has lakes of methane, which makes it the only celestial body that we know of that has surface liquid, besides the Earth."
}

,
{
    "id": "46", "fact": "Jupiter is the biggest planet in our system, over 300 times bigger than Earth. It is so big that it is sometimes considered a failed star. In fact, it emits more energy than it receives from the Sun."
}

,
{
    "id": "47", "fact": "Jupiter has a huge perpetual storm that rages in its upper layers, known as the Great Red Spot. It is so big that the whole Earth could fit into it. Gas giants have a very turbulent atmosphere, so storms such as this are fairly common. True enough, both Neptune and Saturn have their own spots, called the Great Dark Spot and the Great White Spot, respectively. Jupiter\u2019s Great Red Spot is a cyclone that\u2019s presently about 1.2 times as big as Earth. As recently as 1979, it was twice Earth\u2019s diameter as illustrated here."
}

,
{
    "id": "48", "fact": "Jupiter has 67 natural satellites (or moons), the highest number of all the planets in the solar system. The largest and most famous are Io, Europa, Ganymede and Callisto."
}

,
{
    "id": "49", "fact": "Pluto is not the only dwarf planet in our system. Besides Pluto there are four other dwarf planets in our system: Ceres, Haumea, Makemake and Eris."
}

,
{
    "id": "50", "fact": "All the dwarf planets, except Ceres, are called the Plutoids in honor of the ex-planet Pluto. This designation is reserved for all the dwarf planets that orbit the Sun beyond Neptune."
}

,
{
    "id": "51", "fact": "The definition of a planet has been set at an astronomical conference in Prague, Czech Republic, in the summer of 2006. The new definition states that the planet: Is in orbit around the Sun. Has sufficient mass to assume a nearly round shape. Has cleared the neighborhood around its orbit. (This means that there are no other celestial bodies of similar size in its orbit path.)"
}

,
{
    "id": "52", "fact": "The main difference between a planet and a dwarf planet is that the dwarf planets have not cleared their neighborhood. Dwarf planets tend to orbit in zones shared with similar objects that can cross their path around the Sun, such as the asteroids. Dwarf planets are also smaller than the planet Mercury, the smallest planet."
}

,
{
    "id": "53", "fact": "There is an asteroid belt that orbits Sun between Mars and Jupiter. It is believed that these asteroids are remnants of a planet that failed to form during the solar system creation. Asteroids can vary in size from a few meters to hundreds of kilometers."
}

,
{
    "id": "54", "fact": "Contrary to the movies and popular belief, the asteroid belt is fairly easy to maneuver in a spacecraft. Even though there are over a million asteroids estimated in the belt, they populate such a huge area of space that the distances between individual asteroids are at least several kilometers."
}

,
{
    "id": "55", "fact": "The crown of the asteroid belt is Ceres, recently classified a dwarf planet. Ceres has a radius of around 950km, and strong enough gravity that it pulled itself into a roughly spherical shape, granting it the almost-planet title."
}

,
{
    "id": "56", "fact": "The solar wind is a combination of particles, mostly ionized atoms from the stars corona, and magnetic fields produced by the star. It bathes our planet constantly, and the radiation would be deadly, if we were not protected by Earth\u2019s magnetic field."
}

,
{
    "id": "57", "fact": "The area behind Neptune is called the Kuiper belt. It is a disc shaped region of comets, asteroids and dwarf planets, including Pluto. There are estimated thousands of bodies larger than 100 km and trillions of comets. Even the big bodies are not typical asteroids, but frozen liquids and gasses such as methane, ammonia and water."
}

,
{
    "id": "58", "fact": "Comets are space snowballs, composed of frozen water and gasses, rock and dust. The nucleus of a comet is usually not bigger than 10 km, but as the comet approaches the Sun and the frozen gases begin to evaporate, the nucleus can expand to over 80 000km."
}

,
{
    "id": "59", "fact": "The tail of a comet appears when it gets close enough to Sun and starts to melt. It is caused by the radiation pressure from the Sun which \u201cblows\u201d away some of the matter from the evaporating comet nucleus, which is why the tail always faces away from the Sun. These tails can be even millions of kilometers long."
}

,
{
    "id": "60", "fact": "The earliest recorded comet is the Halley comet, which was first observed in ancient china in 240 B. C. It makes one orbit around the Sun every 75 years. Famous writer, Mark Twain, was born on the year when the Halley comet passed, and died on the year when it went by again. Both times he had missed it."
}

,
{
    "id": "61", "fact": "Exoplanets are the planets we found that are outside our solar system. These extrasolar planets are very hard to detect, and only in the past 10 years or so have we been able to regularly find new ones. We have so far discovered over 2000 exoplanets."
}

,
{
    "id": "62", "fact": "The smallest recorded exoplanet is twice the size of the Moon, while the most massive has almost 30 times the mass of Jupiter. This gas giant is so big that is uncertain whether it\u2019s a planet, or a brown dwarf (the smallest type of a star)."
}

]

 

A client which accesses these facts is at http://client.api.piemadd.com/ and you can use the api yourself with the endpoint http://api.piemadd.com. You can feed it /galaxy/spec/<id>/ where id is the id of a specific fact, /galaxy/rand/ which returns a random fact, and /galaxy/index/ which returns the whole json file.

i like trains 🙂

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...
  • 1 month later...

I made a simple one that opens up one of five websites depending on what key you press.

import os
import time
import webbrowser
def main():
    while True:
        website = input ("Choose a website to open. y = YouTube | g = Google | gm = gmail | lt = Linus Tech Tips forum | f = facebook")

        if website == 'y':
            webbrowser.open('https://youtube.com')

        if website == 'g':
            webbrowser.open('https://google.com')

        if website == 'gm':
            webbrowser.open('https://gmail.com')

        if website == 'lt':
            webbrowser.open('https://linustechtips.com/main')

        if website == 'f':
            webbrowser.open('https://facebook.com')

        else:
            print("Please type a valid character from the list.")
            main()

        quit()    

main()

 

CPU: Ryzen 5 5600x  | GPU: GTX 1070 FE | RAM: TridentZ 16GB 3200MHz | Motherboard: Gigabyte B450 Aorus M | PSU: EVGA 650 B3 | STORAGE: Boot drive: Crucial MX500 1TB, Secondary drive: WD Blue 1TB hdd | CASE: Phanteks P350x | OS: Windows 10 | Monitor: Main: ASUS VP249QGR 144Hz, Secondary: Dell E2014h 1600x900

Link to comment
Share on other sites

Link to post
Share on other sites

A simple python script to encrypt or decrypt a file with AES

#### Needs to be ran as root/admin
import pyAesCrypt
import getpass
import argparse
from os import stat, remove
import os
import sys

# overwrite file with random data to securely wipe it
def secure_wipe(path, passes=1):
    with open(path, "ba+") as delfile:
        length = delfile.tell()
        for i in range(passes):
            delfile.seek(0)
            delfile.write(os.urandom(length))
    os.remove(path)

# encryption/decryption buffer size - 64K
bufferSize = 64 * 1024

def encrypt(password, filename):
    path = filename
    with open(path, "rb") as Orig:
        with open(path +".aes", "wb") as OrigEnc:
            pyAesCrypt.encryptStream(Orig, OrigEnc, password, bufferSize)
    secure_wipe(path)

def decrypt(password, filename):

    # get encrypted file size
    encFileSize = stat(filename).st_size
    # make sure output filename doesn't already exist
    # so you don't accidentally overwrite a file
    try:
        check_file = open(filename.replace(".aes", ""), 'r')
        print("Error: This action would overwrite a file that already exists.")
    except FileNotFoundError:
        with open(filename, "rb") as enc: # check if you can use filename instead of path
            with open(filename.replace(".aes", "", 1), "wb") as dec:  # create output file
                try:
                    # decrypt file stream
                    pyAesCrypt.decryptStream(enc, dec, password, bufferSize, encFileSize)
                except ValueError:
                    # remove output file on error
                    enc.close()
                    dec.close()
                    secure_wipe(filename.replace(".aes", ""))
                    print("Error: Password not valid.")
                    sys.exit()
        secure_wipe(filename)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", help="ENCRYPT EXAMPLE: -e filename", required=False)
    parser.add_argument("-d", help="DECRYPT EXAMPLE: -d filename", required=False)
    args = parser.parse_args()
    try:
        password = getpass.getpass()
    except Exception as error: 
        print('ERROR', error) 
    print("\nConfirm")
    try:
        password2 = getpass.getpass()
    except Exception as error: 
        print('ERROR', error) 
    if password == password2:
        if args.e:
            filename = args.e
            encrypt(password, filename)
        if args.d:
            filename = args.d
            if filename.endswith(".aes"):
                decrypt(password, filename)
            else:
                print("\nError: Make sure file you are decrypting ends with .aes extension.\n")
    else:
        print("\nPassword does not match.")
		
main()

I'm more of a C# and PHP guy, but Python can be fun sometimes ?

Link to comment
Share on other sites

Link to post
Share on other sites

Usefulness is debatable (lol). But I've written a naive multi-core prime number generator as an exercise.

Spoiler

package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

// NumberGenerator generate numbers for processing
func NumberGenerator(lower, upper uint) <-chan uint {
	numChannel := make(chan uint, runtime.NumCPU()*10)
	go func() {
		for idx := lower; idx <= upper; idx++ {
			if idx%2 == 0 {
				continue
			}
			numChannel <- idx
		}
		close(numChannel)
	}()
	return numChannel
}

// PrimeProcessor concurrenly checks numbers in channel and puts prime numbers to output channel
func PrimeProcessor(numChan <-chan uint, output chan<- uint, wg *sync.WaitGroup) {
	for idx := 0; idx < runtime.NumCPU(); idx++ {
		wg.Add(1)
		go func() {
			for num := range numChan {
				if IsPrime(num) {
					output <- num
				}
			}
			wg.Done()
		}()
	}
}

// IsPrime checks if the number is a prime number
func IsPrime(num uint) bool {
	checkingBound := num / 3
	for divisor := uint(3); divisor <= checkingBound; divisor += 2 {
		if num%divisor == 0 {
			return false
		}
	}
	return true
}

// PrimeNumbers returns an array of prime numbers that exist within the given bounds
func PrimeNumbers(lower, upper uint) []uint {
	resultChannel := make(chan uint, runtime.NumCPU()*10)
	numChannel := NumberGenerator(lower, upper)

	results := make([]uint, 0, (upper-lower)/1000)
	go func() {
		for result := range resultChannel {
			results = append(results, result)
		}
	}()

	var wg sync.WaitGroup
	PrimeProcessor(numChannel, resultChannel, &wg)
	wg.Wait()

	close(resultChannel)
	return results
}

func main() {
	start := time.Now()
	results := PrimeNumbers(0, 1000000)
	finish := time.Now()
	for _, n := range results {
		fmt.Printf("%d\n", n)
	}
	fmt.Printf("Time spent calculating primes: %d ns\n", finish.Sub(start).Nanoseconds())
}

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

Quickly convert a string into a forgotten meme.

 

/* The language is C# */

public string MemeifyString(string toBeMemed, bool firstCharCaps)
{
  StringBuilder memeBuilder = new StringBuilder(toBeMemed.ToLower());
  
  for (int i = 0; i < memeBuilder.Length; i++)
  {
    if ((i % 2 != 0) && (firstCharCaps))
      memeBuilder[i] = memeBuilder[i].ToString().ToUpper()[0];
    
    else if (i % 2 == 0)
      memeBuilder[i] = memeBuilder[i].ToString().ToUpper()[0];
  }
  
  return memeBuilder.ToString();
}

 

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

It's 107 lines. I hope you forgive me for breaking 100 lines. It's a fairly efficient context-free deterministic parallel string rewriter (A simple L System engine), capable of rewriting roughly 12 GB of characters in 5 seconds on a modest machine (i7-6700HQ, HDD, 16GB RAM, Win10).

It can be made into a non-deterministic version simply by writing an IDictionary<char, string> that supports multiple values per key, and randomly selects the value for such a key, and using that for _productionRules.

 

    class ParallelSystem
    {
        private bool _alreadyRestructured;
        private readonly string _axiom;
        private readonly IDictionary<char, string> _productionRules;
        private List<List<char>> _segments;

        public string Axiom { get => _axiom; }
        public IDictionary<char, string> ProductionRules { get => _productionRules; }

        public ParallelSystem(string axiom, IDictionary<char, string> productionRules)
        {
            _axiom = axiom;
            _productionRules = productionRules;

            _segments = new List<List<char>>();
            _segments.Add(new List<char>(axiom));

            _alreadyRestructured = false;
        }

        private void RestructureSegments(int numSegments)
        {
            List<List<char>> newSegments = new List<List<char>>();

            for (int i = 0; i < numSegments; i++)
                newSegments.Add(new List<char>());

            string currentAxiom = this.ToString();
            int numElements = currentAxiom.Length;

            if (numSegments < numElements / 2)
                throw new ArgumentException("The number of new segments must be greater than or equal to half the number of characters in the current axiom.");

            int charsPerSegment = numElements / numSegments;
            int leftoverChars = numElements % numSegments;

            for (int segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
            {
                if (segmentIndex == 0)
                {
                    for (int axiomIndex = 0; axiomIndex < charsPerSegment; axiomIndex++)
                        newSegments[segmentIndex].Add(currentAxiom[axiomIndex * segmentIndex]);
                }

                else
                {
                    for (int axiomIndex = 1; axiomIndex < charsPerSegment + 1; axiomIndex++)
                        newSegments[segmentIndex].Add(currentAxiom[axiomIndex * segmentIndex]);
                }
            }

            for (int remainingCharsIndex = currentAxiom.Length - leftoverChars; remainingCharsIndex < currentAxiom.Length; remainingCharsIndex++)
                newSegments[^1].Add(currentAxiom[remainingCharsIndex]);

            _segments = newSegments;
        }

        public void Produce()
        {
            if (!_alreadyRestructured && (GetCurrentLength() >= Environment.ProcessorCount))
            {
                RestructureSegments(Environment.ProcessorCount);
                _alreadyRestructured = true;
            }

            Parallel.ForEach(_segments, segment =>
            {
                List<char> backBuffer = new List<char>();

                foreach(char c in segment)
                {
                    string temp;

                    if (_productionRules.TryGetValue(c, out temp))
                        foreach (char d in temp)
                            backBuffer.Add(d);

                    else
                        backBuffer.Add(c);
                }

                segment.Clear();
                segment.AddRange(backBuffer);
            });
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();

            foreach (var v in _segments)
                foreach (char c in v)
                    builder.Append(c);

            return builder.ToString();
        }

        public int GetCurrentLength()
        {
            int sum = 0;
            foreach (var v in _segments)
                sum += v.Count;

            return sum;
        }
    }

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Is it cheating if I do this?

foo = 1, bar = 1;

It's two separate operations, but technically one line of code.

EDIT: What about this?

if(...){
	...
    for(...){
    	...
    }} // is bracket stacking allowed?

 

Link to comment
Share on other sites

Link to post
Share on other sites

Replying to @pierom_qwerty

It's a neat program, but I'm not sure many would consider it to be "useful". How should we rate the usefulness of a program?

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×