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

The under 100 line challenge!

Recommended Posts

4 hours ago, penia said:

+remainder[7] +remainder[6] +remainder[5] +remainder[4] +remainder[3] +remainder[2] +remainder[1] +remainder[0])

you could put this in another for loop:

for (count = remainder.length; count < 0; count--) {
  System.out.println(remainder[count])
}

(don't know how to get the length of an array, but I hope you get it)


 "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 post
Share on other sites
class Fibonacci
    {
        public int a = 1;
        public int b = 1;
        public int c = 0;

        public IEnumerator<int> GetEnumerator()
        {
            while (true)
            {
                this.c = this.a + this.b;
                this.a = this.b;
                this.b = this.c;

                yield return this.a;
            }
        }

A Fibonacci iterator in C#. Should probably be modified to allow for only producing fibonacci numbers up to n, or only producing n fibonacci numbers.

EDIT:: Here's the updated version (Please note some backing fields can be removed):
 

    public class Fibonacci
    {
        // Backing fields
        private ulong _a;
        private ulong _b;
        private bool _mode; // True for up to n, false for maximum of n
        private ulong _num;
        private ulong _count;

        // Properties
        public bool Mode { get { return _mode; } set { _mode = value; } }
        public ulong A { get { return _a; } set { _a = value; } }
        public ulong B { get { return _b; } set { _b = value; } }
        public ulong Number { get { return _num; } set { _num = value; } }
        public ulong Count { get { return _count; } }

        // Constructors
        public Fibonacci()
        {
            _a = 0;
            _b = 1;
            _mode = true;
            _num = ulong.MaxValue;
        }

        public Fibonacci(ulong a, ulong b, ulong num, bool mode)
        {
            _a = a;
            _b = b;
            _mode = mode;
            _num = num;
        }

        public Fibonacci(ulong num)
        {
            _a = 0;
            _b = 1;
            _mode = true;
            _num = num;
        }

        // Iterators
        public IEnumerator<ulong> GetEnumerator()
        {
            if (_mode)
                return UpTo();

            else
                return LessThan();
        }

        // Methods
        public IEnumerator<ulong> UpTo()
        {
            ulong c = 0;
            _count = 2;

            while ((_a < _num) && (_b < _num))
            {
                c = _a + _b;
                _a = _b;
                _b = c;

                yield return _a;
                _count++;
            }

        }

        public IEnumerator<ulong> LessThan()
        {
            ulong c = 0;
            _count = 2;

            while (_count < _num)
            {
                c = _a + _b;
                _a = _b;
                _b = c;

                yield return _a;
                _count++;
            }
        }
    }


Fits in 93 lines.


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites

Using AHK, simple script that let you alternate between the last 2 windows (visible) using the key [ESC] (as alt tab but faster since it require only 1 key)

Esc::
hwnd := WinActive("A")
Loop
{
	hwnd := DllCall("GetWindow",uint,hwnd,int,2) ; 2 = GW_HWNDNEXT
	SetFormat,integer,hex
	hwnd += 0
	SetFormat,integer,d
	if (DllCall("IsWindowVisible",uint,hwnd) = 1)
		break
}
WinActivate,ahk_id %hwnd%
return

 


 

Link to post
Share on other sites

This is the final form of my first ever Windows exe 

 

 

^!NumpadEnter::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput shutdown /r /fw /t 0 {enter}
 Return

^!NumpadSub::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput bcdedit /set {current} safeboot minimal {enter}
  Sendinput shutdown /r /t 0 {enter}
 Return

^!NumpadAdd::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput bcdedit /deletevalue safeboot {enter}
  Sendinput shutdown /r /t 0 {enter}
 Return

^+`::
  Run c:\\windows\system32\control.exe
 Return

^SPACE::  
  Winset, Alwaysontop, , A
 Return

I run it with Task Scheduler from the System32 folder 


 With all the Trolls, Try Hards, Noobs and Weirdos around here you'd think i'd find SOMEWHERE to fit in!

Link to post
Share on other sites

Probably pointless, but could useful depending on the individual who is interested in IL programming and this snippet is about 140 lines of code. I created it on a whim.

 

The purpose of this snippet is basically to emit Brainf*ck programming language into IL during runtime in C#:

 

using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.IO;

namespace BFJIT
{
    public unsafe class BFJIT
    {
        public static void ZeroOutMemory(byte* ptr, int size)
        {
            for (int I = 0; I < size; I++)
                ptr[I] = 0;
        }
        public delegate IntPtr BrainFkCompile();
        public BrainFkCompile Compile(string code)
        {
            var WhileBeginMarkStack = new Stack<Label>();
            var WhileEndMarkStack = new Stack<Label>();
            var reader = new StringReader(code);

            var method = new DynamicMethod($"BrainFk{Guid.NewGuid().ToString().Replace("-", "_")}", typeof(IntPtr), null);
            var il = method.GetILGenerator();
            // Set the locals
            il.DeclareLocal(typeof(byte*));
            il.DeclareLocal(typeof(IntPtr));
            // Allocate pointer
            il.Emit(OpCodes.Ldc_I4, 1048576); // 1 MB Memory
            il.EmitCall(OpCodes.Call, typeof(Marshal).GetMethod("AllocHGlobal", new Type[] { typeof(int) }), null);
            il.Emit(OpCodes.Stloc_1);
            il.Emit(OpCodes.Ldloca_S, 1);
            il.EmitCall(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer"), null);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ldc_I4, 1048576); // 1 MB Memory
            il.EmitCall(OpCodes.Call, typeof(BFJIT).GetMethod("ZeroOutMemory"), null);
            int currentCharacter = -1;
            do
            {
                currentCharacter = reader.Read();
                switch ((char)currentCharacter)
                {
                    case '>':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldc_I4_1);
                            il.Emit(OpCodes.Add);
                            il.Emit(OpCodes.Stloc_0);
                            break;
                        }
                    case '<':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldc_I4_1);
                            il.Emit(OpCodes.Sub);
                            il.Emit(OpCodes.Stloc_0);
                            break;
                        }
                    case '+':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldind_U1);
                            int increment = 1;
                            while (reader.Peek() == '+')
                            {
                                ++increment;
                                reader.Read();
                            }
                            il.Emit(OpCodes.Ldc_I4, increment);
                            il.Emit(OpCodes.Add);
                            il.Emit(OpCodes.Conv_U1);
                            il.Emit(OpCodes.Stind_I1);
                            break;
                        }
                    case '-':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldind_U1);
                            int decrement = 1;
                            while (reader.Peek() == '-')
                            {
                                ++decrement;
                                reader.Read();
                            }
                            il.Emit(OpCodes.Ldc_I4, decrement);
                            il.Emit(OpCodes.Sub);
                            il.Emit(OpCodes.Conv_U1);
                            il.Emit(OpCodes.Stind_I1);
                            break;
                        }
                    case '.':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldind_U1);
                            il.EmitCall(OpCodes.Call, typeof(Console).GetMethod("Write", new[] { typeof(byte) }), null);
                            break;
                        }
                    case '[':
                        {
                            Label begin = il.DefineLabel();
                            Label end = il.DefineLabel();
                            il.Emit(OpCodes.Br, end);
                            il.MarkLabel(begin);
                            WhileBeginMarkStack.Push(begin);
                            WhileEndMarkStack.Push(end);
                            break;
                        }
                    case ']':
                        {
                            il.MarkLabel(WhileEndMarkStack.Pop());
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldind_U1);
                            il.Emit(OpCodes.Brtrue, WhileBeginMarkStack.Pop());
                            break;
                        }
                    default:
                        continue;
                }
            } while (currentCharacter > -1);
            il.Emit(OpCodes.Ldloc_1);
            il.Emit(OpCodes.Ret);
            return (BrainFkCompile)method.CreateDelegate(typeof(BrainFkCompile));
        }

        static unsafe void Main(string[] args)
        {
            var jitter = new BFJIT();
            var func = jitter.Compile("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.");
            Console.WriteLine("Brainfk Compiled");
            var ptr = func();
            Console.WriteLine();
            Console.WriteLine("Program Terminated.");
            Marshal.FreeHGlobal(ptr);
            Console.ReadLine();
        }
    }
}

 

Link to post
Share on other sites
45 minutes ago, FreeDev said:

Probably pointless, but could useful depending on the individual who is interested in IL programming and this snippet is about 140 lines of code. I created it on a whim.

That's interesting. My implementation is a little different. I do a a two pass compilation that spits out an AST, then I walk the AST. Yours is probably faster (maybe, it's hard to tell with reflection), but mine includes a WPF "IDE" which shows the state of memory and allows breakpoint debugging. 


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites

That would work pretty well, I am actually curious on how much faster it would be to try and have Brainf*ck emitted as native assembly with the help of LLVM JIT, guess that would be the next challenge for me.

Link to post
Share on other sites
1 minute ago, FreeDev said:

That would work pretty well, I am actually curious on how much faster it would be to try and have Brainf*ck emitted as native assembly with the help of LLVM JIT, guess that would be the next challenge for me.

I'm more interested in adding features to BF than making it faster, so for me the AST is the way to go. Adding subroutines is a big one that I'm thinking about now. I can't decide if I want to do it with a stack (functions calls with arguments), a stack (manually push arguments to stack), or to change the AST into a weird combined AST/CALL graph structure.


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites

You could do it similarly to how IL does it, you basically can load the parameters/fields/variables onto the stack and call the function which would pop the stack for each parameter and then return the value (if it's non-void) onto the stack. I think it's fairly sensible approach.

Link to post
Share on other sites
12 minutes ago, FreeDev said:

You could do it similarly to how IL does it, you basically can load the parameters/fields/variables onto the stack and call the function which would pop the stack for each parameter and then return the value (if it's non-void) onto the stack. I think it's fairly sensible approach.

As an aside, I think that the pattern that the "original recipe" C# compiler and Roslyn uses is that void methods return a void object (the CTS BCL has a type System.Void), and then calls a POP instruction, which throws away the void object.

Btw, I see you're new. Welcome to the forum :) One of the things we do is quote someone when replying to them. (highlight text in their reply and a quote button pops up). This gives them a notification that you've responded. Had I not been subscribed to this thread I would have never known that you replied.


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites
11 minutes ago, straight_stewie said:

As an aside, I think that the pattern that the "original recipe" C# compiler and Roslyn uses is that void methods return a void object (the CTS BCL has a type System.Void), and then calls a POP instruction, which throws away the void object.

Btw, I see you're new. Welcome to the forum :) One of the things we do is quote someone when replying to them. (highlight text in their reply and a quote button pops up). This gives them a notification that you've responded. Had I not been subscribed to this thread I would have never known that you replied.

Thank you! And I don't know what CLR does that when loading void object onto the stack and popping it, I've checked up on Mono source code and discovered that they didn't even bother with the loading onto stack for Void structure in C# and a lot of people seems to mention that System.Void is only for reflection purpose.

 

And yep, I've just joined up recently and pretty much searching for a new community to discuss programming basically. Thank you for the warm welcome. :)

Link to post
Share on other sites
28 minutes ago, FreeDev said:

Thank you! And I don't know what CLR does that when loading void object onto the stack and popping it, I've checked up on Mono source code and discovered that they didn't even bother with the loading onto stack for Void structure in C# and a lot of people seems to mention that System.Void is only for reflection purpose.

I just checked. In release mode Roslyn doesn't have void methods return anything. In Debug mode it does.


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites

That is really interesting, I never have heard of it being done before. That is something new to learn about today. Thank you. :D

Link to post
Share on other sites
 
Disp "Enter x1 for V1:"
Input A
Disp "Enter x2 for V1:"
Input B
Disp "Enter x3 for V1:"
Input C
Disp "Enter x1 for V2:"
Input D
Disp "Enter x2 for V2:"
Input E
Disp "Enter x3 for V2:"
Input F
ClrHome
(B*F)-(C*E)->G
(C*D)-(A*F)->H
(A*E)-(B*D)->I
Disp G,H,I

Program for calculator TI-83Plus to calculate the cross-product of two vectors 


for(var i = 0; i<= 1/0; i++) {
	alert("Look, i am like while(true){}");
}

1/0 != Error; 1/0 == ∞

Link to post
Share on other sites

Geoblocking EU users (so you won't have to bother about the GDPR) in five lines of PHP code:

$disallowed_countries = ["BE", "BG", "CZ", "DK", "DE", "EE", "IE", "EL", "ES", "FR", "HR", "IT", "CY", "LV", "LT", "LU", "HU", "MT", "NL", "AT", "PL", "PT", "RO", "SI", "SK", "FI", "SE", "UK"];
$ip = $_SERVER["REMOTE_ADDR"];
if (in_array(geoip_country_code_by_name($ip), $disallowed_countries)) {
    die("Your country does not want you to be here.");
}

 


Write in C.

Link to post
Share on other sites
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PokeballBot
{
    public partial class Form1 : Form
    {
        bool running = false;

        public Form1() => InitializeComponent();

        void button1_Click(object sender, EventArgs e)
        {
            running = !running;
            button1.Text = running ? "Stop" : "Start";
        }

        void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (running)
            {
                Bitmap screenshot = ScreenshotPokeball;
                Point ball = GetLoc(Color.FromArgb(201, 60, 76), screenshot);
                Point pika = GetLoc(Color.FromArgb(248, 208, 80), screenshot);
                pictureBox1.Image = screenshot;
                if (ball.X != -1 && ball.Y != -1 && pika.X != -1 && pika.Y != -1)
                    if (pika.X < ball.X)
                        KeyboardPress(68, 7);
                    else if (pika.Y > ball.Y)
                        KeyboardPress(87, 26);
                    else if (pika.X > ball.X)
                        KeyboardPress(65, 4);
                    else if (pika.Y < ball.Y)
                        KeyboardPress(83, 22);
            }
            Invalidate(false);
            Update();
        }

        Point GetLoc(Color c, Bitmap croppedGameScreen)
        {
            for (int x = 0; x < croppedGameScreen.Width; x++)
                for (int y = 0; y < croppedGameScreen.Height; y++)
                    if (AreAboutEqual(c, croppedGameScreen.GetPixel(x, y)))
                        return new Point(x / 16, y / 16);
            return new Point(-1, -1);
        }

        bool AreAboutEqual(Color f, Color s) => f.R - 10 < s.R && f.R + 10 > s.R && f.G - 10 < s.G && f.G + 10 > s.G && f.B - 10 < s.B && f.B + 10 > s.B;

        static Bitmap ScreenshotPokeball
        {
            get
            {
                Rect rect = new Rect();
                GetWindowRect(Process.GetProcessesByName("Pokeball").ToArray()[0].MainWindowHandle, ref rect);
                Bitmap bmp = new Bitmap(160, 160, PixelFormat.Format24bppRgb);
                Graphics.FromImage(bmp).CopyFromScreen(rect.left + 19, rect.top + 42, 0, 0, new Size(160, 160), CopyPixelOperation.SourceCopy);
                return bmp;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        struct Rect
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        static void KeyboardPress(byte vk, byte sc)
        {
            keybd_event(vk, sc, 0, 0);
            keybd_event(vk, sc, 2, 0);
        }

        [DllImport("user32.dll")]
        static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
    }
}

Combined with some some windows forms its a pretty nice bot for this game.

PokeballBot.exe


~chrissx aka. that crazy german dude

A bad website

Link to post
Share on other sites

Recently I had a situation where one of our clients was typing a message our server needed to handle.  While processing the message through a web service we use, we kept getting an improper XML format error.  Unfortunately the error was super generic, and didn't provide any information as to where the problem actually was.  Made sure all special characters were properly escaped or removed, there were no hidden character, even made sure there were no new line characters, although I knew that shouldn't be the issue. 

 

Finally I noticed two words in the message:  weren't and don't, and that the apostrophe didn't look right.

What it ended up being was that for some reason the client's keyboard was not setup to output the ordinary single quote, instead it used a different version of it that required unicode.  The message is being transmitted as ASCII (it's not critical, but it avoid a lot of other problems).

 

Now handling that one character was easy enough;  I just added the code to replace it with a standard single quote, but it did bring to my attention that there were other characters that could prove problematic as well, and I wanted to find a simple and elegant way to handle them.

 

Regex to the rescue, per usual:

This little gem ended up doing pretty much everything I needed

[^ -~]

This will select any character that is not a printable ascii character, and you can then replace it with space, or empty string, or whatever you want.

 

I actually wasn't sure if the character ranges worked this way, but I had a hunch so I decided to test it.  Previously I had assumed that when you specified a range, it was only for alphanumeric characters, since they have a defined order.  So you could only do a-z, b-j,0-9,4-5, etc

It turns out the way the ranges actually works is by comparing them as their respective ASCII/Unicode Integer values, similar to how in C/C++ code, you can test if a number is an integer by comparing it like so

int isdigit(char c)
{
    if((c >= '0' && c <= '9')
    {
         return 1;
    }
    else
    {
         return 0;
    }                       
}

I know I'm not the first person to discover this, but I've never seen someone mention that it works this way, so I thought it worth mentioning.

 

Link to post
Share on other sites

 

52 minutes ago, JacobFW said:

Regex to the rescue, per usual:

not to sound critical given I have 0 idea what your codebase is like, but it sounds like you are missing some cross layer validation (i.e. a system on the client side that does the data creation so that it's always sent with the right encoding/format/schema etc, and can let the user know something is incorrect before sending the data over the wire).

I know regex fixed it this time, but that seems more like a bandaid fix than a robust solution. not having a standardized client/server interface might cause more headache down the road.

 

Again, no idea who your users are or what your code is like and I have no idea what domain context you might have, just thought i'd throw my probably unwanted 2 cents in.


Gaming build:

CPU: i7-7700k (5.0ghz, 1.312v)

GPU(s): Asus Strix 1080ti OC (~2063mhz)

Memory: 32GB (4x8) DDR4 G.Skill TridentZ RGB 3000mhz

Motherboard: Asus Prime z270-AR

PSU: Seasonic Prime Titanium 850W

Cooler: Custom water loop (420mm rad + 360mm rad)

Case: Be quiet! Dark base pro 900 (silver)
Primary storage: Samsung 960 evo m.2 SSD (500gb)

Secondary storage: Samsung 850 evo SSD (250gb)

 

Server build:

OS: Ubuntu server 16.04 LTS (though will probably upgrade to 17.04 for better ryzen support)

CPU: Ryzen R7 1700x

Memory: Ballistix Sport LT 16GB

Motherboard: Asrock B350 m4 pro

PSU: Corsair CX550M

Cooler: Cooler master hyper 212 evo

Storage: 2TB WD Red x1, 128gb OCZ SSD for OS

Case: HAF 932 adv

 

Link to post
Share on other sites
35 minutes ago, reniat said:

 

not to sound critical given I have 0 idea what your codebase is like, but it sounds like you are missing some cross layer validation (i.e. a system on the client side that does the data creation so that it's always sent with the right encoding/format/schema etc, and can let the user know something is incorrect before sending the data over the wire).

I know regex fixed it this time, but that seems more like a bandaid fix than a robust solution. not having a standardized client/server interface might cause more headache down the road.

 

Again, no idea who your users are or what your code is like and I have no idea what domain context you might have, just thought i'd throw my probably unwanted 2 cents in.

Fair point.  A lot of it however is outside of my control, and to my knowledge most of the formal solutions require integrating the code everywhere it's needed.

Link to post
Share on other sites
17 hours ago, JacobFW said:

Fair point.  A lot of it however is outside of my control, and to my knowledge most of the formal solutions require integrating the code everywhere it's needed.

Just make sure at the very least you are sanitizing your input if security is a concern. Theres a big potential for code injection depending on what consumes the data being passed.


Gaming build:

CPU: i7-7700k (5.0ghz, 1.312v)

GPU(s): Asus Strix 1080ti OC (~2063mhz)

Memory: 32GB (4x8) DDR4 G.Skill TridentZ RGB 3000mhz

Motherboard: Asus Prime z270-AR

PSU: Seasonic Prime Titanium 850W

Cooler: Custom water loop (420mm rad + 360mm rad)

Case: Be quiet! Dark base pro 900 (silver)
Primary storage: Samsung 960 evo m.2 SSD (500gb)

Secondary storage: Samsung 850 evo SSD (250gb)

 

Server build:

OS: Ubuntu server 16.04 LTS (though will probably upgrade to 17.04 for better ryzen support)

CPU: Ryzen R7 1700x

Memory: Ballistix Sport LT 16GB

Motherboard: Asrock B350 m4 pro

PSU: Corsair CX550M

Cooler: Cooler master hyper 212 evo

Storage: 2TB WD Red x1, 128gb OCZ SSD for OS

Case: HAF 932 adv

 

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


×