Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
fletch to 99

The under 100 line challenge!

Recommended Posts

On 6/14/2013 at 9:29 PM, deafboy said:

Under 100 lines... does that include comments?

 

This might be fun :)

just make inline comments, I'm very sure you're not desperate enough to sacrifice whole lines to just comments :)


Bloodshot

First PC Build and Generally Very High End

Originally planned for December 2017 | 

 

Build Log Post

 

CPU: Intel Core i7-8700K

Cooler: Custom Hardline loop cooling GPU and CPU with 2 360 Rads

Thermal Compound: Thermal Grizzly Kryonaut Thermal Paste

Motherboard: Asus ROG MAXIMUS X HERO (WI-FI AC)

RAM: G.Skill Trident Z RGB 32GB (4 x 8GB) DDR4-3600 Memory

SSD: Samsung 960 Pro 512Gb M.2-2280 Solid State Drive

HDD: Seagate Barracuda PRO 4TB 3.5" 7200RPM Internal Hard Drive

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: Fractal Design Define R6 Blackout TG

PSU: EVGA SuperNOVA P2 1000W 80+ Platinum Fully-Modular ATX Power Supply

Case Fans: 7 Corsair Air Series SP120 High Performance Edition

Fan Controller: NZXT GRID+ V3 Fan Controller

Accessories:

  • Corsair Commander Pro Fan Controller

Set Up

  • Mouse: Razer Deathadder Elite
  • Keyboard: Razer Blackwidow X Chroma
  • Mousepad: Steelseries QcK Gaming Mousepad
  • Monitor: Asus ROG Swift PG278QR
  • Audio
    • AMP: Sennheiser GSX1000
    • Headphones: HyperX Cloud Alpha
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
  • IKEA Desk
    • IKEA White Linmon Tabletop (Longest Size)
    • IKEA 5 Black Olov Legs
    • IKEA White Alex Drawer
Link to post
Share on other sites
On 6/15/2013 at 8:08 AM, Cheesebaron said:

Is it allowed to use external libraries? Also, how do you count lines? For instance you can just cramp up all your code on one line if the language uses delimiters such as ;{}()[]

I just realized that that's soo smart, makes 10 files full of like 1,000 lines each, imports them all to one file, Best program in in 10 lines *insert mischievous face here*


Bloodshot

First PC Build and Generally Very High End

Originally planned for December 2017 | 

 

Build Log Post

 

CPU: Intel Core i7-8700K

Cooler: Custom Hardline loop cooling GPU and CPU with 2 360 Rads

Thermal Compound: Thermal Grizzly Kryonaut Thermal Paste

Motherboard: Asus ROG MAXIMUS X HERO (WI-FI AC)

RAM: G.Skill Trident Z RGB 32GB (4 x 8GB) DDR4-3600 Memory

SSD: Samsung 960 Pro 512Gb M.2-2280 Solid State Drive

HDD: Seagate Barracuda PRO 4TB 3.5" 7200RPM Internal Hard Drive

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: Fractal Design Define R6 Blackout TG

PSU: EVGA SuperNOVA P2 1000W 80+ Platinum Fully-Modular ATX Power Supply

Case Fans: 7 Corsair Air Series SP120 High Performance Edition

Fan Controller: NZXT GRID+ V3 Fan Controller

Accessories:

  • Corsair Commander Pro Fan Controller

Set Up

  • Mouse: Razer Deathadder Elite
  • Keyboard: Razer Blackwidow X Chroma
  • Mousepad: Steelseries QcK Gaming Mousepad
  • Monitor: Asus ROG Swift PG278QR
  • Audio
    • AMP: Sennheiser GSX1000
    • Headphones: HyperX Cloud Alpha
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
  • IKEA Desk
    • IKEA White Linmon Tabletop (Longest Size)
    • IKEA 5 Black Olov Legs
    • IKEA White Alex Drawer
Link to post
Share on other sites
On 6/15/2013 at 11:29 AM, ChrisPBacon2010 said:

YouTube competition winner generator, paste YouTube video link in and click generate.

 

All commenters will be recorded and get one entry each (excludes replies) and then one of those users gets randomly picked as the winner - https://gist.github.com/Cirx08/9ccbdce2d21cabefa472#file-random-youtube-winner

can you relink it because the link isn't working anymore and I want to see how you did it, it sounds realllly cool!!


Bloodshot

First PC Build and Generally Very High End

Originally planned for December 2017 | 

 

Build Log Post

 

CPU: Intel Core i7-8700K

Cooler: Custom Hardline loop cooling GPU and CPU with 2 360 Rads

Thermal Compound: Thermal Grizzly Kryonaut Thermal Paste

Motherboard: Asus ROG MAXIMUS X HERO (WI-FI AC)

RAM: G.Skill Trident Z RGB 32GB (4 x 8GB) DDR4-3600 Memory

SSD: Samsung 960 Pro 512Gb M.2-2280 Solid State Drive

HDD: Seagate Barracuda PRO 4TB 3.5" 7200RPM Internal Hard Drive

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: Fractal Design Define R6 Blackout TG

PSU: EVGA SuperNOVA P2 1000W 80+ Platinum Fully-Modular ATX Power Supply

Case Fans: 7 Corsair Air Series SP120 High Performance Edition

Fan Controller: NZXT GRID+ V3 Fan Controller

Accessories:

  • Corsair Commander Pro Fan Controller

Set Up

  • Mouse: Razer Deathadder Elite
  • Keyboard: Razer Blackwidow X Chroma
  • Mousepad: Steelseries QcK Gaming Mousepad
  • Monitor: Asus ROG Swift PG278QR
  • Audio
    • AMP: Sennheiser GSX1000
    • Headphones: HyperX Cloud Alpha
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
  • IKEA Desk
    • IKEA White Linmon Tabletop (Longest Size)
    • IKEA 5 Black Olov Legs
    • IKEA White Alex Drawer
Link to post
Share on other sites

4 lines of python code that returns the position of your mouse every time you press enter in the console of the running file, enjoy :).

 

import pyautogui as gui
while True:
	input()
    print(gui.position())

 


Bloodshot

First PC Build and Generally Very High End

Originally planned for December 2017 | 

 

Build Log Post

 

CPU: Intel Core i7-8700K

Cooler: Custom Hardline loop cooling GPU and CPU with 2 360 Rads

Thermal Compound: Thermal Grizzly Kryonaut Thermal Paste

Motherboard: Asus ROG MAXIMUS X HERO (WI-FI AC)

RAM: G.Skill Trident Z RGB 32GB (4 x 8GB) DDR4-3600 Memory

SSD: Samsung 960 Pro 512Gb M.2-2280 Solid State Drive

HDD: Seagate Barracuda PRO 4TB 3.5" 7200RPM Internal Hard Drive

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: Fractal Design Define R6 Blackout TG

PSU: EVGA SuperNOVA P2 1000W 80+ Platinum Fully-Modular ATX Power Supply

Case Fans: 7 Corsair Air Series SP120 High Performance Edition

Fan Controller: NZXT GRID+ V3 Fan Controller

Accessories:

  • Corsair Commander Pro Fan Controller

Set Up

  • Mouse: Razer Deathadder Elite
  • Keyboard: Razer Blackwidow X Chroma
  • Mousepad: Steelseries QcK Gaming Mousepad
  • Monitor: Asus ROG Swift PG278QR
  • Audio
    • AMP: Sennheiser GSX1000
    • Headphones: HyperX Cloud Alpha
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
  • IKEA Desk
    • IKEA White Linmon Tabletop (Longest Size)
    • IKEA 5 Black Olov Legs
    • IKEA White Alex Drawer
Link to post
Share on other sites

No code just a really handy tip for diagnosing issues when parsing CSV's.

 

Count the number of newlines in your data/file, then compare it to the number of rows in the parsed CSV.  Should be pretty much the same +- 2-3 lines (depending on how empty rows + headers are handled).  If it's too different have it throw and error.  Really hand for catching CSV's with quotes/commas not properly escaped.  

 

Only situation you really have to watch out for is when the data in a field can contain a new line, but if you're comfortable with regex you can usually find a way to get around that.

 

 

 

Link to post
Share on other sites

93 lines of subpar goodness.

/* 
 ----| Shitware |----
 password generator, uses the mouse as a source of entropy.
 CodeNova
 3/26/2019
 -----------------------
 Results from ENT test
 http://www.fourmilab.ch/random/
  
 Entropy = 0.999986 bits per bit.

 Optimum compression would reduce the size
 of this 90032 bit file by 0 percent.

 Chi square distribution for 90032 samples is 1.69, and randomly
 would exceed this value 19.37 percent of the times.

 Arithmetic mean value of data bits is 0.4978 (0.5 = random).
 Monte Carlo value for Pi is 3.153066667 (error 0.37 percent).
 Serial correlation coefficient is -0.004062 (totally uncorrelated = 0.0). 
*/

#include <windows.h>
#include <stdio.h>
#include <stdint.h>

#define PASSL 16
#define SAMLIM 2000

//void RAW_TEST(void);

int main(int argc, char **argv) {	
	//RAW_TEST(); //used for randomness analysis
	HWND hwnd;		//I hate windows API
	POINT aPoint;
	uint64_t x = 0, w = 0, s = 0xb5ad4eceda1ce2a9;
	uint32_t t = 0, lastX = 0, lastY = 0, result = 0, samples = 0;
	char password[PASSL] = {0};
	int i = 0;

	printf("Move Your Mouse!\n");
	
	while(samples < SAMLIM) {
		do {
			GetCursorPos(&aPoint);
		} while((aPoint.x == lastX) && (aPoint.y == lastY));
		lastX = aPoint.x;
		lastY = aPoint.y;
		t ^= (t << 1);				//Xor Shift Buffer
		t += (lastX ^ lastY);		
		x *= x;						//Middle Square Weyl Sequence PRNG
		x += (w += s);
		x = (x>>32) | (x<<32);		
		result = t ^ x;				//Xor results
		result = result&0xFF;		//Mask
		samples++;
		//char rule check, upper, lower, digits
		if(((result>47) && (result<58)) || ((result>64) && (result<91)) || ((result>96) && (result<123)))
			password[samples%PASSL] = result;
		printf("\rSamples: %0.5d", samples);
	}
	printf("\n\nNew Password: ");
	for(i = 0; i < PASSL; i++) {
		printf("%c", password[i]);
	}
	printf("\n");
	
	return 0;
}
/*
void RAW_TEST(void) {
	HWND hwnd;
	POINT aPoint;
	uint64_t x = 0, w = 0, s = 0xb5ad4eceda1ce2a9;
	uint32_t t = 0, lastX = 0, lastY = 0, result = 0;
	
	while(1) {
		do {
			GetCursorPos(&aPoint);
		} while((aPoint.x == lastX) && (aPoint.y == lastY));
		lastX = aPoint.x;
		lastY = aPoint.y;
		t ^= (t << 1);				//Xor Shift Buffer
		t += (lastX ^ lastY);		
		x *= x;						//Middle Square Weyl Sequence PRNG
		x += (w += s);
		x = (x>>32) | (x<<32);		
		result = t ^ x;				//Xor results
		result = result&0xFF;		//Mask
		printf("%c", result);
	}
}
*/
Spoiler

image.png.c25cd8d5f53d64594d6da6ac1b76a57e.png

 

Spoiler

Edit: Change to test


//output *.xbm image data
//prog.exe >> out.xbm
//gimp for render
int RAW_TEST(void) {
	HWND hwnd;
	POINT aPoint;
	uint64_t x = 0, w = 0, s = 0xb5ad4eceda1ce2a9;
	uint32_t t = 0, lastX = 0, lastY = 0, result = 0;
	
	uint32_t HEIGHT = 480, WIDTH = 480, sampleSize = 0;
	uint32_t samples = (HEIGHT*WIDTH)/8;
	
	printf("#define out_width %d\n", WIDTH);
	printf("#define out_height %d\n", HEIGHT);
	printf("static char out_bits[] = {\n");
	
	while(sampleSize < samples) {
		do {
			GetCursorPos(&aPoint);
		} while((aPoint.x == lastX) && (aPoint.y == lastY));
		lastX = aPoint.x;
		lastY = aPoint.y;
		t ^= (t << 1);				//Xor Shift Buffer
		t += (lastX ^ lastY);		
		x *= x;						//Middle Square Weyl Sequence PRNG
		x += (w += s);
		x = (x>>32) | (x<<32);		
		result = t ^ x;				//Xor results
		result = result&0xFF;		//Mask
		printf("0x%0.2X,", result);	//print hex
		if((sampleSize%15) == 14)
			printf("\n");
		sampleSize++;
	}
	printf("\b};\n");
	return 0;
}

Visual RND test

out.png.3dd4606b06feedbdb675680277280274.png

 

 

out.xbm

Link to post
Share on other sites

Changes video mode from ugly MS-DOS 80x25 to good 320x200 256 color (assembly, real mode, so no way to run this on a normal OS at all only smthn like a bootloader)

mov ah, 0x00
mov al, 0x13
int 0x10

 


Ryzen 5 1500X (2.8GHz@0.8875V) === ASRock B450 Gaming ITX/AC === 24GB DDR4 === Sapphire RX 570 4GB === Optane 800P 58GB === Patriot Burst 240GB === Toshiba Q300 240GB === beQuiet SFX Power 2 400W === Silverstone ML08B

Spoiler

OK, i'm not even gonna build this, but is this a good workstation?

PCPartPicker part list / Price breakdown by merchant

CPU: AMD Athlon X4 860K 3.7GHz Quad-Core Processor  ($72.99 @ Amazon) 
CPU Cooler: Corsair H100i 77.0 CFM Liquid CPU Cooler  ($168.99 @ Amazon) 
Motherboard: Gigabyte GA-F2A88XM-D3H Micro ATX FM2+ Motherboard  ($62.99 @ NCIX US) 
Memory: Samsung 32GB (1 x 32GB) DDR3-1866 Memory  ($256.99 @ SuperBiiz) 
Storage: Hitachi Ultrastar He8 8TB 3.5" 7200RPM Internal Hard Drive  ($479.99 @ Amazon) 
Video Card: EVGA GeForce GTX 960 2GB SuperSC ACX 2.0+ Video Card  ($179.99 @ NCIX US) 
Case: Lian-Li PC-V2130WX ATX Full Tower Case  ($499.99 @ Newegg) 
Power Supply: EVGA 430W 80+ Certified ATX Power Supply  ($23.98 @ Newegg) 
Total: $1745.91
Prices include shipping, taxes, and discounts when available
Generated by PCPartPicker 2016-02-09 12:48 EST-0500

 

Link to post
Share on other sites

I love Scala.

 

I've been doing a lot of Calcudoku puzzles lately, and my scratch work involves writing a list of all the combinations of numbers that satisfy the criteria for a cage then eliminating possibilities. Obviously I only do that for large cages (4+ numbers), but even then it takes up a lot of time and doesn't involve a whole lot of thinking.

 

I wrote a Scala program that takes as input the number of cells in the cage, the allowed numbers, and the operator and result for the cage, then spits out a list of all valid sets of numbers.

 

Things I do in one line in the program without stretching the definition of "in one line":

  • Prompt the user for a list of numbers, read the list of numbers to a string, split that string into a list of tokens, convert it to a list of integers, and sort it from greatest to least.
  • Build a new array of integers from the first one with repeated elements (to allow more than one of a single element in the combinations), generate the set of all combinations of those elements of a certain length, then filter out all the combinations that don't satisfy the cage's condition.
  • Convert an array of integers to a string with elements separated by the operator character and print it.

Seriously, Scala is all the best parts of Java, Haskell, and Python wrapped into a single language.

 

object CalcudokuSetGenerator extends App {
  var cont = true
  
  do{
    val len = scala.io.StdIn.readLine("Length: ").toInt
    val nums = scala.io.StdIn.readLine("Possible Numbers (separated by spaces): ").split(" ").map(_.toInt).sortWith(_>_)
    val opSel = scala.io.StdIn.readLine("Operator (+,-,*,/,|): ")
    val result = scala.io.StdIn.readLine("Result: ").toInt
    println
    
    val perms = nums.foldLeft(List[Int]()){case (a, b) => a ++ List.fill(len)(b)}.combinations(len).toList.filter(opFun(_, opSel, result))
    
    printList(perms, opSel)
    println
    
    cont = scala.io.StdIn.readLine("Continue? (y/n): ").toLowerCase.equals("y")
    println
  }while(cont)
  
  def opFun(lst: List[Int], str: String, res: Int): Boolean = str match{
    case "+" => lst.sum == res
    case "-" => lst.head - lst.tail.sum == res
    case "*" => lst.product == res
    case "/" => lst.head/lst.tail.product == res
    case "|" => lst.foldLeft(0){case (a, b) => a|b} == res
    case _ => true
  }
  
  def printList(lst: List[List[Int]], opstr: String): Unit = {
    for(arr <- lst){
      println(arr.mkString(opstr))
    }
  }
}

 


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

-Because you actually care if it makes sense.

Link to post
Share on other sites

Escaping HTML Characters in Javascript

	function escapeHTML(str)
	{
	    if(typeof str == 'string')
	    {
	        return str.replace(/[^a-z\d\s]/gi, function(c)
	        {
	            return '&#' + c.charCodeAt(0).toString() + ';';
	        });
	    }
	    else
	    {
	        return str;
	    }
	}

Javascript doesn't include a built in function for escaping HTML characters.  Something people forget about is that in addition to the standard escape sequences of 

< => &lt;

> => &gt;

etc.

 

You can also escape represent any character as it's unicode value in hex or in base 10.

For instance, the ampersand & has a ascii/unicode decimal value of 38, so it could be represented as &#38;

This function will replace anything that isn't either a space or an alphanumeric character as it's escaped value.

 

For those of you who read it this far before replying and complaining, yes, I am well aware of innerText, but there are times when you're building an HTML string, and it's much easier to go ahead and escape any text as the string's being built, rather than having to build it, then go back to each node and add the necessary text in.

Link to post
Share on other sites

I've been benchmarking different types of code in Scala, and I just got the bulk benchmarking utility right about where I want it.

 

With full documentation, no less.

 

package bulk_bench

import java.io.{File, PrintWriter}

import ichi.bench.Thyme
import ichi.bench.Thyme.Benched

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 Joseph Schulte
  */
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] = try{
    val benchResult = Benched.empty
    tst.benchWarm(tst.Warm(func))(benchResult)
    Success(benchResult)
  }catch{
    case e: Throwable => Failure(e)
  }
}

 


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

-Because you actually care if it makes sense.

Link to post
Share on other sites

A parallel-processing brute-force SHA-256 cracker:

 

import java.security.MessageDigest

import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector

object EncryptionCracker {
  def crackLazy(hash: String, charSet: Vector[Char], len: Int, num: Int): Option[String] = {
    @tailrec
    def getMatch(lst: LazyList[String], bid: Int): Option[String] = {
      print(s"Checking Block $bid... ")
      def hit = lst.take(num).to(ParVector).find(str => getHash(str).equalsIgnoreCase(hash))
      def nxt = lst.drop(num)
      hit match{
        case Some(str) =>
          println("Match")
          Some(str)
        case None if nxt.nonEmpty =>
          println("Loop")
          getMatch(nxt, bid + 1)
        case None =>
          println("Fail")
          None
      }
    }
    
    def perms = charSet
      .flatMap(Vector.fill(len)(_))
      .combinations(len)
      .flatMap(_.permutations.map(_.mkString)).to(LazyList)
    
    getMatch(perms, 0)
  }
  
  def getHash(str: String): String = {
    val digester = MessageDigest.getInstance("SHA-256")
    digester.digest(str.getBytes("UTF-8")).map("%02x".format(_)).mkString
  }
}

 


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

-Because you actually care if it makes sense.

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 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 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 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 post
Share on other sites

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 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 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 post
Share on other sites
#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 post
Share on other sites

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 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 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


×