Jump to content

The under 100 line challenge!

fletch to 99

Hi

Totally new here but thought I would join the programmer master race.

On 6/15/2013 at 5:15 AM, Nathan4567a said:

Here is a converter that takes any US measurement (like feet or miles) and converts it into inches, feet, yards, and miles and displays them all to the user. Its really useful to do quick and easy conversions. It could easily be adapted to metric also.

 

https://gist.github.com/LernerProductions/5786703

 

I could not help my self into making that unit converter smaller.

Spoiler

import java.util.InputMismatchException;
import java.util.Scanner;
public class UnitConverter {
	public static double inches, feet, yards, miles;
	public static void main(String[] args) {
		Scanner Keyboard=new Scanner(System.in);
		String again = null;
		do {
			try {
				System.out.println("Enter a number: ");
				int num=Keyboard.nextInt();
				System.out.println("Select the units. 1=miles, 2=yards, 3=feet, 4=inches");
				int unit=Keyboard.nextInt();
				miles = (unit==2) ? num/1760 : (unit==3) ? num/5280 : (unit==4) ? num/63360 : num;
				yards = (unit==1) ? 1760*num : (unit==3) ? num/3 : (unit==4) ? num/36 : num;
				feet = (unit==1) ? 5280*num : (unit==2) ? 3*num : (unit==4) ? num/12 : num;
				inches = (unit==1) ? 63360*num : (unit==2) ? 36*num : (unit==3) ? 12*num : num;
				System.out.printf("Miles: %f \nYards: %f \nFeet: %f \nInches: %f", miles, yards, feet, inches);
			} catch (Exception e) {
				if (e instanceof InputMismatchException) {
					System.out.println("Please enter a valid integer number!!!");
				}else{
					System.out.println("Unsuspected error occurred contact R2D2!!!");
				}
			}finally{
				System.out.println("Again? (y/n): ");
				again = Keyboard.next();
			}
		} while (again!= null && again.toLowerCase().equals("y"));
	}
}

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ManagementObjectSearcher
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void output_BTN_Click(object sender, EventArgs e)
        {
            try
            {
                output_ET.Clear();
                foreach (
                ManagementObject queryObj in
                new System.Management.ManagementObjectSearcher("root\\CIMV2", "Select * from " + class_ET.Text).Get())
                    foreach (PropertyData property in queryObj.Properties)
                        if (property.Value != null || !notNull_CB.Checked)
                            output_ET.AppendText((arrayFormat_CB.Checked ? "\"" : "") +
                                                 property.Name +
                                                 (arrayFormat_CB.Checked ? (namesOnly_CB.Checked ? "" : ": " + property.Value) + "\"," : (namesOnly_CB.Checked ? "" : ": " + property.Value)) +
                                                       (newLine_CB.Checked ? Environment.NewLine : "")
                                                       ); // If you are reading this method/line, DONT!! If you do - you may decide that the best couse of action is suicide... 
                                                       //But now when i think about it, u probobly alreay dont have a life since u are reading it....

                        
            }
            catch (Exception ex )
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

https://github.com/WithoutCaps/ManagementObjectSearcher/blob/master/ManagementObjectSearcher/Form1.cs

 

Mini application to get output of all these badboys in managed manner

Screenshot 2017-04-27 20.18.07.png

Link to comment
Share on other sites

Link to post
Share on other sites

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;

namespace PlayRandom
{
    class Program {
        static void Main(string[] args) {
            List<string> allowedTypes = new List<string>(new string[] { ".mkv", ".avi", ".mp4", ".mpg" });
            try {
                string sDir;
                if (args.Length > 0) sDir = args[0];
                else {
                    CheckRegistryEntry(String.Empty);
                    throw new Exception("No arguments passed.");
                }
                CheckRegistryEntry(sDir);
                if (System.IO.Directory.Exists(sDir)) {
                    bool canPlayFile = false;
                    string fileToPlay = "";
                    do {
                        fileToPlay = returnPlayable(sDir);
                        foreach (string allowedType in allowedTypes) {
                            if (fileToPlay.ToLower().EndsWith(allowedType)) {
                                canPlayFile = true;
                                break;
                            }
                        }
                    } while (!canPlayFile);
                    System.Diagnostics.Process.Start(fileToPlay);
                }
                else throw new Exception(String.Format("{0} is not a valid directory.", sDir));
            }
            catch (Exception AwwCrap) { System.Windows.Forms.MessageBox.Show(String.Format("Exception: {0}", AwwCrap.Message)); }
        }
        public static void CheckRegistryEntry(string args) {
            const string DesiredKeyName = "PlayRandomAH";
            const string ctxString = "Play Random File";
            string ExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8).Replace('/', '\\');
            string ctxCommand = String.Format("\"{0}\" \"%1\"", ExecutablePath);
            RegistryKey rk = Registry.ClassesRoot.OpenSubKey("Directory\\shell");
            String[] subkeys = rk.GetSubKeyNames();
            bool ctxIsOkay = false;
            foreach (string sk in subkeys) {
                if (sk == DesiredKeyName) {
                    RegistryKey MyKey = rk.OpenSubKey(sk);
                    if (MyKey.GetValue("").ToString() == ctxString) {
                        foreach (string ssk in MyKey.GetSubKeyNames()) {
                            if (ssk == "command") {
                                MyKey = MyKey.OpenSubKey("command");
                                string currctxCommand = MyKey.GetValue("").ToString();
                                if (currctxCommand.ToLower() == ctxCommand.ToLower()) ctxIsOkay = true;
                            }
                        }
                    }
                }
            }
            if (ctxIsOkay == false) {
                if (IsAdministrator()) {
                    rk = Registry.ClassesRoot.OpenSubKey("Directory\\shell", true);
                    rk.DeleteSubKeyTree(DesiredKeyName, false);
                    rk.CreateSubKey(DesiredKeyName);
                    rk.OpenSubKey(DesiredKeyName, true).SetValue("", ctxString);
                    rk.OpenSubKey(DesiredKeyName, true).CreateSubKey("command");
                    rk.OpenSubKey(DesiredKeyName, true).OpenSubKey("command", true).SetValue("", String.Format("\"{0}\" \"%1\"", ExecutablePath));
                }
                else GetAdmin(args, ExecutablePath);
            }
        }
        static string returnPlayable(string path) {
            List<string> dirs = new List<string>(Directory.EnumerateDirectories(path));
            List<string> files = new List<string>(Directory.EnumerateFiles(path));
            return (dirs.Count > 0) ? returnPlayable(dirs.PickRandom()) : ((files.Count > 0) ? files.PickRandom() : String.Empty);
        }
        public static bool IsAdministrator() {
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        public static void GetAdmin(string args, string filename) {
            Process elevate = new Process();
            elevate.StartInfo.UseShellExecute = true;
            elevate.StartInfo.Verb = "runas";
            elevate.StartInfo.Arguments = args;
            elevate.StartInfo.FileName = filename;
            elevate.Start();
            Environment.Exit(0);
        }
    }
    public static class EnumerableExtension {
        public static T PickRandom<T>(this IEnumerable<T> source)                           { return source.PickRandom(1).Single(); }
        public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)   { return source.Shuffle().Take(count); }
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)                 { return source.OrderBy(x => Guid.NewGuid()); }
    }
}

Opens a random file of a type specified on line 12 (I have mine set to video formats)

99 lines with a lot of trimming, but nothing too egregious.

 

There is one nested ternary return statement in line 77 that is less than beautiful.

 

Usage: Put it somewhere you want to keep it, run it from there. Give it admin rights to create the context menu item in the registry.

Right click a folder with some video files, "Play Random File", and it will open it your default media player.

PlayRandom Context.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

Does a program count as useful if it crashes the hard drive and makes it unbootable? If so I have an idea using bitwise operators to basically flip all the bits on somebody's hard drive. 

DELETE! DELETE!

EXTERMINATE! EXTERMINATE!

Silence will fall.

 

PSU Tier List - I keep forgetting where this is so I'm going to leave it here.

Link to comment
Share on other sites

Link to post
Share on other sites

;;; implement split of list ;;;
(define (split lst)
  (if (null? lst)
      (list '() '())
      (if (null? (cdr lst))
          (list (list (car lst)) '())
          (let*( (x (car lst))
                 (y (car (cdr lst)))
                 (z (split (cdr (cdr lst))))
                 (z1 (car z))
                 (z2 (car (cdr z)))
                 )
            (list (cons x z1) (cons y z2))
            
            ))))


;;; implement merge ;;;

(define (merge lst1 lst2)
     (if (null? lst1)
         lst2
         (if (null? lst2)
             lst1
             (if (< (car lst1) (car lst2))
                 (cons (car lst1) (merge (cdr lst1) lst2))
                 (cons (car lst2) (merge (cdr lst2) lst1))
                 )
             )
         )
  )

;;; implement mergesort ;;;

(define (mergesort lst)
  (if(or (null? lst) (null? (cdr lst)))
     lst
     (let*((splitted (split lst))
           (left (mergesort (car splitted)))
           (right (mergesort (car (cdr splitted))))
           )
       (merge left right))))

simple implementation of mergesort with Racket an derived Scheme/Lisp interpreter.

Link to comment
Share on other sites

Link to post
Share on other sites

I've just started programming in Python properly in the past 2-3 weeks (I started looking at Python 2 years ago) and I've created this...

GitHub: https://github.com/JackSewell-Git/Gold-Box

Gold Box is a text based game where you have to locate a hidden box full of gold.

Link to comment
Share on other sites

Link to post
Share on other sites

I made this script a while ago. it rewrites number to the scientific notation (like 5,43*10^5).

The language is AutoIt3

 


$in1 = InputBox("Input","Enter a number you want to rewrite","Enter number")
$out1 = $in1
$out2 = 0
$repeat = True

While $repeat
    $repeat = False
   If $out1==0 Then
       MsgBox(0,"error","can't be 0")
   Elseif $out1>=10 Then
       $out1 = $out1/10
       $out2 = $out2+1
       $repeat = True
   Elseif $out1<=1 Then
       $out1 = $out1*10
       $out2 = $out2-1
       $repeat = True
    Else
       MsgBox(0, "New number", $out1 & "*10^" & $out2)
   EndIf
WEnd

 "Aeneas troianus est."

I'm allergic to social interaction in real life, don't talk to me in real life please.

don't forget to quote or tag (@marten.aap2.0) me when you reply!

Link to comment
Share on other sites

Link to post
Share on other sites

Periodic table in under 100 lines

78 Lines :D


from table import *

def User(decision):
    if len(decision) <= 2:
        print (elements[decision]['name'])
        return elements[decision]['mass']
    if len(decision) > 2:
        sym = symbols[decision]
        print (elements[sym]['name'])
        return elements[sym]['mass']
def floater(decision):
    sym = invatomicmass[decision]
    print (elements[sym]['name'])
    return elements[sym]['atomic']  
def find(decision):
    if type(decision) == int:
        return integer(decision)
    if type(decision) == str:
        return User(decision)
    if type(decision) == float:
        return floater(decision)
def help():
    print ("Run find(x) module by giving it one of the following arguments:")
    print ("\tx: Integers (atomic number)")
    print ("\tx: Floating point numbers (atomic mass)")
    print ("\tx: Element names (abbreviation or full name)")
    print ("\nAll of these will return the atomic mass of the element, except for floating point numbers.")
    print ("Those will return atomic mass.")

 

And then the table itself

Table.py

technically 4 or 5 lines because they are really long lines

 


elements = {'Ru': {'mass': 102.91, 'name': 'rhodium', 'atomic': 45}, 'Rb': {'mass': 85.468, 'name': 'rubidium', 'atomic': 37}, 'Pt': {'mass': 195.09, 'name': 'platinum', 'atomic': 78}, 'Ni': {'mass': 58.71, 'name': 'nickel', 'atomic': 28}, 'Na': {'mass': 22.99, 'name': 'sodium', 'atomic': 11}, 'Nb': {'mass': 92.906, 'name': 'niobium', 'atomic': 41}, 'Bh': {'mass': 272.0, 'name': 'bohrium', 'atomic': 107}, 'Ne': {'mass': 20.179, 'name': 'neon', 'atomic': 10}, 'Li': {'mass': 6.941, 'name': 'lithium', 'atomic': 3}, 'Pb': {'mass': 207.2, 'name': 'lead', 'atomic': 82}, 'Re': {'mass': 128.207, 'name': 'rhenium', 'atomic': 75}, 'Tl': {'mass': 204.37, 'name': 'thallium', 'atomic': 81}, 'As': {'mass': 74.922, 'name': 'arsenic', 'atomic': 33}, 'Ra': {'mass': 226.03, 'name': 'radium', 'atomic': 88}, 'Pd': {'mass': 106.4, 'name': 'palladium', 'atomic': 46}, 'Ti': {'mass': 47.9, 'name': 'titanium', 'atomic': 22}, 'Rn': {'mass': 222.0, 'name': 'radon', 'atomic': 86}, 'Te': {'mass': 127.6, 'name': 'tellerium', 'atomic': 52}, 'Po': {'mass': 209.0, 'name': 'polonium', 'atomic': 84}, 'Ta': {'mass': 180.95, 'name': 'tantalum', 'atomic': 73}, 'Be': {'mass': 9.0122, 'name': 'beryllium', 'atomic': 4}, 'Fr': {'mass': 223.0, 'name': 'francium', 'atomic': 87}, 'Xe': {'mass': 131.3, 'name': 'xenon', 'atomic': 54}, 'Ba': {'mass': 137.33, 'name': 'barium', 'atomic': 56}, 'Hs': {'mass': 227.0, 'name': 'hassium', 'atomic': 108}, 'La': {'mass': 0, 'name': 'lanthanum', 'atomic': 57}, 'Db': {'mass': 268.0, 'name': 'dubnium', 'atomic': 105}, 'Bi': {'mass': 206.98, 'name': 'bismuth', 'atomic': 83}, 'Tc': {'mass': 97.0, 'name': 'technetium', 'atomic': 43}, 'Fe': {'mass': 55.847, 'name': 'iron', 'atomic': 26}, 'Br': {'mass': 79.904, 'name': 'bromine', 'atomic': 35}, 'H': {'mass': 1.0079, 'name': 'hydrogen', 'atomic': 1}, 'Cu': {'mass': 63.546, 'name': 'copper', 'atomic': 29}, 'Hf': {'mass': 178.49, 'name': 'hafnium', 'atomic': 72}, 'Hg': {'mass': 200.59, 'name': 'mercury', 'atomic': 80}, 'He': {'mass': 4.0026, 'name': 'helium', 'atomic': 2}, 'Cl': {'mass': 35.453, 'name': 'chlorine', 'atomic': 17}, 'Mg': {'mass': 24.305, 'name': 'magnesium', 'atomic': 12}, 'B': {'mass': 10.81, 'name': 'boron', 'atomic': 5}, 'Sg': {'mass': 271.0, 'name': 'seaborgium', 'atomic': 106}, 'F': {'mass': 18.998, 'name': 'fluorine', 'atomic': 9}, 'I': {'mass': 126.9, 'name': 'iodine', 'atomic': 53}, 'Sr': {'mass': 87.62, 'name': 'strontium', 'atomic': 38}, 'Mo': {'mass': 95.94, 'name': 'molybdenum', 'atomic': 42}, 'Mn': {'mass': 54.938, 'name': 'manganese', 'atomic': 25}, 'Zn': {'mass': 65.38, 'name': 'zinc', 'atomic': 30}, 'O': {'mass': 15.999, 'name': 'oxygen', 'atomic': 8}, 'N': {'mass': 14.007, 'name': 'nitrogen', 'atomic': 7}, 'P': {'mass': 30.974, 'name': 'phosphorus', 'atomic': 15}, 'S': {'mass': 32.06, 'name': 'sulfur', 'atomic': 16}, 'Sn': {'mass': 118.69, 'name': 'tin', 'atomic': 50}, 'W': {'mass': 183.84, 'name': 'tungsten', 'atomic': 74}, 'Cr': {'mass': 51.996, 'name': 'chromium', 'atomic': 24}, 'Y': {'mass': 88.906, 'name': 'yttrium', 'atomic': 39}, 'Sb': {'mass': 121.75, 'name': 'antimony', 'atomic': 51}, 'Os': {'mass': 190.2, 'name': 'osmium', 'atomic': 76}, 'Se': {'mass': 78.96, 'name': 'selenium', 'atomic': 34}, 'Sc': {'mass': 44.955912, 'name': 'scandium', 'atomic': 21}, 'Ac': {'mass': 227.0, 'name': 'actinium', 'atomic': 89}, 'Co': {'mass': 58.933, 'name': 'cobalt', 'atomic': 27}, 'Ag': {'mass': 107.87, 'name': 'silver', 'atomic': 47}, 'Kr': {'mass': 83.8, 'name': 'krypton', 'atomic': 36}, 'C': {'mass': 12.011, 'name': 'carbon', 'atomic': 6}, 'Si': {'mass': 28.086, 'name': 'silicon', 'atomic': 14}, 'k': {'mass': 39.096, 'name': 'potassium', 'atomic': 19}, 'Ir': {'mass': 192.22, 'name': 'iridium', 'atomic': 77}, 'Rf': {'mass': 265.0, 'name': 'rutherfordium', 'atomic': 104}, 'Cd': {'mass': 112.41, 'name': 'cadmium', 'atomic': 48}, 'Ge': {'mass': 72.59, 'name': 'germanium', 'atomic': 32}, 'Ar': {'mass': 39.948, 'name': 'argon', 'atomic': 18}, 'Au': {'mass': 196.97, 'name': 'gold', 'atomic': 79}, 'Mt': {'mass': 276.0, 'name': 'meitnerium', 'atomic': 109}, 'Ga': {'mass': 69.72, 'name': 'gallium', 'atomic': 31}, 'v': {'mass': 50.941, 'name': 'vanadium', 'atomic': 23}, 'Cs': {'mass': 132.91, 'name': 'cesium', 'atomic': 55}, 'Al': {'mass': 26.982, 'name': 'aluminum', 'atomic': 13}, 'At': {'mass': 210.0, 'name': 'astatine', 'atomic': 85}, 'Ca': {'mass': 40.08, 'name': 'calcium', 'atomic': 20}, 'Zr': {'mass': 91.224, 'name': 'zirconium', 'atomic': 40}, 'In': {'mass': 114.82, 'name': 'indium', 'atomic': 49}} symbols = {'krypton': 'Kr', 'copper': 'Cu', 'rubidium': 'Rb', 'iodine': 'I', 'rhenium': 'Re', 'gold': 'Au', 'radium': 'Ra', 'neon': 'Ne', 'calcium': 'Ca', 'cobalt': 'Co', 'germanium': 'Ge', 'titanium': 'Ti', 'seaborgium': 'Sg', 'zinc': 'Zn', 'astatine': 'At', 'arsenic': 'As', 'hydrogen': 'H', 'fluorine': 'F', 'platinum': 'Pt', 'niobium': 'Nb', 'hafnium': 'Hf', 'lead': 'Pb', 'sodium': 'Na', 'thallium': 'Tl', 'chromium': 'Cr', 'selenium': 'Se', 'tantalum': 'Ta', 'technetium': 'Tc', 'cesium': 'Cs', 'meitnerium': 'Mt', 'tin': 'Sn', 'actinium': 'Ac', 'tellerium': 'Te', 'osmium': 'Os', 'sulfur': 'S', 'helium': 'He', 'lithium': 'Li', 'hassium': 'Hs', 'beryllium': 'Be', 'mercury': 'Hg', 'yttrium': 'Y', 'nickel': 'Ni', 'polonium': 'Po', 'ruthenium': 'Ru', 'potassium': 'k', 'francium': 'Fr', 'bohrium': 'Bh', 'dubnium': 'Db', 'strontium': 'Sr', 'bromine': 'Br', 'argon': 'Ar', 'antimony': 'Sb', 'rhodium': 'Ru', 'boron': 'B', 'tungsten': 'W', 'carbon': 'C', 'palladium': 'Pd', 'silver': 'Ag', 'chlorine': 'Cl', 'phosphorus': 'P', 'rutherfordium': 'Rf', 'bismuth': 'Bi', 'scandium': 'Sc', 'aluminum': 'Al', 'oxygen': 'O', 'vanadium': 'v', 'nitrogen': 'N', 'lanthanum': 'La', 'gallium': 'Ga', 'zirconium': 'Zr', 'manganese': 'Mn', 'radon': 'Rn', 'silicon': 'Si', 'molybdenum': 'Mo', 'iridium': 'Ir', 'cadmium': 'Cd', 'magnesium': 'Mg', 'iron': 'Fe', 'xenon': 'Xe', 'barium': 'Ba', 'indium': 'In'} invatomicmass = {0: 'La', 1.0079: 'H', 69.72: 'Ga', 6.941: 'Li', 114.82: 'In', 121.75: 'Sb', 39.948: 'Ar', 54.938: 'Mn', 226.03: 'Ra', 79.904: 'Br', 268.0: 'Db', 112.41: 'Cd', 22.99: 'Na', 272.0: 'Bh', 271.0: 'Sg', 276.0: 'Mt', 118.69: 'Sn', 207.2: 'Pb', 127.6: 'Te', 92.906: 'Nb', 195.09: 'Pt', 87.62: 'Sr', 180.95: 'Ta', 206.98: 'Bi', 35.453: 'Cl', 51.996: 'Cr', 204.37: 'Tl', 12.011: 'C', 58.933: 'Co', 65.38: 'Zn', 88.906: 'Y', 74.922: 'As', 83.8: 'Kr', 58.71: 'Ni', 18.998: 'F', 265.0: 'Rf', 44.955912: 'Sc', 190.2: 'Os', 72.59: 'Ge', 196.97: 'Au', 50.941: 'v', 30.974: 'P', 102.91: 'Ru', 15.999: 'O', 20.179: 'Ne', 10.81: 'B', 4.0026: 'He', 47.9: 'Ti', 126.9: 'I', 63.546: 'Cu', 9.0122: 'Be', 32.06: 'S', 210.0: 'At', 40.08: 'Ca', 91.224: 'Zr', 95.94: 'Mo', 183.84: 'W', 85.468: 'Rb', 78.96: 'Se', 28.086: 'Si', 222.0: 'Rn', 223.0: 'Fr', 97.0: 'Tc', 200.59: 'Hg', 227.0: 'Ac', 131.3: 'Xe', 106.4: 'Pd', 209.0: 'Po', 26.982: 'Al', 39.096: 'k', 24.305: 'Mg', 137.33: 'Ba', 178.49: 'Hf', 192.22: 'Ir', 132.91: 'Cs', 128.207: 'Re', 55.847: 'Fe', 14.007: 'N', 107.87: 'Ag'} inv_pro = {1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'Na', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar', 19: 'k', 20: 'Ca', 21: 'Sc', 22: 'Ti', 23: 'v', 24: 'Cr', 25: 'Mn', 26: 'Fe', 27: 'Co', 28: 'Ni', 29: 'Cu', 30: 'Zn', 31: 'Ga', 32: 'Ge', 33: 'As', 34: 'Se', 35: 'Br', 36: 'Kr', 37: 'Rb', 38: 'Sr', 39: 'Y', 40: 'Zr', 41: 'Nb', 42: 'Mo', 43: 'Tc', 45: 'Ru', 46: 'Pd', 47: 'Ag', 48: 'Cd', 49: 'In', 50: 'Sn', 51: 'Sb', 52: 'Te', 53: 'I', 54: 'Xe', 55: 'Cs', 56: 'Ba', 57: 'La', 72: 'Hf', 73: 'Ta', 74: 'W', 75: 'Re', 76: 'Os', 77: 'Ir', 78: 'Pt', 79: 'Au', 80: 'Hg', 81: 'Tl', 82: 'Pb', 83: 'Bi', 84: 'Po', 85: 'At', 86: 'Rn', 87: 'Fr', 88: 'Ra', 89: 'Ac', 104: 'Rf', 105: 'Db', 106: 'Sg', 107: 'Bh', 108: 'Hs', 109: 'Mt'}

Link to comment
Share on other sites

Link to post
Share on other sites

Good morning,

If you use a language like Java, you could just type out the program on one line, the compiler would understand it, but it would not be readable.

 

 

Regards,

Richard.

Link to comment
Share on other sites

Link to post
Share on other sites

Wrote a shell script for doing a dropbox-style SSH-based RSync on a specific directory. Manual invocation, but when it runs it does an incremental diff on the files on both sides and moves the ones that were created/modified.

#!/bin/bash
#Server parameters
server="10.0.0.1" #Change this to your server's IP address
username="jim"
portnumber="20" #Your SSH server's port number.


#Excluded files
#I added an example excludes file based on files I've had problems with in the past.
path_to_excludes="...../rsyncexcludes.txt" #Change this to the path to the excludes file

#source and destination
#Please note that due to the nature of rsync, these MUST be absolute paths. They also
#must match on the source and destination, so if you mirror /home/joey/SyncMe on one
#machine, you'll get /home/joey/SyncMe on the other.
source_path="/..../SyncMe" #Path to what you're syncing plus the folder name itself
dest_path="/..../" #Path to what you're syncing without the folder itself

#Tools
excludes="--exclude-from $path_to_excludes" #if you prefer to hard-code exludes, use this variable instead of the excludes file
sshcommand="ssh -p $portnumber" #This is the SSH command. If you need extra params to login, place them here

#From here down is the code to sync stuff itself. Most of the params should be above.
rsync -avucr $excludes -e "$sshcommand" $username@$server:$source_path $dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPull complete. Beginning push...\e[m"
else
	echo -e "\033[1;31mFailed to fetch updates. Please diagnose and rerun the script.\033[m"
	exit;
fi
rsync -avucr $excludes -e "$sshcommand" $source_path $username@$server:$dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPush complete. Script is successful.\e[m"
else
	echo -e "\e[1;31mPush failed. Please diagnose and rerun the script.\e[m"
	exit;
fi

It is written in Bash, and relies on RSync being installed on both systems. If this counts, then including the readme and excludes example file, the entire project comes in at under 100 lines.

 

https://github.com/CannonContraption/rsynccstation

for the other files.

 

I do wish that there was BASH syntax highlighting support, but Perl isn't so far off so if something looks out of place in the highlighting, that's why.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 23.5.2017 at 2:29 AM, CannonContraption said:

Wrote a shell script for doing a dropbox-style SSH-based RSync on a specific directory. Manual invocation, but when it runs it does an incremental diff on the files on both sides and moves the ones that were created/modified.


#!/bin/bash
#Server parameters
server="10.0.0.1" #Change this to your server's IP address
username="jim"
portnumber="20" #Your SSH server's port number.


#Excluded files
#I added an example excludes file based on files I've had problems with in the past.
path_to_excludes="...../rsyncexcludes.txt" #Change this to the path to the excludes file

#source and destination
#Please note that due to the nature of rsync, these MUST be absolute paths. They also
#must match on the source and destination, so if you mirror /home/joey/SyncMe on one
#machine, you'll get /home/joey/SyncMe on the other.
source_path="/..../SyncMe" #Path to what you're syncing plus the folder name itself
dest_path="/..../" #Path to what you're syncing without the folder itself

#Tools
excludes="--exclude-from $path_to_excludes" #if you prefer to hard-code exludes, use this variable instead of the excludes file
sshcommand="ssh -p $portnumber" #This is the SSH command. If you need extra params to login, place them here

#From here down is the code to sync stuff itself. Most of the params should be above.
rsync -avucr $excludes -e "$sshcommand" $username@$server:$source_path $dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPull complete. Beginning push...\e[m"
else
	echo -e "\033[1;31mFailed to fetch updates. Please diagnose and rerun the script.\033[m"
	exit;
fi
rsync -avucr $excludes -e "$sshcommand" $source_path $username@$server:$dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPush complete. Script is successful.\e[m"
else
	echo -e "\e[1;31mPush failed. Please diagnose and rerun the script.\e[m"
	exit;
fi

It is written in Bash, and relies on RSync being installed on both systems. If this counts, then including the readme and excludes example file, the entire project comes in at under 100 lines.

 

https://github.com/CannonContraption/rsynccstation

for the other files.

 

I do wish that there was BASH syntax highlighting support, but Perl isn't so far off so if something looks out of place in the highlighting, that's why.

Now you just need to tie it down with some inotify goodness, right? :) Or just "cheat" and use incron to trigger it when folder contents change.

Link to comment
Share on other sites

Link to post
Share on other sites

<?php

       if (isDomainAvailible('http://google.com'))
       {
               echo "<div class='alert alert-success'>No Problem!</div>";
       }
       else
       {
               echo "<div class='alert alert-danger'><strong>Problem Detected! GET TO DA CHOPPER</strong></div>";
       }
       function isDomainAvailible($domain)
       {
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
               $response = curl_exec($curlInit);
               curl_close($curlInit);
               if ($response) return true;
               return false;
       		}
?>

A PHP script that checks if it is able to connect to domain :)

 

Q: How many prolog programmers does it take to change a lightbulb?

A: Yes.

Link to comment
Share on other sites

Link to post
Share on other sites

If I understood the theory correctly, I made a basic Huffman codec in Python

def bucketize_string(input):
    buckets = {}
    for idx in xrange(0, len(input), 1):
        char = input[idx]
        if char not in buckets:
            buckets[char] = 1
        else:
            buckets[char] += 1
    return buckets

def create_nodes(leaves, freq_idx = 1):
    nodes = []
    if len(leaves) > 1:
        for idx in xrange(0, len(leaves)-1, 2):
            if type(leaves[idx+1]) is tuple:
                nodes.append([leaves[idx], leaves[idx+1], leaves[idx][freq_idx] + leaves[idx+1][1]])
            else:
                nodes.append([leaves[idx], leaves[idx+1], leaves[idx][freq_idx] + leaves[idx+1][freq_idx]])
        if idx < len(leaves) - 2:
            nodes.append(leaves[idx+2])
    else:
        nodes.append(leaves[0])
    return nodes

def build_sym_table(tree):
    sym_table = {}
    map_node(tree, sym_table, '')
    return sym_table

def map_node(node, sym_table, code):
    for x in xrange(0, len(node), 1):
        if type(node[x]) is list:
            map_node(node[x], sym_table, code + str(x))
        elif type(node[x]) is tuple:
            sym_table[node[x][0]] = code + str(x)

def huffman_encode(in_string):
    import operator
    buckets = bucketize_string(foobar)
    tree = create_nodes(sorted(buckets.items(), key=operator.itemgetter(1)))

    while len(tree) > 2:
        tree = create_nodes(tree, 2)
    sym_table = build_sym_table(tree)

    code = ''
    for x in xrange(0, len(in_string), 1):
        code += sym_table[in_string[x]]
    return code, tree
    
def huffman_decode(in_stream, tree):
    message = ''
    node = tree
    for x in xrange(0, len(in_stream), 1):
        symbol = int(in_stream[x])
        node = node[symbol]
        if type(node) is tuple:
            message += node[0]
            node = tree

    return message

This has no practical purpose (for one it expands rather than compresses), but I was bored.

 

EDIT again: I think I finally got it down. It now theoretically compresses :3

Edited by M.Yurizaki
Link to comment
Share on other sites

Link to post
Share on other sites

https://pastebin.com/6qTPYQZb

a little text based ellipse solver that asks for defining variables and then outputs useful information such as the vertexes, endpoints, foci, and what kind of ellipse has been defined (horizontal, vertical, or a circle)

inspired by my college math class unit on conics and ellipses.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 15/06/2013 at 7:27 AM, fletch to 99 said:

Here's a HTML clock I made in 10 minutes


<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>

 

 

<script type="text/javascript" src="http://100widgets.com/js_data.php?id=264"></script>

Link to comment
Share on other sites

Link to post
Share on other sites

This is a .bat script that temporally sets the APPDATA folder to a different folder to allow minecraft to be run off a flash drive.  It also has a built in version switcher. I used this to play minecraft at school. More to showoff than to actually play. Its value is probably less since minecraft does those things now. However this works with hacked clients that allow you to play offline multiplayer with any username. These hacked clients only work up to release 1.5.2 but it can be fun to go back in time sometimes. It also has an ASCII grass block. I thought it was a nice touch.

@echo off
color 0a
title Minecraft
If Not Exist .\Minecraft\.minecraft\bin\ (
color 07
Echo.
Echo   Minecraft has yet to be installed in this folder. 
Echo   Please hit enter and run it for the first time.
Echo   After this, you will be able to run the version selector
Pause >Nul
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)
Del .\Minecraft\.minecraft\bin\minecraft.jar
cls
Echo.
Echo                                +#++           
Echo                              +####+#+         
Echo                            +#+#++++###+       
Echo                          #++++###+++#+++#     
Echo                        #+##+###++#####++:+#   
Echo      Minecraft        ##:##+#+##+++++#+#+##+  
Echo ===================   ''#++#+#++#++##++##+;+  
Echo                       '''''+#++##+#++#+;+;++  
Echo  A. 1.2.6 (Alpha)     '''+'####+++###+;;;+++  
Echo  B. 1.7.3 (Beta)      '''+'';''##++++;+;+++;  
Echo  C. 1.5.2 (Release)   ''''+';';';;;;+;+++++;  
Echo                       '''''++'+'''+++++++++;  
Echo ===================   ';;''++'''++++;+++;+++  
Echo                       ''''''+;'''+;++++'+''+  
Echo                       '''''';';''++++;;+++;;  
Echo                        ,'+'''''''+++''+'+;:   
Echo                          :;;;'';'+'+++;;:     
Echo                            ,''';;++'+;:       
Echo                              :'''++;:         
Echo                                '++:            
Echo.
Choice /C ABC /N /M "Choose"
Pause >Nul
cls
If %ErrorLevel% EQU 3 (
Copy /B .\Jars\1.5.2\minecraft.jar .\Minecraft\.minecraft\bin\ 
cls
Set AppData=.\
.\Minecraft\Minecraft.exe 
Exit
)
If %ErrorLevel% EQU 2 (
Copy /B .\Jars\1.7.3\minecraft.jar .\Minecraft\.minecraft\bin\ 
cls
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)
If %ErrorLevel% EQU 1 (
Copy /B .\Jars\1.2.6\minecraft.jar .\Minecraft\.minecraft\bin\
cls
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)

 

Link to comment
Share on other sites

Link to post
Share on other sites

Now, you talking about raw code? Or just the user-edited portion of a VS project?

Link to comment
Share on other sites

Link to post
Share on other sites

i call this program "SHAForce1".

 

Not quite 100 lines, little bit over but i already had made this a while back and thought it could be kinda cool. 

 

You supply 2 files, a file full of SHA1 hashes and a dictionary, All the hashes will then be testing and if there are any matches then they will be displayed.

 

total: 144 lines (had around 160 on the full project with annotations)

 

no comments: https://gist.github.com/h3adshotzz/cf37e94e7621cee1a46bf5327f785a4b

Full project: https://github.com/h3adshotzz/SHAForce1

Link to comment
Share on other sites

Link to post
Share on other sites

So I needed to come up with a way to clean up some whitespaces in CSV's that I was reading in.  I needed to both trim the ends of the strings, as well as convert multiple whitespaces into a single white space.  Took a stab at doing it with Regular Expressions and came up with

 

^\s*+([^\s])|(\s)\s*+|([^\s])\s*+$

And you would replace it with

\1\2\3

 

So it would take something like this:

Quote

<     Smith,    John                 H                  >

The <> brackets just signify where the string begins and end

 

And it would convert it into

Quote

<Smith, John H>

Yes, that many extra white spaces is unrealistic, but all it takes is one extra space to throw off my parser.

 

Sadly, as beautiful as it is, it does have some slight performance problems, and I ended up instead just first trimming the string, then using the regex:

\s+

And Replaced it with a single space.

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

This was something I didn't think I needed it until I started building computers for my friends. I wanted something easy for me to create junctions on fresh windows installations that had a boot drive (usually an ssd) and a storage drive (usually an hdd). I wanted to do it only for the Documents, Music, Pictures, Videos, and Downloads folders. So I created a batch file to have the user input the drive letter and the program creates the directories in the secondary hard drive and copies all the files from the boot drive to the storage drive. Then it deletes the folders from %UserProfile% and makes a junction to link the storage drive folders to the %UserProfile%.

 

@echo off
color 0a
:start
echo Type the drive letter of the storage drive.
SET /P Drive=
md %Drive%:\%UserName%
md %Drive%:\%UserName%\Documents
md %Drive%:\%UserName%\Music
md %Drive%:\%UserName%\Pictures
md %Drive%:\%UserName%\Videos
md %Drive%:\%UserName%\Downloads

copy %UserProfile%\Documents\*.* %Drive%:\%UserName%\Documents
copy %UserProfile%\Music\*.* %Drive%:\%UserName%\Music
copy %UserProfile%\Pictures\*.* %Drive%:\%UserName%\Pictures
copy %UserProfile%\Videos\*.* %Drive%:\%UserName%\Videos
copy %UserProfile%\Downloads\*.* %Drive%:\%UserName%\Downloads

rmdir /s /q %UserProfile%\Documents
rmdir /s /q %UserProfile%\Music
rmdir /s /q %UserProfile%\Pictures
rmdir /s /q %UserProfile%\Videos
rmdir /s /q %UserProfile%\Downloads

mklink /j "%UserProfile%\Documents" "%Drive%:\%UserName%\Documents"
mklink /j "%UserProfile%\Music" "%Drive%:\%UserName%\Music"
mklink /j "%UserProfile%\Pictures" "%Drive%:\%UserName%\Pictures"
mklink /j "%UserProfile%\Videos" "%Drive%:\%UserName%\Videos"
mklink /j "%UserProfile%\Downloads" "%Drive%:\%UserName%\Downloads


ECHO ALL DONE!

pause

Current Build

Successful Builds

Spoiler
Spoiler

 

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


×