Jump to content

The under 100 line challenge!

fletch to 99

I had written a small script to find very large prime numbers in unix shell....i'll have to think back.  It's "useful" only if you find a prime number large enough to win the $150k prize money though.  I got stumped trying to run it on my old dual x5690 server though...I need to get back to it...

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...
On 6/14/2013 at 9:13 PM, IntelvsAMD said:

I can make the most useful program in 1 line. Remove all white spaces ^-^. 

Yes. You are correct.

unless you are using something like Python

TsmDan Studios and Computer Epicenter take absolutely no liability or responsibility for any damages caused by operation on your device. If you damage something, don't blame it on me. If I break something, it's not my fault.

WARNING: Opening a laptop will immediately void any warranty on that laptop

WARNING: Your price for Builds will increase twofold because of insurance

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

Here is a renaming utility I made in python that I use often.

I use it to change the names of files for certain tasks.

 

import os



def changeText():
    string2edit = input("What string do you want to edit? ")
    string2output = input("What do you want to replace it with? ")
    for fileName in os.listdir("."):
        os.rename(fileName, fileName.replace(string2edit, string2output))

            
if __name__ == "__main__":
    changeText()



 

Link to comment
Share on other sites

Link to post
Share on other sites

I could never make anything that is any good under 100 lines.

if day == Friday:

  Celebrate()

Link to comment
Share on other sites

Link to post
Share on other sites

Ascii clock, it looks awful, but it works, c++.

 

/*
 * Ascii clock that runs in the console, windows
 */

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <time.h>
#include <windows.h> //...win api, ugh

const char zero[49] = {"  ___    / _ \\  | | | | | | | | | |_| |  \\___/  "};       //8x6+1
const char one[31] = {" __  /_ |  | |  | |  | |  |_| "};                            //5x6+1
const char two[43] = {" ___   |__ \\     ) |   / /   / /_  |____| "};               //7x6+1
const char three[49] = {" ____   |___ \\    __) |  |__ <   ___) | |____/  "};       //8x6+1
const char four[55] = {" _  _    | || |   | || |_  |__   _|    | |      |_|   "};   //9x6+1
const char five[49] = {" _____  | ____| | |__   |___ \\   ___) | |____/  "};        //8x6+1
const char six[49] = {"   __     / /    / /_   | '_ \\  | (_) |  \\___/  "};        //8x6+1
const char seven[55] = {" ______  |____  |     / /     / /     / /     /_/     "};  //9x6+1
const char eight[49] = {"  ___    / _ \\  | (_) |  > _ <  | (_) |  \\___/  "};      //8x6+1
const char nine[49] = {"  ___    / _ \\  | (_) |  \\__, |    / /    /_/   "};       //8x6+1
const char colon[19] = {" _ (_)    _ (_)   "};                                      //3x6+1

const char width[11] = {8, 5, 7, 8, 9, 8, 8, 9, 8, 8, 3};
char *index[11] = {(char*)zero, (char*)one, (char*)two, (char*)three, (char*)four,
                    (char*)five, (char*)six, (char*)seven, (char*)eight, (char*)nine, (char*)colon};

void display_time(char _time[]);    //ascii to dec, to ascii font
void gotoxy(int x, int y);          //goes to x,y console
void clear_line(void);              //blanks line of text

int main() {
    char string_time[50] = {0};
    char *pch;
    time_t rawtime, rawOld;

    while(1) {
        time (&rawtime);
        if(difftime(rawtime, rawOld)) {
            time (&rawOld);
            sprintf(string_time, "%s", ctime (&rawtime));
            pch = strtok (string_time, " ");
            for(int i = 0; i < 3; i++)
                pch = strtok (NULL, " ");
            gotoxy(0,0);
            printf("ClockTerm - ASCII - 2020\n");
            display_time(pch);
        }
        Sleep(1); //CPU break
    }
    return 0;
}
//jacked from stackoverflow
void gotoxy(int x, int y) {
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void clear_line(void) {
    char _space[61] = {'\0'};
    memset(_space, ' ', 60);
    printf("%s\r", _space); //prints 60 spaces, returns home
}

void display_time(char _time[]) {
    for(int y = 0; y < 6; y++) {
        clear_line();
        for(int i = 0; i < 8; i++)
            for(int j = 0; j < width[_time[i]-48]; j++) {
                char *_temp = index[_time[i]-48];
                printf("%c", _temp[j+(width[_time[i]-48] * y)] );
            }
        printf("\n");
    }
}
//line 77
Spoiler

image.png.51ef75d9ebfd1bce047bf57287d4073d.png

 

Link to comment
Share on other sites

Link to post
Share on other sites

Random Binary Generator 5,000

 

/***********************************************
 * Comes as is, no warranty
 * Compiler option: -std=c++11
 * optimize -O3
 * Capable of generating mass random files for
 * testing transfer stability.
 ***********************************************/

#include <iostream>
#include <chrono>
#include <random>
#include <string.h>

#define BYTE_FRAME 4194304 //4096
#define A_SIZE 1048576 //1024

int main(int argc, char* argv[]) {
    if(argc < 2) {
        printf("Usage: %s -f file.bin -b byteVal -s b/k/m/g -n #files\n", argv[0]);
        printf("\t%s -f 84byte.bin -b 84\n", argv[0]);
        printf("\t%s -f 1gig.bin -b 1 -s g\n", argv[0]);
        printf("\t%s -f 100x1k.bin -b 1 -s k -n 100\n", argv[0]);
        return 1;
    }
    printf("------------------------------------------\n");
    printf("|   The Random Binary Generator 5,000!   |\n");
    printf("------------------------------------------\n");

    signed long long byte_count_master = 0, byte_count = 0;
    int file_index = 0, files_to_gen = 1, file_count = 0;

    for(int i = 0; i < argc; i++) {
        if(!strcmp("-f", argv[i]))
            file_index = i+1;
        if(!strcmp("-b", argv[i]))
            byte_count_master = std::stoll(argv[i+1], NULL, 0);
        if(!strcmp("-s", argv[i])) {
            char *_tmp = argv[i+1];
            if(_tmp[0] == 'b') byte_count_master*=1;
            if(_tmp[0] == 'k') byte_count_master*=1024;
            if(_tmp[0] == 'm') byte_count_master*=(1024*1024);
            if(_tmp[0] == 'g') byte_count_master*=(1024*1024*1024);
        }
        if(!strcmp("-n", argv[i]))
            files_to_gen = std::stoi(argv[i+1], NULL, 0);
    }
    printf("Now Running\n");
    auto _start = std::chrono::high_resolution_clock::now();
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    printf("seed: %u\n", seed);

    std::mt19937 generator(seed);
    std::uniform_int_distribution<int> distribution(0,4294967294);

    FILE *pFile;
    unsigned int *_rnd = new(std::nothrow) unsigned int[A_SIZE];
    if(!_rnd) {
        printf("Not Enough Memory!\n");
        return 1;
    }
    char file_name_buffer[501] = {0};

    while(file_count < files_to_gen) {
        byte_count = byte_count_master;

        if(files_to_gen == 1) snprintf(file_name_buffer, 500, "%s", argv[file_index]);
        else snprintf(file_name_buffer, 500, "%d_%s", file_count, argv[file_index]);

        pFile = fopen(file_name_buffer, "wb");
        if(pFile == NULL) printf("Error Opening File\n");

        while(byte_count > 0) {

            for(int i = 0; i < A_SIZE; i++)
                _rnd[i] = distribution(generator);

            if((byte_count - BYTE_FRAME) >= 0) {
                if(fwrite(_rnd, sizeof(char), BYTE_FRAME, pFile) < sizeof(_rnd))
                    printf("Write Error\n");
                byte_count -= BYTE_FRAME;
            }
            else {
                if(fwrite(_rnd, sizeof(char), byte_count, pFile) < byte_count)
                    printf("Write Error\n");
                byte_count = 0;
            }
        }
        fclose(pFile);
        file_count++;
    }
    delete[] _rnd;
    auto _end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> _elapsed = _end - _start;
    printf("Finished\n");
    printf("Time Taken: %.2f Seconds\n", _elapsed.count());
    return 0;
}
//line 98, I really could have used something like this a few months ago.

//100

This is the 3rd iteration, let me know if it doesn't work.

Spoiler

image.thumb.png.93583aaf6614e187f6ce899245bcc259.png

 

 

RndBin.exe

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

This program downloads YouTube videos, the video to audio class is because originally i wanted to download only the audio, but that's not as useful as the whole thing...

 

import pytube as pt
import urllib.request
import urllib.parse
import re
import datetime

lis = []
print("\nYouTube video Downloader v1.2\n")

print("----------------------------------------------------------------------------")

print("Write the title of the videos you want to download, as if you were using the youtube search bar, after you "
      "have finished \n"
      "press enter twice, before that you have to clarify the directory you want the files downloaded to...\n")

dir = input(r"Please enter the download directory, then press enter: ")

print("\n\nNow write the titles...")

try:

    while True:

        inp = input()
        if inp != "":

            lis.append(inp)
        else:

            n = 0
            for a in range(int(len(lis))):
                query_string = urllib.parse.urlencode({"search_query": lis[n]})

                html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)

                search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())

                inp = "http://www.youtube.com/watch?v=" + search_results[0]


                class Video_to_audio:

                    def __init__(self, url):
                        self.url = url

                    def convert(self):

                        vid = pt.YouTube(self.url)
                        stri = vid.streams.filter(file_extension='mp4').get_highest_resolution()
                        print("Dowloading: ", vid.title, "| ", str(datetime.timedelta(seconds=vid.length)), "hours",
                              "| ", vid.views, " views", "| ", "rating ", vid.rating, "\n")

                        stri.download(dir)

                        
                video = Video_to_audio(inp)
                video.convert()
                n += 1

            input("\nAll videos have been downloaded, press ENTER to exit")

            break
except:

    pass

 

Main PC [The Rig of Theseus]:

CPU: i5-8600K @ 5.0 GHz | GPU: GTX 1660 | RAM: 16 GB DDR4 3000 MHz | Case: Lian Li PC-O11 Dynamic | PSU: Corsair RM 650i | SSD: Corsair MP510 480 GB |  HDD: 2x 6 TB WD Red| Motherboard: Gigabyte Z390 Aorus Pro | OS: Windows 11 Pro for Workstations

 

Secondary PC [Why did I bother]:

CPU: AMD Athlon 3000G | GPU: Vega 3 iGPU | RAM: 8 GB DDR4 3000 MHz | Case: Corsair 88R | PSU: Corsair VS 650 | SSD: WD Green M.2 SATA 120 GB | Motherboard: MSI A320M-A PRO MAX | OS: Windows 11 Pro for Workstations

 

Server [Solution in search of a problem]:

Model: HP DL360e Gen8 | CPU: 1x Xeon E5-2430L v1 | RAM: 12 GB DDR3 1066 MHz | SSD: Kingston A400 120 GB | OS: VMware ESXi 7

 

Server 2 electric boogaloo [A waste of electricity]:

Model: intel NUC NUC5CPYH | CPU: Celeron N3050 | RAM: 2GB DDR3L 1600 MHz | SSD: Kingston UV400 120 GB | OS: Debian Bullseye

 

Laptop:

Model: ThinkBook 14 Gen 2 AMD | CPU: Ryzen 7 4700U | RAM: 16 GB DDR4 3200 MHz | OS: Windows 11 Pro

 

Photography:

 

Cameras:

Full Frame digital: Sony α7

APS-C digital: Sony α100

Medium Format Film: Kodak Junior SIX-20

35mm Film:

 

Lenses:

Sony SAL-1870 18-70mm ƒ/3.5-5.6 

Sony SAL-75300 75-300mm ƒ/4.5-5.6

Meike MK-50mm ƒ/1.7

 

PSA: No, I didn't waste all that money on computers, (except the main one) my server cost $40, the intel NUC was my old PC (although then it had 8GB of ram, I gave the bigger stick of ram to a person who really needed it), my laptop is used and the second PC is really cheap.

I like tinkering with computers and have a personal hatred towards phones and everything they represent (I daily drive an iPhone 7, or a 6, depends on which one works that day)

Link to comment
Share on other sites

Link to post
Share on other sites

Go program to get new Linus videos as Windows 10 notifications (thanks to libraries I didn't make). Can be easily expanded to other YouTubers or even other RSS/Atom feeds.

 

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/mmcdole/gofeed"
	"gopkg.in/toast.v1"
)

var ids = map[string]string{
	"Linus Tech Tips":   "UCXuqSBlHAE6Xw-yeJA0Tunw",
	"Techquickie":       "UC0vBXGSyV14uvJ4hECDOl0Q",
	"Tech Linked":       "UCeeFfhMcJa1kjtfZAGskOCA",
	"Short Circuit":     "UCdBK94H6oZT2Q7l0-b0xmMg",
	"Channel Super Fun": "UCBZiUUYeLfS5rIj4TQvgSvA",
	"LMG Clips":         "UCFLFc8Lpbwt4jPtY1_Ai5yA",
	"Carpool Critics":   "UCt-oJR5teQIjOAxCmIQvcgA",
}

func main() {
	for title, id := range ids {
		go waitOnFeed(title, fmt.Sprintf("https://www.youtube.com/feeds/videos.xml?channel_id=%s", id))
	}

	ch := make(chan struct{})
	<-ch // Do not exit. Program must be closed via interrupt / Task Manager
}

func waitOnFeed(feedName, feedURL string) {
	var t time.Time

	feed, err := gofeed.NewParser().ParseURL(feedURL)
	if err != nil {
		log.Println(feedURL, err)
	}
	t = newestItem(feed)

	for {
		time.Sleep(5 * time.Minute) // how much we sleep between polls -- adjust to your liking

		feed, err = gofeed.NewParser().ParseURL(feedURL)
		if err != nil {
			log.Println(feedURL, err)
			continue
		}

		for _, item := range feed.Items {
			if item.PublishedParsed.After(t) {
				// we have a new item -- notify the user
				toast := toast.Notification{
					AppID:               "LTT Update",
					Title:               fmt.Sprintf("New %s Video", feedName),
					Message:             item.Title,
					Icon:                "", // change to C:/path/to/icon.jpg if you want an icon for your notification
					ActivationArguments: item.Link,
					Audio:               toast.Mail,
					Duration:            toast.Long,
				}

				err = toast.Push()
				if err != nil {
					log.Fatal("could not push notification")
				}
			}
		}

		t = newestItem(feed)
	}
}

func newestItem(feed *gofeed.Feed) time.Time {
	var t time.Time
	for _, item := range feed.Items {
		if item.PublishedParsed.After(t) {
			t = *item.PublishedParsed
		}
	}
	return t
}

Code provided under 0BSD. Note that it has not really been tested and may not work.

 

Edit: Now that I think about it, the code has a serious design flaw: if YouTube waits more than 5 minutes after the video was published to update the feed, and reports the old time as the Publish Date, this code will not work. We should remember the newest item in the feed and compare it to that.

 

Edit: Fixed.

The Eight Fallacies of Distributed Computing

Essentially everyone, when they first build a distributed application, makes the following eight assumptions. All prove to be false in the long run and all cause big trouble and painful learning experiences.

  1. The network is reliable
  2. Latency is zero
  3. Bandwidth is infinite
  4. The network is secure
  5. Topology doesn’t change
  6. There is one administrator
  7. Transport cost is zero
  8. The network is homogeneous

        — Peter Deutsch

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...
program Addition

	implicit none

	real :: a, b

	real :: TheAnswer

		write(*,*) "Addition checker"

		write(*,*) "Enter number A "

		read(*,*) a

		write(*,*) "Enter number B "

		read(*,*) b

		TheAnswer = a + b

		write(*,*) a, " + ", b, " = ", TheAnswer

end program Addition

Not very useful but useful enough to count(hah)

Link to comment
Share on other sites

Link to post
Share on other sites

On 6/14/2013 at 7:27 PM, fletch to 99 said:

Here is mine here is the code in pastebin: https://pastebin.com/MzLG90ZK it is a calculator in Python in 56 lines, here is a video of my running it but if you want to use it you can use a python code editor such as pyCharm: https://www.youtube.com/watch?v=833aaM6ejuY 

edit:  don't know why it turned out as a quote but its a reply to submit my project.

Edited by TheDabbingDeveloper
cause i noticed i made a mistake and quoted it instead of reply
Link to comment
Share on other sites

Link to post
Share on other sites

Here's my entry. A .bashrc function that combines cd, ls, and mkdir, all into one:

function scd {
        if [ $# -eq 0 ]; then
                return 0
        fi
        if [ -d "$@" ]; then
                builtin cd "$@"
                ls
                return 0
        fi
        if [ ! -d "$@" ]; then
                mkdir "$@" && echo "scd: new directory created" && cd "$@"
                return 0
        fi
}

It is so useful so that you don't have to do BS like make a directory after trying to cd into it but it doesn't exist, or having to always run ls after entering a new directory.

Furry EE student, amateur radio operator, and part-time programmer. https://twitter.com/ntoskrnl4

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 months later...

Alright guys, this is totally useless but I like how it turned out, whoever figures out what this does gets free bragging rights. For anybody else I'll put the answer below.

 

// will work with whatever compiler I used when I initially wrote it
// modern p***y c++ compilers will complain about unidefined functions, unnamed types and incompatible pointer types
#include <stdlib.h>
s;char*c;main()
{for(scanf((char[]){37,115,0},c=malloc(1<<8)),s=0;*c!=0&&s>=0;s+=*c++==(1<<3|1<<5)?1:-1,printf(!(*c||s)?"YES":0));}


// tested, you can run it here https://repl.it/repls/RigidSickAddons#main.cpp
#include <iostream>
int s;char*c;int main()
{for(scanf((char[]){37,115,0},c=(char*)malloc(1<<8)),s=0;*c!=0&&s>=0;s+=*c++==(1<<3|1<<5)?1:-1,printf(!(*c||s)?"YES":0));}
Spoiler

Reads a string containing a configuration of brackets "(" and ")" and prints "YES" if the configuration was valid

( ( ) ( ) ) ( ) // valid

( ) ( ) // valid

( ) ) // invalid

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
# importing ~~cars~~ modules!

from random import sample
from time import sleep

# fancy drawing thing

def DrawMessage():
    print("\nDrawing", end = "", flush = True)	

    for i in range(3):
        sleep(0.7)
        print(".", end = "", flush = True)
        
def main():

    # variables

    list = []

    # intro? 

    print("================================================================")
    print("========================= Make a draw! =========================")
    print("================================================================\n")

    # reading participants

    print("Enter participants: ")
    p = input("NOTE: Enter \"-\" after the last participant. \n\n")

    while(p != "-"):
        list.append(p)
        p = input()


    # let's draw! (if there are participants, duh)

    if(len(list) > 0):
        
        # let's ask how many people will win this raffle! (we will use p because we are stingy as f**k!)
        
        while True: 
            p = int(input("\nEnter number of winners: "))
            if((p > 0) and (p < len(list))):
                break
            print("ERROR: Number is invalid. Please, enter a correct number.")
        
        # drawing...
        
        DrawMessage()
        
        w = sample(list, p)
        
        if(p == 1):
            print("\n\nThe winner is " + w[0] + ". Congratulations!")
            
        else:
            print("\n\nThe winners are: \n")
            j = 1
            for i in w:
                msg = "{0}. {1}" .format(j, i)
                print(msg)
                j += 1
                
            print("\nCongratulations!")
            
    else:
        print("\nNo participants have been entered.")

    # goodbye!
    input("\nPress Enter to exit.")
    
    
# go!

main()

A little something I made a while ago while learning python

Link to comment
Share on other sites

Link to post
Share on other sites

On 3/8/2020 at 5:45 AM, RandleMcmurphy said:

Random Binary Generator 5,000

 


/***********************************************
 * Comes as is, no warranty
 * Compiler option: -std=c++11
 * optimize -O3
 * Capable of generating mass random files for
 * testing transfer stability.
 ***********************************************/

#include <iostream>
#include <chrono>
#include <random>
#include <string.h>

#define BYTE_FRAME 4194304 //4096
#define A_SIZE 1048576 //1024

int main(int argc, char* argv[]) {
    if(argc < 2) {
        printf("Usage: %s -f file.bin -b byteVal -s b/k/m/g -n #files\n", argv[0]);
        printf("\t%s -f 84byte.bin -b 84\n", argv[0]);
        printf("\t%s -f 1gig.bin -b 1 -s g\n", argv[0]);
        printf("\t%s -f 100x1k.bin -b 1 -s k -n 100\n", argv[0]);
        return 1;
    }
    printf("------------------------------------------\n");
    printf("|   The Random Binary Generator 5,000!   |\n");
    printf("------------------------------------------\n");

    signed long long byte_count_master = 0, byte_count = 0;
    int file_index = 0, files_to_gen = 1, file_count = 0;

    for(int i = 0; i < argc; i++) {
        if(!strcmp("-f", argv[i]))
            file_index = i+1;
        if(!strcmp("-b", argv[i]))
            byte_count_master = std::stoll(argv[i+1], NULL, 0);
        if(!strcmp("-s", argv[i])) {
            char *_tmp = argv[i+1];
            if(_tmp[0] == 'b') byte_count_master*=1;
            if(_tmp[0] == 'k') byte_count_master*=1024;
            if(_tmp[0] == 'm') byte_count_master*=(1024*1024);
            if(_tmp[0] == 'g') byte_count_master*=(1024*1024*1024);
        }
        if(!strcmp("-n", argv[i]))
            files_to_gen = std::stoi(argv[i+1], NULL, 0);
    }
    printf("Now Running\n");
    auto _start = std::chrono::high_resolution_clock::now();
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    printf("seed: %u\n", seed);

    std::mt19937 generator(seed);
    std::uniform_int_distribution<int> distribution(0,4294967294);

    FILE *pFile;
    unsigned int *_rnd = new(std::nothrow) unsigned int[A_SIZE];
    if(!_rnd) {
        printf("Not Enough Memory!\n");
        return 1;
    }
    char file_name_buffer[501] = {0};

    while(file_count < files_to_gen) {
        byte_count = byte_count_master;

        if(files_to_gen == 1) snprintf(file_name_buffer, 500, "%s", argv[file_index]);
        else snprintf(file_name_buffer, 500, "%d_%s", file_count, argv[file_index]);

        pFile = fopen(file_name_buffer, "wb");
        if(pFile == NULL) printf("Error Opening File\n");

        while(byte_count > 0) {

            for(int i = 0; i < A_SIZE; i++)
                _rnd[i] = distribution(generator);

            if((byte_count - BYTE_FRAME) >= 0) {
                if(fwrite(_rnd, sizeof(char), BYTE_FRAME, pFile) < sizeof(_rnd))
                    printf("Write Error\n");
                byte_count -= BYTE_FRAME;
            }
            else {
                if(fwrite(_rnd, sizeof(char), byte_count, pFile) < byte_count)
                    printf("Write Error\n");
                byte_count = 0;
            }
        }
        fclose(pFile);
        file_count++;
    }
    delete[] _rnd;
    auto _end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> _elapsed = _end - _start;
    printf("Finished\n");
    printf("Time Taken: %.2f Seconds\n", _elapsed.count());
    return 0;
}
//line 98, I really could have used something like this a few months ago.

//100

This is the 3rd iteration, let me know if it doesn't work.

 

 

This actually makes me sad.... templates and std libraries and requiring c++ 11 for something that can be done in other languages in a few lines.

Go (golang) for example can do it in less than 20 lines using only built in stuff and you end up with a binary that doesn't require runtime dlls to work.

Link to comment
Share on other sites

Link to post
Share on other sites

54 minutes ago, mariushm said:

Go (golang) for example can do it in less than 20 lines using only built in stuff

Interestingly enough, here's a C# function to do the same thing, albeit without all of the console output:

public void WriteRandomBitsToFile(int bitLength, RNGCryptServiceProvider numberGenerator, string path)
{
  byte[] randomBytes = new byte[bitLength / 8];
  numberGenerator.GetBytes(randomBytes);
  
  using (FileStream file = new FileStream(path, FileMode.Create))
  {
    using (BinaryWriter writer = new BinaryWriter(file))
      writer.Write(randomBytes);
  }
}

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

On 7/14/2020 at 3:09 PM, mariushm said:

 

This actually makes me sad.... templates and std libraries and requiring c++ 11 for something that can be done in other languages in a few lines.

Go (golang) for example can do it in less than 20 lines using only built in stuff and you end up with a binary that doesn't require runtime dlls to work.

#include <random>
#include <fstream>
#define SIZE /*1kb*/ 1024   //size of rnd file
#define O_F_NAME "out.bin"  //output file name
int main() {
    printf("Here's a tissue\n");
    size_t _meow = 0;
    char *rnd = new char[SIZE] {0x00};
    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_int_distribution<char> distribution(0,255);
    while(_meow < SIZE) rnd[_meow++] = distribution(generator);
    std::ofstream output(O_F_NAME, std::ofstream::binary | std::ofstream::trunc);
    if(output.is_open()) output.write(rnd, SIZE);
    else printf("fail\n");
    output.close();
    delete[] rnd;
    printf("fin!\n");
    return 0;
} //line 20

I would really be interested in seeing the GO (golang) source you speak of. Every failure is an opportunity to learn.

 

Spoiler

#include <cstdio>
#include <cstdlib>
#include <ctime>
int main() {
    time_t t;
    srand((unsigned) time(&t));
    FILE *f = fopen("out.bin", "wb");
    for(int i=0; i<1024; i++) fputc((rand()%256), f);
    fclose(f); return 0;
} //line 10

 

Spoiler

Better still, use PowerShell.


$out = new-object byte[] 1024; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes('file.bin', $out)

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

This is 111 lines of Javascript code so far. does html and css count or not? Its almost finished. What do you think, any suggestions?

 Check what it does here https://fallout2rcg.000webhostapp.com/

 

Spoiler

const startButton_div = document.getElementById("startButton");
const version_input = document.getElementById("versionInput");
const traits_select = document.getElementById("traitSelect");
const skills_select = document.getElementById("skillSelect");
const traitsText = {
    1: "Fast Metabolism", 2: "Bloody Mess", 3: "Bruiser", 4: "Jinxed",
    5: "Small Frame", 6: "Good Natured", 7: "One Hander", 8: "Chem Reliant",
    9: "Finesse", 10: "Chem Resistant", 11: "Kamikaze", 12: "Sex Appeal",
    13: "Heavy Handed", 14: "Skilled", 15: "Fast Shot", 16: "Gifted"
}
const skillText = {
    1: "Small Guns", 2: "Big Guns", 3: "Energy Weapons", 4: "Unarmed", 5: "Melee Weapons", 6: "Throwing",
    7: "First Aid", 8: "Doctor", 9: "Sneak", 10: "Lockpick", 11: "Steal", 12: "Traps", 13: "Science", 14: "Repair",
    15: "Speech", 16: "Barter", 17: "Gambling", 18: "Outdoorsman",
}
var traitChoiceValue;
var skillsChoiceValue;
var traitsStored = [0, 0];
var skillsStored_random = [0, 0, 0];
var skillsStored_randomOrder = [0, 0, 0];
const skillsMath = [[6, 1], [8, 7], [4, 15]]

function assignTraits() {
    traitsStored[0] = 0;
    traitsStored[1] = 0;
    while (traitsStored[0] == traitsStored[1]) {
        for (i = 0; i < 2; i++) {
            var traitSelected = Math.floor(Math.random() * 16) + 1;
            traitsStored[i] = traitSelected;
        }
    }
    traitChoiceValue = traits_select.options[traits_select.selectedIndex].value;
    if (traitChoiceValue == "none") traitChoiceValue = 0;
    if (traitChoiceValue == "random") traitChoiceValue = Math.floor(Math.random() * 3);
    if (typeof traitChoiceValue == "string") traitChoiceValue=Number(traitChoiceValue);
    switch (traitChoiceValue) {
        case 0:
            document.getElementById("traitResult_p").innerHTML = "You have no Traits";
            break;
        case 1:
            document.getElementById("traitResult_p").innerHTML = "Trait: " + traitsText[traitsStored[0]] + ".";
            break;
        case 2:
            document.getElementById("traitResult_p").innerHTML = "Traits: " + traitsText[traitsStored[0]] + " and " + traitsText[traitsStored[1]] + "!";
            break;
        default:
            document.getElementById("traitResult_p").innerHTML = "There was an error in the script! Received " + traitChoiceValue + " from the drop-down box." ;
            break;
    }
}

function assignSkills() {
    for (i = 0; i < 3; i++) {
        var skillSelected = Math.floor(Math.random() * 18) + 1;
        skillsStored_random[i] = skillSelected;
        var skillSelected = Math.floor(Math.random() * skillsMath[i][0]) + skillsMath[i][1];
        skillsStored_randomOrder[i] = skillSelected;
    }
    skillsStored_random.sort(function(a, b){return a - b});
    skillsStored_randomOrder.sort(function(a, b){return a - b});
    skillsChoiceValue = skills_select.options[skills_select.selectedIndex].value;
    switch (skillsChoiceValue) {
        case "random":
            document.getElementById("skillResult_p").innerHTML = "Skills: " + skillText[skillsStored_random[0]] + ", " + skillText[skillsStored_random[1]] + ", " + skillText[skillsStored_random[2]] + ".";
            break;
        case "random_order":
            document.getElementById("skillResult_p").innerHTML = "Skills: " + skillText[skillsStored_randomOrder[0]] + ", " + skillText[skillsStored_randomOrder[1]] + ", " + skillText[skillsStored_randomOrder[2]] + ".";
            break;
        case "random_speech":
            if (skillsStored_random[0] == 15) assignSkills();
            if (skillsStored_random[1] == 15) assignSkills();
            document.getElementById("skillResult_p").innerHTML = "Skills: " + skillText[skillsStored_random[0]] + ", " + skillText[skillsStored_random[1]] + ", " + skillText[15] + ".";
            break;
        case "first_char":
            document.getElementById("skillResult_p").innerHTML = "Skills: " + skillText[1] + ", " + skillText[10] + ", " + skillText[15] + ".";
            break;
    }
}

function assignPoints() {
    var stats = [1, 1, 1, 1, 1, 1, 1];
    const statsText = ["Strength", "Perception", "Endurance", "Charisma", "Intelligence", "Agility", "Luck"];
    if (traitChoiceValue>0) {
        for (i=0; i<traitChoiceValue; i++) {
            if (traitsStored[i] == 3) stats[0]+=2;
            if (traitsStored[i] == 5) stats[5]++;
            if (traitsStored[i] == 16) 
                for (j=0; j<7; j++) stats[j]++;
        }
    }
    var statsTotal = 0
    while (statsTotal < 33) {
        var statsDist = Math.floor(Math.random() * 7);
        if (stats[statsDist] < 10) {
        stats[statsDist]++;
        statsTotal++;
        }
    }
    for (i = 0; i < 7; i++) {
        document.getElementById(statsText[i]).innerHTML = stats[i];
    }
}

function main() {
    startButton_div.addEventListener('click', function() {
        assignTraits();
        assignSkills();
        assignPoints();
    })
}
main()

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

I never thought I'd be posting my own program but here I am.

 

Simple Notepad. Can create, edit, read, and delete files. Limited Functionality.

 

90 lines, even with redundant print commands and functions that could be implemented someway else

 

import os
import sys

def NOTEPAD():
	print('NOTEPAD.SYS allows you to create text files with ease. Just simply start\nby creating the name of the text file and your file will be created. After\nthat, start typing what you want. Current limitations make it so only one\nparagraph is creatable. After you are done press ENTER to either create a\nnew file or open another file. If you want to edit a pre-existing file,\nyou can do that too.\n')
	print('Use the command CREATE to create a new file, EDIT to edit an old file,\nREAD to read a file, and DELETE to delete an file forever.\n')
	print('Use QUIT to quit the application\n')
	command = input("$input<<")
	if (command == "CREATE"):
		CREATE()
	elif (command == "EDIT"):
		EDIT()
	elif (command == "READ"):
		READ()
	elif (command == "DELETE"):
		DELETE()
	elif (command == "QUIT"):
		QUIT()
	else:
		print("Invalid Command. Please try again.\n")
		NOTEPAD_COPY()

def CREATE():
	command = input('\nFile Name?\n$input<<')
	try:
		f = open(command + ".txt", "x")
		f.close()
	except FileExistsError:
		print("\nSorry, there was an error while trying to create your file. There is a file with the same name that exists\n")
	finally:
		NOTEPAD_COPY()


def EDIT():
	print("\nEnter the file you want to edit")
	command = input('\n$input<<')
	try:
		r = open(command + ".txt", "r")
		print("File Contents:\n")
		print(r.read())
		r.close()
		with open(command + ".txt", "a") as f:
			f.write(input('\n$append<<'))
	except FileNotFoundError:
		print('\nSorry, there was an error while trying to edit your file. The file doesn\'t exist.\n')
	finally:
		NOTEPAD_COPY()
		
def READ():
	command = input('\nFile Name\n\n$input<<')
	try:
		f = open(command + ".txt", "r")
		print(f.read())
	except FileNotFoundError:
		print('\nSorry, there was an error while trying to read your file. The file doesn\'t exist')
	finally:
		NOTEPAD_COPY()

def DELETE():
	command = input('\nFile Name\n$input<<')
	try:
		os.remove(command + ".txt")
	except FileNotFoundError:
		print('\nSorry, there was an error while trying to delete your file. The file doesn\'t exist')
	finally:
		NOTEPAD_COPY()
def QUIT():
	command = input('\nAre you sure? [Y] [N]\n$input<<')
	if (command == "Y"):
		sys.exit(0)
	else:
		NOTEPAD_COPY()

def NOTEPAD_COPY():
	print('Use the command CREATE to create a new file, EDIT to edit an old file,\nREAD to read a file, and DELETE to delete an file forever.\n')
	print('Use QUIT to quit the application\n')
	command = input("$input<<")
	if (command == "CREATE"):
		CREATE()
	elif (command == "EDIT"):
		EDIT()
	elif (command == "READ"):
		READ()
	elif (command == "DELETE"):
		DELETE()
	elif (command == "QUIT"):
		QUIT()
	else:
		print("Invalid Command. Please try again.\n")
		NOTEPAD_COPY()

Original program if you want to check it out, this one is modified so that it is standalone, the other one below is not standalone:

 

TsmDan Studios and Computer Epicenter take absolutely no liability or responsibility for any damages caused by operation on your device. If you damage something, don't blame it on me. If I break something, it's not my fault.

WARNING: Opening a laptop will immediately void any warranty on that laptop

WARNING: Your price for Builds will increase twofold because of insurance

Link to comment
Share on other sites

Link to post
Share on other sites

A screensaver like consoleapp, that beeps on a random tone.

It does not really serve a purpose, but you can costumize its message & disable console beeps.

 

You can take a look at it on github if you want.

 

sCapture.PNG.1dc0eb2fbdab9445783f710f8cb95064.PNG

 

The helloworld message is costumizeable thru a json, and the little window (the white helloworld message) hopps around on to random cordinates on screen, sorta like the DVD screensaver thing.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Nothing crazy, just a simple mortgage payment/interest calculator written in a .NET Core console app:

 

using System;
namespace _100LineChallenge
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the simple mortgage calculator!");
            while (true)
            {
                Console.Clear();
                Console.WriteLine("Please enter the principal balance (numbers only):");
                int.TryParse(Console.ReadLine(), out int principal);
                Console.WriteLine("Please enter your interest rate in a whole number format (example: 3.123%):");
                double.TryParse(Console.ReadLine(), out double interestRate);
                interestRate = interestRate / 12 / 100;
                Console.WriteLine("Please enter the desired number of years for your mortgage:");
                int.TryParse(Console.ReadLine(), out int months);
                months = months * 12;
                double monthlyPayment = (principal * (interestRate * Math.Pow((1 + interestRate), (months)))) / (Math.Pow((1 + interestRate), months) - 1);
                Console.WriteLine(String.Concat("Your monthly payment will be: ", monthlyPayment.ToString("C"), Environment.NewLine, "Total cost of the loan: ", (monthlyPayment * months).ToString("C"), Environment.NewLine, "Total loan interest paid: ", ((monthlyPayment * months - principal).ToString("C"))));
                Console.WriteLine("Run another calculation? (Y / N)");
                if (Console.ReadLine().ToLower() != "y")
                {
                    break;
                }
            }
        }
    }
}

 

Main System: [Windows 10 Pro] [Core i7 5960x] [Asus Rampage V Extreme] [32GB 2400mhz G.Skill Value] [Corsair AX1200] [RXT 2080 Super] [Corsair H100i] [Thermaltake Core P3]

Link to comment
Share on other sites

Link to post
Share on other sites

Here is some cheap n simple Editor replace. 78 LoCs
 

 

 

 

import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.swing.filechooser.FileNameExtensionFilter; 
public class Editor extends JFrame{
    JTextArea text;
    public static void main(String args[]){
        new Editor();
    }  
    Editor(){
        text=new JTextArea();
        text.setMinimumSize(new Dimension(450,650));
        setSize(500,700);
        GroupLayout gl = new GroupLayout(getContentPane());
        gl.setVerticalGroup(gl.createSequentialGroup().addComponent(text));
        gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(text));
        setLayout(gl);
        JMenuBar mb = new JMenuBar();
        JMenu mm = new JMenu("options");
        JMenuItem mmm = new JMenuItem("open");
        JMenuItem m = new JMenuItem("save");
        mm.add(mmm);
        mm.add(m);
        mb.add(mm);
        m.addActionListener( e->{  saveAs(null);});
        mmm.addActionListener( e->{  open(null); });
        setJMenuBar(mb);
        setVisible(true);}

    boolean saveAs(String pfad) { 
        JFileChooser chooser; 
        if (pfad == null) pfad = System.getProperty("user.home"); 
        File file = new File(pfad.trim()); 

        chooser = new JFileChooser(pfad); 
        chooser.setDialogType(JFileChooser.SAVE_DIALOG); 
        FileNameExtensionFilter plainFilter = new FileNameExtensionFilter( "Plaintext: txt, csv", "txt", "csv"); 
        chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter());
        chooser.setFileFilter(plainFilter); 
        chooser.setDialogTitle("Save as..."); 
        chooser.setVisible(true); 

        int result = chooser.showSaveDialog(this); 

        if (result == JFileChooser.APPROVE_OPTION) { 

            pfad = chooser.getSelectedFile().toString(); 
            try{
                FileWriter fw = new FileWriter(new File(pfad));
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(text.getText());
                bw.flush();
                bw.close();
            }catch(Exception e ){} 
        chooser.setVisible(false); 
        return false; }
    boolean open(String pfad) { 
        JFileChooser chooser; 
        if (pfad == null) 
            pfad = System.getProperty("user.home"); 
        File file = new File(pfad.trim()); 

        chooser = new JFileChooser(pfad); 
        chooser.setDialogType(JFileChooser.OPEN_DIALOG); 
        FileNameExtensionFilter plainFilter = new FileNameExtensionFilter("Plaintext: txt, csv", "txt", "csv"); 
        chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter());
        chooser.setFileFilter(plainFilter); 
        chooser.setDialogTitle("Open..."); 
        chooser.setVisible(true); 

        int result = chooser.showSaveDialog(this); 

        if (result == JFileChooser.APPROVE_OPTION) { 
            pfad = chooser.getSelectedFile().toString(); 
            try{
                FileReader fr = new FileReader(pfad);
                BufferedReader br = new BufferedReader(fr);
                String txt;
                String ret = new String();
                while((txt=br.readLine())!=null) ret+=txt+System.lineSeparator();
                text.setText(ret);
                this.validate();
            }catch(Exception e){ }  } 
        chooser.setVisible(false); 
        return false; } 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

Some Arduino code.

Spoiler

/*
   Wii Nunchuk 
   Quake Champions Controller 4 PC
   USB Keyboard Interface
   Nunchuk Pinout: https://www.xarg.org/2016/12/using-a-wii-nunchuk-with-arduino/
   Hardware: 
      Adafruit ItsyBitsy M4 Express: https://www.adafruit.com/product/3800
      Wii Nunchuk: https://www.amazon.com/gp/product/B07RLBHJ67/
      
   RandleMcmurphy | 9/10/2020
*/

#include <Adafruit_DotStar.h>
#include <NintendoExtensionCtrl.h>
#include "Keyboard.h"

#define NUMPIXELS  1
#define DATAPIN    8
#define CLOCKPIN   6

#define DEAD_ZONE   5   // threshold
#define NULL_STICK  128 // un-touched

#define _POSITIVE (NULL_STICK + DEAD_ZONE) // +
#define _NEGITIVE (NULL_STICK - DEAD_ZONE) // -

#define UP          'w' // W
#define DOWN        's' // S
#define LEFT        'a' // A
#define RIGHT       'd' // D
#define JUMP        ' ' // space
#define ABILITY     'f' // F

#define _FLIP(a) (_state[(a)] = !_state[(a)])

#define SET_LED_RED     strip.setPixelColor(0, 0, 255, 0); strip.show()
#define SET_LED_GREEN   strip.setPixelColor(0, 255, 0, 0); strip.show()

Adafruit_DotStar strip(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);
Nunchuk nchuk;

bool _state[4] = { 0 };
bool LED = 0;

void setup() {
  Keyboard.begin();
  nchuk.begin();
  strip.begin();
  strip.setBrightness(64);

  while (!nchuk.connect()) {
    SET_LED_RED;
    delay(1000);
  } // end while
  
  SET_LED_GREEN;
} //end setup

void loop() {
  boolean success = nchuk.update();
  
  if (!success) {
    SET_LED_RED;
    delay(1000);
  }
  else {
    boolean zButton = nchuk.buttonZ();
    boolean cButton = nchuk.buttonC();
    int joyY = nchuk.joyY();
    int joyX = nchuk.joyX();

    /* ================ ABILITY ================================================= */
    cButton == true ? Keyboard.press(ABILITY) : Keyboard.release(ABILITY);
    /* ================ JUMP ==================================================== */
    zButton == true ? Keyboard.press(JUMP)    : Keyboard.release(JUMP);
    /* ================ UP ====================================================== */
    if (joyY >= _POSITIVE) { if (!_state[0]) Keyboard.press(UP),      _FLIP(0); }
    else                   { if ( _state[0]) Keyboard.release(UP),    _FLIP(0); }
    /* ================ DOWN ==================================================== */
    if (joyY <= _NEGITIVE) { if (!_state[1]) Keyboard.press(DOWN),    _FLIP(1); } 
    else                   { if ( _state[1]) Keyboard.release(DOWN),  _FLIP(1); }
    /* ================ RIGHT =================================================== */
    if (joyX >= _POSITIVE) { if (!_state[2]) Keyboard.press(RIGHT),   _FLIP(2); }
    else                   { if ( _state[2]) Keyboard.release(RIGHT), _FLIP(2); }
    /* ================ LEFT ==================================================== */
    if (joyX <= _NEGITIVE) { if (!_state[3]) Keyboard.press(LEFT),    _FLIP(3); }
    else                   { if ( _state[3]) Keyboard.release(LEFT),  _FLIP(3); }
    /* ========================================================================== */
  } // end else

  if(success != LED) {
    if(!success) { SET_LED_RED;   }
    else         { SET_LED_GREEN; }
    LED = success;
  } //end if
  
} // end loop


// Line 100

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...
import matplotlib.pyplot as plt
import numpy as np
import psutil as ps
import time
import sys

while True:
    battStat = ps.sensors_battery()
    battPerc = np.zeros(2880)
    i = 0
    while battStat[2] != True:
        battStat = ps.sensors_battery()
        battPerc[i] = battStat[0]
        time.sleep(10)
        i += 1
        if battStat[2] == True:
            t = np.zeros(2880)
            plt.plot(t, battPerc)
            plt.show()
            sys.exit()

I think this is my first half successful Python project. It's a simple lil guy that monitors your laptop battery percentage while the power is disconnected, then plots it once power is reconnected. I wish I wrote more comments, I can't remember why I made two arrays that are 2880 indices large, but I mostly just took on this project at 3am to see how hard it was to replace Matlab with Python. Answer: not that hard, but not really worth it for classes.

ASU

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


×