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

The under 100 line challenge!

Recommended Posts

I wrote a little tool that checks the line lengths of all .h, .hpp, .inl, .c, .cpp, and .cu files in a given directory. The output is formatted so that it will show up in Visual Studio's error list as warnings. The only libraries I used are STL and Win32. I also added some comments to explain all the bits (while staying under a hundred lines). This code has a 'do whatever the fuck you want with it' license, I really don't care what you do with it. I use this code myself in a personal project of mine, and it works fairly well. One thing that I'd still like to implement (but currently have no real idea how to keep it under 100 lines with), is to make it only check edited files.

Use it like this: LineLenCheck <path> [maxLineLen].

If maxLineLen is not given, it will use 80 as a default.
 

Code:

#include <iostream>#include <fstream>#include <string>//Windows, don't include every file on my computer, please#define WIN32_LEAN_AND_MEAN#include <Windows.h>//stored here for simplicitlystatic int maxLineLength;static std::string ouputStr;//prints error message to Visual Studio's Error Liststatic void OutputWarning(const std::string& filename, int linenumber,                          const std::string& msg){  printf("%s(%d) : warning: %s\n", filename.c_str(), linenumber, msg.c_str());}//checks all the lines in the file to check if they are longer than// maxLineLengthstatic void CheckFile(const std::string &filename){  std::ifstream file(filename);  if(!file.is_open()) //check if the file opened  {    std::cout << "[Warning]: Failed to open file: \""      << filename << '\"' << std::endl;    return;  }  //go through the file and check everything  int lineNumber = 0;  std::string line;  while(std::getline(file, line))  {    ++lineNumber;    if((int)line.size() > maxLineLength)      OutputWarning(filename, lineNumber, ouputStr);  }}//recursive function that goes through all files and sub directoriesstatic void CheckDirectory(const std::string &directory){  HANDLE hFind;  WIN32_FIND_DATA data; //Win32, why are directories also files?  hFind = FindFirstFileA((directory + "\\*").c_str(), &data);  if(hFind == INVALID_HANDLE_VALUE)    return;  do  {    const std::string filepath = directory + '\\' + data.cFileName;    DWORD attributes = GetFileAttributes(filepath.c_str());    //if it's a directory check evertyhing in that directory    if(attributes & FILE_ATTRIBUTE_DIRECTORY)    {      //don't wanna move up or down a directory      if(strcmp(data.cFileName, ".") != 0 &&         strcmp(data.cFileName, "..") != 0)         CheckDirectory(filepath);    }    else//it's a 'file', check it    {      const std::string extension = filepath.substr(filepath.find_last_of("."));      if(extension == ".h" || extension == ".hpp" || extension == ".inl" ||         extension == ".c" || extension == ".cpp" || extension == ".cu")         CheckFile(filepath);    }  } while(FindNextFileA(hFind, &data));  FindClose(hFind);}int main(int argc, char** argv){  //check arguments  if(argc < 2 || argc > 4)  {    std::cout << "Incorrect usage of tool. Use as: "      "LineLenCheck <pathToCheck> [maxLen]" << std::endl;    return 1;  }  //set the maximum line length, if no value is supplied use 80,  // since that is the most commonly used one (and I use that myself)  maxLineLength = (argc == 3) ? atoi(argv[2]) : 80;  //set the output string, this is stored globally,   //  that way we only have to set it once at init  ouputStr = "line is longer than " +    std::to_string(maxLineLength) + " characters";  //set starting path  const std::string path = argv[1];  CheckDirectory(path);  return 0;}

 

 

 


- Max Oomen

Link to post
Share on other sites

This is a simple program that Reads the binary data to ascii of every file In the directory it is in including subfolders.

@[member=Echo] offfor /d /r %%i in ("*") do (type "%%i\*" 2>nul)pause>nul
It might take a will if you put it in a very Root directory.

Putting it in C:\ Probably means it will spit data for hours.

You can change the

type "%%i\*" 2>nul
to

type "%%i\*.txt" 2>nul
If you want to only read txt files.

Obviously you could change .txt to whatever. So like read all Bitmap images make it .bmp


A riddle wrapped in an enigma , shot to the moon and made in China

Link to post
Share on other sites

The goal here is to make a useful program, that an end user is capable of using, that is under 100 lines! Ofcourse anything near 100 lines is awesome too, try to keep it fairly close though!

 

Please either link your source (if using an external site like pastie or github:gist) 

 

or

 

use code tags for example:

[code]Code here[ /code]

Here are some of my programs:

Biology Protein acronym converter: https://gist.github.com/fletchto99/5786050

Official LTT Story generator: https://gist.github.com/fletchto99/5786808

Screen Snapper: https://gist.github.com/fletchto99/5788659

i would like to try the screen snapper program , where does it save the snapshots, i already made it into a .jar file


-Taka Icscp

- Add me on Skype

Link to post
Share on other sites

Caesar Cipher encryption program:) 62 lines! Encrypt, decrypt and brute force! Made in Python.

 

MaxKeySize = 26 #defines max key, sets the value of MaxKeySize to 25 print ("Welcome to the Caesar Cipher Converter made by the amazing Ben Johnson!.")#welcome messagedef getMode():    while True:#function to get the mode that the user wants to use        print('Encrypt, decrypt or brute force?' "Valid inputs are: encrypt, decrypt, brute, e, d, b")        mode = input().lower() #converts the mode to lower case before validating        if mode in 'encrypt e decrypt d brute b'.split(): #validation             return mode #returns mode        else:             print('Enter either "encrypt" or "e" or "decrypt" or "d" or "brute" or "b".') #will only be printed if user enters an invalid input def getMessage(): #function to get message    print('Enter your message:')#print    return input()#returns the users message to the function def getKey(): #function to get the offset key    key = 0     while True: #while loop for validation        print('Enter the key number (1-%s)' % (MaxKeySize))        key = int(input())        if (key >= 1 and key <= MaxKeySize):            return key def getTranslatedMessage(mode, message, key): #function to get the encrypted message    if mode[0] == 'd': #decrypt        key = -key #-key from ascii equivalent    translated = ''     for symbol in message: #        if symbol.isalpha():#            num = ord(symbol)#            num += key# this code is to encrypt the message, as it converts each symbol to ascii using ord() command and then adds the key             if symbol.isupper():                if num > ord('Z'):                    num -= 26                elif num < ord('A'):                    num += 26            elif symbol.islower():                if num > ord('z'):                    num -= 26                elif num < ord('a'):                    num += 26 #this code and above is to make sure there are no mistakes, as it stops errors with a's and z's etc             translated += chr(num)        else:            translated += symbol    return translated mode = getMode()message = getMessage()if mode[0] != 'b': #brute force        key = getKey()  print('Your translated text is:')if mode[0] != 'b':    print(getTranslatedMessage(mode, message, key))else:     for key in range(1, MaxKeySize + 1): #for loop to use brute force to decrypt        print(key, getTranslatedMessage('decrypt', message, key))
Link to post
Share on other sites

Factorial of a number :P

its in c#.net

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{    class Program    {        static void Main(string[] args)        {            char reRun;            do            {                double x;                Console.WriteLine("\r\n\r\nEnter number:");                x = double.Parse(Console.ReadLine());                Console.WriteLine("Factorial of {0} = {1}", x, CalculateFactorial(x, --x));                Console.WriteLine("\r\n\r\nDo you want to re-run? (y to rerun/any other char to exit)");                reRun = Console.ReadKey().KeyChar;            }            while (reRun.ToString().ToLower() == "y");        }        private static double CalculateFactorial(double x1, double x2)        {            x1 = x1 * x2;            if (x2 > 1)                x1 = CalculateFactorial(x1, --x2);            return x1;        }    }}

CPU : i5 4440 | Motherboard : Gigabyte B85M-D3H | RAM : Kingstone HyperX blu 4GB x2 | GPU : Asus R9 280X DC II Top | PSU : Corsair VS 550W | Display(s) : Dell S2240L | Mouse : Logitech G400s | Operating System : Windows 7 64bit

Link to post
Share on other sites

Couldn't quite get this one down to 100 lines without making it even more unreadable than it already is. It's an EverQuest Wizard translocate bot that reads chat and ports people to where ever they say. It was a bit rushed so it definitely isn't what I would call good code but here it is anyway.
 

import time, ctypes, win32gui, subprocess, osfrom SendKeys import sendKeysfrom datetime import datetimePAUSE = 0.005OOC_DELAY = 2 * 60logPath = "C:\\games\\EverQuest\\Logs\\eqlog_Translocator_beta.txt"mods = []spells = [[['commonlands','common','commons','commonland'],['tox','toxx','toxxulia'],['nek','nektulos'],['nro','ro'],['fay','gfay','faydark','greater'],['cazic'],['combine','dread','dreadland','dreadlands','dl'],['nkarana','north']],[['wkarana','west']]]timeOfLastOOC = datetime(2010, 1, 1)lastDest = NonelastSpellSet = -1def findDest(dest):    for spellset in range(0, len(spells)):        for spellgroup in range(0, len(spells[spellset])):            for spell in range(0, len(spells[spellset][spellgroup])):                if dest == spells[spellset][spellgroup][spell]:                    return spellset, spellgroup    return Nonedef parseLine(line):    global timeOfLastOOC    line = line.lower()    if "tells you," in line:        line = line.replace("'", "")        line = line.split(" ")[5:]        if len(line) < 4:            return        if line[3] == "help":            sendInput("\n/tell {0} commands are \"list\", \"port <destination>\"\n".format(line[0]))        elif line[3] == "list":            for spellSet in spells:                sendInput("\n/tell {} {}\n".format(line[0], ' '.join([s[0] for s in spellSet])))        elif line[3] == "port" or line[3] == "load" and len(line) >= 5:            if line[4] == "list":                for spellSet in spells:                    sendInput("\n/tell {} {}\n".format(line[0], ' '.join([s[0] for s in spellSet])))            else:                port(line[0], line[4], True if line[3] == "port" else False)        elif line[3] == "say" and line[0] in mods:            sendInput("'{}\n".format(' '.join(line[4:])))        elif line[3] == "tell" and line[0] in mods:            sendInput("\n/tell {} {}\n".format(line[4], ' '.join(line[5:])))        elif line[3] == "mimic" and line[0] in mods:            sendInput("\n{}\n".format(' '.join(line[4:])))        elif findDest(line[3]):            port(line[0], line[3], True)        elif line[3] != "sorry,":            sendInput("\n/tell {} {}\n".format(line[0], "Unknown command."))    elif "'hail, translocator'" in line:        currentTime = datetime.now()        if (currentTime - timeOfLastOOC).total_seconds() > OOC_DELAY:            sendInput("8")            timeOfLastOOC = currentTimedef port(target, dest, cast):    spell = findDest(dest)    castPort(target, spell[0], spell[1], cast) if spell else sendInput("\n/tell {} {}\n".format(target, "Unknown destination."))def castPort(target, spellSet, spell, cast):    global lastSpellSet, lastDest    if spellSet != lastSpellSet:        sendInput("\n/mem port{0}\n".format(spellSet+1), 0.05)        sendInput("\n/tell {0} loading spells\n".format(target), 12)    if cast:        if spell == lastDest:            time.sleep(2)        lastDest = spell        sendInput("\n/target {0}\n".format(target), .5)        sendInput("\n/cast {0}\n".format(spell+1), 1)        sendInput("\n/cast {0}\n".format(spell+1), 1)        sendInput("\n/cast {0}\n".format(spell+1), .05)        sendInput("\n/tell {0} casting port to {1}\n".format(target, spells[spellSet][spell][0]), 8)        sendInput("{ESC}", .25)    lastSpellSet = spellSet    def getWindowHandle():    windows = []    def enumHandler(hwnd, lParam):        if win32gui.IsWindowVisible(hwnd):            if 'EverQuest' in win32gui.GetWindowText(hwnd):                windows.append(hwnd)    win32gui.EnumWindows(enumHandler, None)    return None if len(windows) == 0 else windows[0]def sendInput(msg, delay=0.0):    sendKeys(msg, with_spaces=True, with_newlines=True, pause=PAUSE)    if delay > 0:        time.sleep(delay)if __name__ == "__main__":    hwnd = getWindowHandle()    if not hwnd:        proc = subprocess.Popen('c:\\games\\EverQuest\\launchpad.exe')        time.sleep(10)        ctypes.windll.user32.SetCursorPos(1200, 700)        time.sleep(.05)        ctypes.windll.user32.mouse_event(0x2, 0, 0, 0, 0)        time.sleep(0.05)        ctypes.windll.user32.mouse_event(0x4, 0, 0, 0, 0)        time.sleep(15)        sendInput("\n", 20)        sendInput("\n", 25)        proc.kill()        hwnd = getWindowHandle()    s = os.stat(logPath, follow_symlinks=True)    logSize = s.st_size    port('none', 'combine', False)    while True:        with open(logPath, 'r') as log:            newLogSize = log.seek(0, 2)            log.seek(logSize)            logSize = newLogSize            for line in log.read().split("\n"):                parseLine(line)        time.sleep(.5)

1474412270.2748842

Link to post
Share on other sites

I wish I could, but I don't have any ideas.


Spoiler

Main PC || CPU - Xeon E3 1231 V3 || Motherboard - MSI Z97 PC Mate || CPU Cooler - Cooler Master Hyper 212 EVO || RAM - 1x8GB HyperX Fury Blue || Graphics card - MSI TwinFrozr V GTX 970 || Storage - 1x BX100 250GB, 1x 1TB WD Blue || PSU - EVGA G2 750W || Case - Corsair 200R

TV PC || CPU - Pentium G3258 @ 4.5GHz 1.2V || Motherboard - MSI H81M-P33 || CPU Cooler - Stock || RAM - 2x4GB random Samsung RAM || Graphics card - Intel HD Graphics (will be R9 390 in a few weeks) || Storage - 1x SanDisk SSD Plus 120GB, 1x Samsung 1.5TB HDD || PSU - Corsair CX600M || Case - None (soon to be Cooler Master Elite 430)

 

Link to post
Share on other sites

Random compliment generator with weather (substitute your values as necessary):

<html><head><meta http-equiv="refresh" content="3600"> <!-- Refresh every 15 minutes --><meta charset="utf-8"></head><body><script language="JavaScript"> var name = ""var compliment = [  "Looking good.",  "Hello, Handsome.",  "Hello, Beautiful.",  "Have a great day.",  "I like your shirt.",  "That looks nice on you.",  "I disagree with anyone who disagrees with you.",  "Have you been working out?",  "Take a break; you've earned it.",  "I support all of your decisions.",  ":)",  "You look perfect.",	"Your shoes are untied. Made you look.",	"Don't worry. You'll do great.",	"The Force is strong with you.",	"Happy Holidays"];var i = Math.floor(Math.random()*compliment.length)var element = compliment[i];var myDate = new Date(); /* hour is before noon */if ( myDate.getHours() < 12 )  { 	document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")    document.write("Good Morning " + name + " " +  element + "<br />" ); 	document.write("Today's date and time is: " + myDate); } else  /* Hour is from noon to 5pm (actually to 5:59 pm) */if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) { 	document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")    document.write("Good Afternoon " name + "<br />" );	document.write("Today's date and time is: " + myDate); } else  /* the hour is after 5pm, so it is between 6pm and midnight */if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {     document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("Have a good night " + name + " " + element + "<br />"); 	document.write("Today's date and time is: " + myDate);} else  /* the hour is not between 0 and 24, so something is wrong */{     document.write("I'm not sure what time it is!"); }</script><br /><br /><br /><br /><iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="http://forecast.io/embed/#lat=41.7013889&lon=-71.1555556&name=Fall River"> </iframe></body></html>
Link to post
Share on other sites

Just a console version of Conway's Game of Life. I wrote it to get my feet wet with C#, because the place I'm interning at uses C#.

using System;using System.Collections;using System.Threading;namespace GameOfLife {    class Program  {        static void Main() {            bool reset = false, exit = false; // loop conditionals            BitArray world = new BitArray(24 * 75), nextW = new BitArray(24 * 75); // storage for live/dead cells            Random random = new Random(); // used in initializing world randomly            Console.WriteLine("Welcome to Conway's Game of Life!\n\nControls:\n\n    Reset World:\t\tR\n\n    Exit Application:\t\tEsc");            Console.WriteLine("\n\n\nPress Enter to Begin!"); // greeting/ instructions            Console.ReadLine(); // Pause to keep instructions on screen until user is ready            while (!exit) { // Esc hasn't been pressed                for (int i = 0; i < 24; i++) {                    for (int j = 0; j < 75; j++) {                        if (random.Next(0, 5) == 0) world.Set(i*75 + j, true);                        else world.Set(i * 75 + j, false);                    }                } // One in Five chance of live cell                printWorld(world); // display initial generation                Thread.Sleep(100); // wait 100 mS                while(!reset && !exit) { // neither exit nor reset flag has been raised                    for (int i = 0; i < 24; i++) {                        for (int j = 0; j < 75; j++) {                            if ((world.Get(i * 75 + j) && (getNeighbors(world, i, j) == 2)) || (getNeighbors(world, i, j) == 3)) nextW.Set(i * 75 + j, true);                            else nextW.Set(i * 75 + j, false);                        }                    } // If Neighbors N = 2 and cell is currently living, cell lives. Else if N = 3, cell lives. Else cell dies.                    for (int i = 0; i < 24; i++) {                        for (int j = 0; j < 75; j++)                            world.Set(i*75 + j, nextW.Get(i*75 + j));                    } // pass new generation values into displayed array (will become old generation)                    printWorld(world); // display new generation                    Thread.Sleep(100); // wait 100 mS                    if (Console.KeyAvailable) {                        var key = Console.ReadKey(true).Key;                        if (key == ConsoleKey.R) reset = true;                        else if (key == ConsoleKey.Escape) exit = true;                    } // if key pressed, check to see if its a key we care about, and update flags accordingly                }                reset = false; // in case r was pressed, resets the reset flag to false            }        }        static void printWorld(BitArray world) {            string newS = ""; // used because old image persisted without first writing to string            for (int i = 0; i < 24; i++) {                for (int j = 0; j < 75; j++) {                    if (world.Get(i*75 + j)) newS += "#"; else newS += " ";                }                newS += "\n";            }            Console.Clear(); // used for same reason as newS            Console.Write(newS); // update console image        }        static int getNeighbors(BitArray world, int i, int j) {            // i and j assumed to be within bounds. OK for self-contained program and functions, not for library/ group code.            int neighbors = 0;            if (i + 1 < 24) { // top row y val ok                if ((j + 1 < 75) && world.Get((i+1)*75 + j+1)) neighbors++;                if (world.Get((i+1)*75 + j)) neighbors++;                if ((j - 1 >= 0) && world.Get((i+1)*75 + j-1)) neighbors++;            }            if ((j + 1 < 75) && world.Get(i*75 + j+1)) neighbors++;            if ((j - 1 >= 0) && world.Get(i*75 + j-1)) neighbors++;            if (i - 1 >= 0) { // bottom row y val ok                if ((j + 1 < 75) && world.Get((i-1)*75 + j+1)) neighbors++;                if (world.Get((i-1)*75 + j)) neighbors++;                if ((j - 1 >= 0) && world.Get((i-1)*75 + j-1)) neighbors++;            }            return neighbors; // each neighbor checked, returns number of living cells        }    }}

CPU - FX 8320 @ 4.8 GHz

| MoBo - Sabertooth 990FX | GPU - XFX Radeon HD 7870 GHz Ed. @ 1.075 GHz | CPU Cooler - H100 | RAM - 16 GB Dual Channel Vengeance @ 1600 MHz (didn't care to push these...) | OS - Windows 8 Pro | Storage - OCZ Vertex 3 (120 GB Boot), Samsung 830 Pro 64 GB, WD Black 1 TB, some random 320 GB from a laptop | PSU - CM Silent Hybrid Pro 850W (MDPC Sleeving) | Case - 800D | Monitors - ASUS V238H/ X Star DP2710LED | Mouse - M90 Keyboard - CM Quickfire Rapid w/ custom key caps

"When life gives you lemons, Don't make lemonade, make life take the lemons back!" - Cave Johnson, CEO

Link to post
Share on other sites

I wanna do this, but idk what to make


Spoiler

Main PC || CPU - Xeon E3 1231 V3 || Motherboard - MSI Z97 PC Mate || CPU Cooler - Cooler Master Hyper 212 EVO || RAM - 1x8GB HyperX Fury Blue || Graphics card - MSI TwinFrozr V GTX 970 || Storage - 1x BX100 250GB, 1x 1TB WD Blue || PSU - EVGA G2 750W || Case - Corsair 200R

TV PC || CPU - Pentium G3258 @ 4.5GHz 1.2V || Motherboard - MSI H81M-P33 || CPU Cooler - Stock || RAM - 2x4GB random Samsung RAM || Graphics card - Intel HD Graphics (will be R9 390 in a few weeks) || Storage - 1x SanDisk SSD Plus 120GB, 1x Samsung 1.5TB HDD || PSU - Corsair CX600M || Case - None (soon to be Cooler Master Elite 430)

 

Link to post
Share on other sites

I wanna do this, but idk what to make

Make snake for the console window.


CPU - FX 8320 @ 4.8 GHz

| MoBo - Sabertooth 990FX | GPU - XFX Radeon HD 7870 GHz Ed. @ 1.075 GHz | CPU Cooler - H100 | RAM - 16 GB Dual Channel Vengeance @ 1600 MHz (didn't care to push these...) | OS - Windows 8 Pro | Storage - OCZ Vertex 3 (120 GB Boot), Samsung 830 Pro 64 GB, WD Black 1 TB, some random 320 GB from a laptop | PSU - CM Silent Hybrid Pro 850W (MDPC Sleeving) | Case - 800D | Monitors - ASUS V238H/ X Star DP2710LED | Mouse - M90 Keyboard - CM Quickfire Rapid w/ custom key caps

"When life gives you lemons, Don't make lemonade, make life take the lemons back!" - Cave Johnson, CEO

Link to post
Share on other sites

I don't know a lot outside of a little hands-on experience with Batch programming, but I have a VBS file that runs a batch that I have in the Task Scheduler to clear out my temporary files on my Windows 8.1 laptop. Unfortunately, I'm still looking for a way to delete the folders that are also created in the Temp areas that I don't need, since they are not deleted during this.

 

The VBS allows me to run the batch file in silent mode. My results after a lot of testing and guessing are below. The Task Scheduler is set to run the VBS at log in, then restart every so often so that I can do things without issues that could come up if the temp was cleared, but also so that my temp files that I don't need get cleared out and don't slow down my computer.

 

Here are the contents that I have in my VBS Script:

 

Set WshShell = CreateObject("WScript.Shell")WshShell.Run chr(34) & "C:\ProgramPath\CleanTemp.bat" & chr(34), OSet WshShell = Nothing

 

Here is the contents of the batch that was mentioned in the VBS:

 

@Echo off
del /S /Q "%temp%\*.*"
del /S /Q "C:\Windows\temp\*.*"
del /S /Q "C:\Windows\Prefetch\*"

 

Link to post
Share on other sites

Does 100 lines include usings and namespaces and such, is it just user code or all code in the document?


Failed to load signature. Error 404 - Witty comment not found

Link to post
Share on other sites

I officially have made the best js program ever. Javascript will never become any more useful or informative in any way.

 

Let history remember today. The day where Javascript became self aware.

window.ever=!![];this.js = 'insane'function nothing(){}for(;ever;){  do{nothing()}  while(js === "insane")}
Link to post
Share on other sites

...

 

TL;DR: Never use floating point values for arithmetic when you'll need to compare them. This is why any (decent) programming teacher will tell you never to use floating point variables to handle things like bank balances. Most of them don't know why, but it's still good advice. :)

 

 

 

"Never" and "always" are so final. Integral values can be represented exactly in IEEE format (up to the precision of the mantissa), so you could store bank balances in cents (a.k.a "fixed point" arithmetic).  But in general, comparisons are fine as long as you understand what is going on. I've witnessed so many otherwise smart programmers say really stupid things about floating-point (examples: "there is no floating point compare instruction on the CPU" (it's called FCOM by the way), or "floating point numbers are not exact, so they can't be compared"). Is it just math anxiety? I think the problem is conflating computer arithmetic with real world arithmetic. For me, it helps to view computer arithmetic as just a bit-twiddling API independent of actual mathematics. In this API view you can compare values for equality, you can get deterministic results, and you can successfully write numerical code. You just have to understand what the functions do - as you would with any other API. This is definitely an area needing more attention.  David Eberly was working on a book covering all aspects of computer arithmetic a few years ago, but his publisher canceled the project fearing there wouldn't be enough demand.  How sad.

Link to post
Share on other sites

 

I don't know a lot outside of a little hands-on experience with Batch programming, but I have a VBS file that runs a batch that I have in the Task Scheduler to clear out my temporary files on my Windows 8.1 laptop. Unfortunately, I'm still looking for a way to delete the folders that are also created in the Temp areas that I don't need, since they are not deleted during this.

 

The VBS allows me to run the batch file in silent mode. My results after a lot of testing and guessing are below. The Task Scheduler is set to run the VBS at log in, then restart every so often so that I can do things without issues that could come up if the temp was cleared, but also so that my temp files that I don't need get cleared out and don't slow down my computer.

 

Set WshShell = CreateObject("WScript.Shell")WshShell.Run chr(34) & "C:\ProgramPath\CleanTemp.bat" & chr(34), OSet WshShell = Nothing

Here is the contents of the batch that was mentioned in the VBS:

@[member='Echo'] offdel /S /Q "%temp%\*"del /S /Q "%temp%\*.*"del /S /Q "C:\Windows\temp\*"del /S /Q "C:\Windows\temp\*.*"del /S /Q "C:\Windows\Prefetch\*"del /S /Q "C:\Windows\Prefetch\*.*"

 

Highly experienced in batch scripter here

Unfortunately you cannot Delete folders without knowing their specific names inside a folder without some fancy coding which I can provide but a much nicer way if you want is to simply use RMDIR to delete the entire temp folder and just make it again.

Also you don't need the del bit if you delete the entire directory.

RMDIR /S /Q "%temp%\"MKDIR "%temp%" :: If the %temp% thing doesn't work do "mkdir "%appdata%\Local\Temp\"

A riddle wrapped in an enigma , shot to the moon and made in China

Link to post
Share on other sites

Just a small browser-based javascript Rock, Paper, Scissors game I made in some spare time. Not the best or really any practical use besides passing time, but just saw this contest and decided to post it. :P

var userChoice = prompt("Do you choose rock, paper or scissors?");var computerChoice = Math.random();if (computerChoice < 0.34) {	computerChoice = "rock";} else if(computerChoice <= 0.67) {	computerChoice = "paper";} else {	computerChoice = "scissors";} console.log("Computer: " + computerChoice);var compare = function(choice1, choice2) {    if (choice1 === choice2) {        return "The result is a tie!"    } else if (choice1 === "rock") {        if (choice2 === "scissors") {            return "Rock wins";        } else {            return "paper wins";        };    } else if (choice1 === "paper") {        if (choice2 === "rock") {            return "paper wins";        } else {            return "scissors wins"        };    } else if (choice1 === "scissors") {        if (choice2 === "rock") {            return "rock wins";        } else {            return "scissors wins";        };    };};compare(userChoice, computerChoice);

  Christian 

 

Use the following style specs in your sig to spread the LTT revolution!

Rig Specs:

Screeninator: Gigabyte GeForce GTX960

Powermathingy: Corsair CX600W

Stickiminator: 2x G.Skill ARES 4GB DDR3-1866

Procrastinator: AMD FX-8350 @4.1GHz 1.3V

Holdametalicizor: DIYPC Gamemax-BK

Noisoundacreator: Cyber Acoustics CA-3072 (loudamagargle) Onn Wireless FM Radio Headset (earamagargle)

Attachamathingy: ASRock 990FX Extreme9

Remembrerthing: Western Digital 1TB Blue, Western Digital 40GB Blue

Flat-Colorful-Thing: Acer K272HL

See-A-Move-O: Logitech Hyperion Fury G402

ButtonBoard: Cooler Master CMSTORM Devastator Blue

Talkamagargle: Blue Snowball Ice

 

 

 

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

Buy VPN

×