r/badcode •

[deleted by user]

[deleted] — view deleted post

0 Upvotes

15 comments sorted by

25

u/sarlok May 25 '20

That sounds an awful lot like a filesystem, so why don't we just use that? Behold, bbcc37.cmd:

:; set() { echo "$2" > "$1"; }; alias get=cat; alias keys=ls; alias delete=rm
:; mkdir bbcc37 2> /dev/null; cd bbcc37; if (false); then
@echo off
doskey /MACROFILE=bbcc37.cmd 2> nul > nul
md bbcc37 2> nul
cd bbcc37
exit /b
set=echo $2 > $1
get=type $1
keys=dir /b
delete=del $1
fi

Features:

  • Cross platform (Windows and Linux)!
  • Uses built in filesystem capabilities for fewer bugs!
  • Gets you into a terminal mode where you can directly type the commands!
  • Creates one directory database automatically called bbcc37!
  • Conveniently overwrites shell builtins for ease of use!

Usage for Windows (from cmd command prompt):

bbcc37
set key value
get value
keys
delete key

Usage for Linux (from bash shell):

. bbcc37.cmd
set key value
get value
keys
delete key

8

u/mathishard821 May 31 '20

Sounds a lot like string manipulation to me, so there's really only one tool for the job! Behold, a database written in sed!

#n
:readdb
/---/!{
	N; b readdb
}
s/\(^\n\|\n---$\)//; h
:top
n

/^get/{
	G
	s/^get \([[:alnum:]]*\)\n\(\1:\([[:alnum:]]*\)\n\|.\)*/\3/p
	$b end; b top
}
/^keys/{
	g; s/:[[:alnum:]]*//gp; $b end; b top
}
/^delete/{
	x; s/\(^\|\n\)/\1@/g; x; G
	:trydelete
	/^delete \([[:alnum:]]*\)\n[^@]*@\1/{
		s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
		s/@//g
	}
	s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
	/@/b trydelete
	s/^[[:print:]]*\n//g
	h; s/.*/OK/p; $b end; b top
}
/^set/{
	x; s/\(^\|\n\)/\1@/g; x; G
	:tryset
	/^set \([[:alnum:]]*\) \([[:alnum:]]*\)\n[^@]*@\1/{
		s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
		s/@//g
	}
	s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
	/@/b tryset
	s/^set \([[:alnum:]]*\) \([[:alnum:]]*\)/\1:\2/
	h; s/.*/OK/p; $b end; b top
}

:end
x; s/\n\?$/\n---/; w out.txt

A database is a text file in the following format:

key1:value1
key2:value2
key3:value3
---

To run this beautiful program, use sed -f script.sed db.txt commands.txt, or pipe your command(s) in through stdin. The resultant database is written to out.txt.

Pros:

  • Harness the full power of sed!
  • Built-in backups generated on each and every command, just throw away the output file if you run the wrong one!

6

u/[deleted] May 26 '20 edited May 26 '20

Haskell, because why not. Database is stored in a single csv file, called database.csv. There is no usage summary available - only the responses OK, ERROR, or the requested data item(s) are printed. Extra parameters are ignored. Keys are always printed out in sorted order.

module Main ( main ) where

import qualified Data.ByteString.Lazy as BL
import Control.Monad
import Data.Csv
import qualified Data.List as List
import qualified Data.Vector as Vector
import System.Directory
import System.Environment
import System.Exit

data Entry = Entry { key :: !String, value :: !String }
    deriving (Show)

instance FromRecord Entry where
    parseRecord v
        | List.length v == 2 = Entry <$> v .! 0 <*> v .! 1
        | otherwise          = mzero

instance ToRecord Entry where
    toRecord (Entry k v) = record [ toField k, toField v ]

dataFileName = "database.csv"

main = do
    args <- getArgs
    if List.length args < 1
        then die "ERROR"
        else let command = List.head args
                 params  = List.tail args
             in case command of
                 "set"    -> handleSet params
                 "get"    -> handleGet params
                 "keys"   -> handleKeys
                 "delete" -> handleDelete params
                 _        -> die "ERROR"

readDB = do
    databaseExists <- doesFileExist dataFileName
    if databaseExists
    then do
        csvData <- BL.readFile dataFileName
        case decode NoHeader csvData :: Either String (Vector.Vector Entry) of
            Left err -> die "ERROR"
            Right entries -> return $ Vector.toList entries
    else return []

writeDB entries =
    BL.writeFile dataFileName (encode entries)

handleSet params =
    if List.length params < 2
        then die "ERROR"
        else let k = List.head params
                 v = List.head (List.tail params)
             in do
                 entries <- readDB
                 if List.elem k (List.map key entries)
                     then let entriesMinusOldItem =
                                  List.filter (\x -> key x /= k) entries
                              entries' = (Entry k v):entriesMinusOldItem
                          in writeDB entries' >> putStrLn "OK"
                     else let entries' = (Entry k v):entries
                          in writeDB entries' >> putStrLn "OK"

handleGet params =
    if List.length params < 1
        then die "ERROR"
        else let k = List.head params
             in do
                 entries <- readDB
                 case (List.find (\x -> (key x) == k) entries) of
                     Nothing -> die "ERROR"
                     Just (Entry k v) -> putStrLn v

handleKeys = do
    entries <- readDB
    mapM_ putStrLn (List.sort $ List.map key entries)

handleDelete params =
    if List.length params < 1
        then die "ERROR"
        else let k = List.head params
             in do
                 entries <- readDB
                 if List.elem k (List.map key entries)
                     then let entriesMinusOldItem =
                                  List.filter (\x -> key x /= k) entries
                          in writeDB entriesMinusOldItem >> putStrLn "OK"
                     else die "ERROR"

Some examples:

$ ./database keys
$ ./database get
ERROR
$ ./database get one
ERROR
$ ./database set one uno
OK
$ ./database set two dos
OK
$ ./database set three tres
OK
$ ./database get two
dos
$ ./database keys
one
three
two
$ ./database delete two
OK
$ ./database keys
one
three
$ ./database get two
ERROR
$ ./database get one
uno

3

u/bytesomething May 29 '20

C. Tested on Linux x86_64 with GCC, appears to work with MinGW, not sure about other platforms and compilers.

set reads from stdin without value argument for convenient storage of binary data. Error messages are written to stderr. No memory is freed, no files are closed. Key-value pairs are stored in a revolutionary database format optimized for linear search.

https://pastebin.com/yX9Uhh5X

2

u/gaberocksall May 25 '20 edited May 25 '20

Here's my entry, i tried to replicate my code from when i just learned python. I was going to mess up the indention scopes, but i couldn't bring myself to force someone to read that. Naturally, this has the following bugs:

  1. Passing too few arguments will error
  2. No shebang is a problem in some environments
  3. Sequential open calls to the same file is bad
  4. You can store multiple values under the same key (This is a feature)
  5. Calling bbcc37 get or bbcc37 delete before creating data.sql will error
  6. bbcc37 get key prints in the ugly format key=value
  7. The data.sql file will have random extra newlines
  8. keys may not contain the = character

And it has the following advantages:

  1. The data file can be opened in a text editor and it's human readable
  2. Will print useful tracebacks to any errors that occur
  3. The program checks for get requests first, so those will be most efficient by several microseconds
  4. Only uses default python libraries, no need to pip install anything

​

import sys

ENTER_CHARACTER = """
"""

if sys.argv[1] == "get":
    f = open("data.sql", "r+")
    for line in f.readlines():
        # whats string.split
        key = ""
        for character in line:
            if character == "=":
                break
            key = key + character
        if key == sys.argv[2]:
            print(line)

if sys.argv[1] == "set":
    f = open("data.sql", "a+")
    f.write(sys.argv[2])
    f.write("=")
    f.write(sys.argv[3])
    f.write(ENTER_CHARACTER)

if sys.argv[1] == "keys":
    f = open("data.sql", "r+")
    for line in f.readlines():
        key = ""
        for character in line:
            if character == "=":
                break
            key = key + character
        print(key)

if sys.argv[1] == "delete":
    f = open("data.sql", "r")
    all_lines = f.readlines()
    f = open("data.sql", "w+")
    f.truncate()
    for line in all_lines:
        key = ""
        for character in line:
            if character == "=":
                break
            key = key + character
        if key == sys.argv[2]:
            # don't write this line back into the database
            print("deleted")
        else:
            f.write(line)
            f.write(ENTER_CHARACTER)```
→ More replies (2)

3

u/--var May 25 '20

After about 30 minutes I've concocted this little gem:

<!-- filname: kvdb.html -->
<!doctype html>
<script>
!(function() {
  if (!window.KVDB) {
    window.KVDB = {
       commands: {},
       DoFoolishCommands: function() {
         let db = JSON.parse(localStorage.KVDB || '{}');
         switch(window.KVDB.commands.action){
          case 'set': db[window.KVDB.commands.key] = window.KVDB.commands.value; output = window.KVDB.commands; break;
          case 'get': output = db[window.KVDB.commands.key]; break;
          case 'keys': output = Object.keys(db); break;
          case 'delete': delete db[window.KVDB.commands.key]; output = window.KVDB.commands; break;
          default: output = {'your commands': 'do not compute'};
        }

        console.log(output, '\nOK');
        document.clear();
        document.write(JSON.stringify(output) + '<br>OK');
        localStorage.KVDB = JSON.stringify(db);
        window.KVDB.commands = {};
      }
    };

    if (window.location.href.includes('?')) {
      window.location.href.substr(window.location.href.indexOf('?') + 1).split('&').forEach(function(index) { window.KVDB.commands[index.split('=')[0]] =  index.split('=')[1]; });
      window.KVDB.DoFoolishCommands();
    }
  }
})();
</script>

WHY YOUR COMPANY NEEDS THIS:

It uses your web browser, so its universal and mobile and will never have compatibility issues

It uses javascript and the window global scope, which are indisputably best practices

It uses localStorage without checking if it's supported and has no input validation, which of course would waste cpu cycles

It accepts commands in url form, from the console or by modifying the local storage directly, which provides flexibility, never mind that a single typo will break everything.

USE EXAMPLES:

in the url

kvbd.html?action=set&key=dope_key&value=dank_value

in the console

window.KVDB.commands = {action:'get',key:'dope_key'}
window.KVDB.DoFoolishCommands()

0

u/[deleted] May 25 '20

[deleted] — view deleted comment

3

u/gaberocksall May 25 '20

f = open(__file__, 'r+')

...

f.truncate(0)

UM

0

u/[deleted] May 25 '20

[deleted] — view deleted comment

1

u/lurebat May 27 '20

why are none of the links updated past the 27th challange?