Recent Entries 10
- snippet minor 112d agoPascal Bubble Sort ImplementationI would prefer a review of: - Efficiency - Standards - Different approaches Here's the code: ``` program bubbleSort; var toSort: array[1..5] of integer = (3, 25, 2, 69, 1); passChanges: boolean = true; counter, index, temp: integer; begin while passChanges do begin index := 1; passChanges := false; for index := 1 to length(toSort) - 1 do begin if (toSort[index] > toSort[index +1]) then Begin temp := toSort[index + 1]; toSort[index + 1] := toSort[index]; toSort[index] := temp; passChanges := true; end; end; end; for counter := 1 to length(toSort) do writeln(toSort[counter]); readln; end. ```
- pattern moderate 112d agoHuman-like mouse movementThe code will move the mouse from a start point (xs, ys) to finish point (xe, ye) like a human would. I'd like some help possibly shortening the code (by optimizing it) and making it more readable. Also, if you spot any mistakes I could have made while converting the Pascal code to C# code, please let me know! Original Pascal code: `procedure _humanWindMouse(xs, ys, xe, ye, gravity, wind, minWait, maxWait, targetArea: extended); var veloX, veloY, windX, windY, veloMag, dist, randomDist, lastDist, D: extended; lastX, lastY, MSP, W, TDist: integer; T: LongWord; sqrt2, sqrt3, sqrt5, maxStep, rCnc: extended; begin MSP := mouseSpeed; sqrt2 := sqrt(2); sqrt3 := sqrt(3); sqrt5 := sqrt(5); TDist := distance(round(xs), round(ys), round(xe), round(ye)); t := getSystemTime() + 10000; repeat if (getSystemTime() > t) then break; dist := hypot(xs - xe, ys - ye); wind := minE(wind, dist); if (dist 25) then D := 25; if (D = targetArea then begin windX := windX / sqrt3 + (random(round(wind) * 2 + 1) - wind) / sqrt5; windY := windY / sqrt3 + (random(round(wind) * 2 + 1) - wind) / sqrt5; end else begin windX := windX / sqrt2; windY := windY / sqrt2; end; veloX := veloX + windX; veloY := veloY + windY; veloX := veloX + gravity * (xe - xs) / dist; veloY := veloY + gravity * (ye - ys) / dist; if (hypot(veloX, veloY) > maxStep) then begin randomDist := maxStep / 2.0 + random(round(maxStep) div 2); veloMag := sqrt(veloX * veloX + veloY * veloY); veloX := (veloX / veloMag) * randomDist; veloY := (veloY / veloMag) * randomDist; end; lastX := round(xs); lastY := round(ys); xs := xs + veloX; ys := ys + veloY; if (lastX <> round(xs)) or (lastY <> round(ys)) then moveMouse(round(xs), round(ys)); W := (random((round(100 / MSP))) * 6); if (W round(xs)) or (round(ye) <> round(ys)) then moveMouse(round(xe), r
- pattern minor 112d agoAuto-click the sequenceThe following Pascal script needs a bit of context for its purpose to be understood. For those who don't give about purpose, feel free to skip ahead. Background A game I'm terribly fond of has a couple of levels which have nothing to do with the rest of the game. One of those is a puzzle: `Alpha Sector::virgilw::Brain` When you open the game, it looks like this: Turns out you need to connect all the 8 red dots to the emitter like this: All dots must be clicked in a specific sequence. If a dot is clicked and allowed to switch, it will light up if not already lit up. If it was already lit up it will darken again. The sequence to light up the 8th dot looks like this: `1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 8 ` The mathematically inclined can probably tell us what such a sequence is called, but it should be obvious to the rest of us that the first 7 characters are always the same and only the 8th varies. Now, there's an achievement for lighting up all 8 dots within 60 seconds. Since it's already 128 clicks for lighting up the 8th one alone, I decided to automate the process using SCAR Divi (manual), an environment running Pascal scripts which allows you to automate keyboard presses and mouse movements. Code The resulting code is ugly, but I was mainly looking for fast code. This means it may not be up to par with Pascal-style and I took a short-cut wherever I thought it would influence the execution speed. I'm looking for improvements on readability wherever this does not hurt the performance in any way. I've written a fair bit of Pascal but I've always been a little fuzzy on what did and didn't impact performance. General tips about this are welcome. The most used procedure is `MnC(x, y)`, short for Move'n'Click. It moves the mouse to whatever coord
- pattern minor 112d agoBinary and linear search methods for a number-guessing gameThis is a code written is Pascal (Delphi). It asks the user to think of a number between `min_` and `max_` and then guesses the number using either a Binary or a Linear method. ``` program BandLSearch; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; var min_, max_: integer; // set the max and min to check between the two (inclusive) BinorLin: string; // Get user input as to which method they wish to use procedure Linear(); { This uses a linear search technique to guess the number. It will ask min_ then min_ +1 etc up to max_. e.g. 1, 2, 3, ... , 99, 100 } var input: string; count: integer; // For the foor loop begin for count := min_ to max_ do // loop from min to max and ask if the number is corect, one by one begin write('Is your number ',count,'? Y or N? > '); readln(input); if (input = 'Y') or (input = 'y') then begin writeln('Found your number, it is ',count); readln; // Prevent the code ending without being able to read the output. break end else begin if count = max_ then //If they have reached max and not said yes, they are lying begin writeln('You have cheated'); readln; end; end; end; end; procedure Binary(); { This uses a linear search technique to guess the number It will ask (min_ + max_)/2 and the user says too high or too low. Depending on the response, it will set either min_ or max_ to the guessed number Eventually it narrows down, eg: 50, 75, 62, 68, 65, 63, 64 L H L H H L C } var input: string; guess, preGuess: integer; // For the current computer guess goesTaken : integer; // To monitor the guesses needed end_: integer; // Will increase for each guess that ma
- pattern minor 112d agoGenerating PositionI'm written the following code to calculate the position of a motor during each timestep, the result of which will be compared with feedback from a quadrature encoder and subjected to a PID algorithm. The trajectory will follow a trapezoidal profile. i.e. Accelerate to a maximum velocity, coast and then decelerate to the target position: ``` program ideone; VAR Pos : Real; Vel : Real; Acc : Real; Demand : Real; Max_Vel : Real; AccDist : Real; DecelPoint : Real; Error : Real; begin Pos:=0; Vel:=0; Acc:=5; Demand:=150; Max_Vel:=10; AccDist := (Max_vel/Acc * Max_vel) / 2; DecelPoint := Demand - AccDist; Writeln('AccelDist ',AccDist:5:2); Writeln('DecelPoint ',DecelPoint:5:2); Writeln('ACCEL'); While Vel <> Max_vel Do Begin Pos := Pos + Vel + Acc/2; Vel := Vel + Acc; If Vel >= Max_Vel Then Begin Vel := Max_Vel; Pos := AccDist End; Writeln('Position:',Pos:5:2); End; Writeln('FLAT'); While Pos 0 Do Begin If Error > 0 Then Begin Pos := DecelPoint; Error := 0; End; Pos := Pos + Vel - Acc/2; Vel := Vel - Acc; If Vel <= 0 Then Pos := Demand; Writeln('Position:',Pos:5:2); End; end. ``` How can the accuracy of the algorithm be improved?
- pattern minor 112d agoAdding and subtracting Matrices based on condition``` procedure E(n, m: integer; A, B: tMatrix; var C: tMatrix); var i, j: integer; begin for i:=1 to n do for j:=1 to m do begin if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j]; end; end; ``` Input: three matrix. Output: new matrix which created by addition or subtraction of two elements of two matrix depending on conditions
- pattern minor 112d agoFunction to split textThe following pascal function (compiled with Delphi) will split strings. It works perfectly, but how to improve the code? For example, to avoid using the repeat-until loop. ``` type TSarray = array of string; function Split(Texto, Delimitador: string): TSarray; var o: integer; PosDel: integer; Aux: string; begin o := 0; Aux := Texto; SetLength(Result, Length(Aux)); repeat PosDel := Pos(Delimitador, Aux) - 1; if PosDel = -1 then begin Result[o] := Aux; break; end; Result[o] := copy(Aux, 1, PosDel); delete(Aux, 1, PosDel + Length(Delimitador)); inc(o); until Aux = ''; end; ``` Example: ``` var texto,deli:string; all_array:TSarray; begin deli := 'test'; texto := deli+'hi world 1'+deli+'hi world 2'+deli; end; all_array := Split(texto,deli); ShowMessage(all_array[1]); ShowMessage(all_array[2]); end; ``` My plan is to use no classes, only the "uses" default What alternatives do I have to repeat-until?
- pattern minor 112d agoSync eye movements with external eventsThis solution was used to synchronize events between two applications: An eye tracking software, Python, and a stimulus control software, object Free Pascal/Delphi. It avoided a rewrite of the stimulus control app from ObjFPC/Delphi to Python. Pupil Eye Tracker sends some info via ZeroMQ to somewhere (I get used to call "net stack" to this place, please do not laugh). Indeed, a lot of info is sent, so they provided a way to filter this events; I have done this in a way that only timestamps should be sent. This is a dummy stand alone broadcast: `""" Broadcast dummy Pupil timestamps """ import zmq #from ctypes import create_string_buffer from time import sleep def test_msg(): test_msg = "Pupil\ntimestamp:1389761135.56\n" return test_msg def main(): context = zmq.Context() socket = context.socket(zmq.PUB) #address = create_string_buffer("tcp://127.0.0.1:5020",512) address = "tcp://127.0.0.1:5020" try: #socket.bind(address.value) socket.bind(address) except zmq.ZMQError: print "Could not set Socket." for i in range(120): socket.send( test_msg() ) sleep(0.5) context.destroy() if __name__ == '__main__': main() ` A timestamp is the basic unit to synchronize frames, eye-gaze, events, basically all the stuff. Initially, they used the Python `now()` function to generate them. The current version can use the hardware of some cameras as well: "Hardware time-stamping: Running Pupil Pro with Linux now uses hardware timestamps taken by the camera hardware at the start of exposure". Since they are using a Publisher-Subscriber protocol, Pupil Team suggested a way to receive this info. So, all I have done was to call the 'receive' client from inside the stimulus control app using a single thread for each call. Of course, it requires a broadcast server, in my case, during the real time Pupil Capture Server broadcast. `unit client; {$mode objfpc}{$H+} interface uses Classes ,
- pattern minor 112d agoEnhancing speed of looping cycle using FreepascalI use Lazarus 1.2.4 and Freepascal 2.6.4. I have created a program that reads a disk in buffers of 64Kb (tried various buffer sizes) using a repeat...until loop. Each buffer is hashed using the SHA1 unit, specifically, SHA1Init, SHA1Update and SHA1Final. The trouble is, is that although it works and the hashes always match that computed by other tools that do the same job, my program is not as fast. On a specific workstation with an 80Gb disk attached, it reads and hashes at about 1.8Gb per minute, and this is as a result of some enhanced compiler directives (and using specific optimisations offered by the Lazarus\FPC compiler). Before those tweaks, it was just 1.22Gb p\min as an average. The other tools do it at about 2.5Gb+ a minute (around 45Mb a second) and some are faster than that. If I remove the hashing element and just do the disk reading, it reads at about 4Gb per minute, so I am fairly sure my loop structure is actually fairly quick. So I'm almost certain the bottleneck is the hashing aspect and this has been discussed at the Lazarus forum, here where it has been suggested that maybe the library needs to be improved a little for better speed. One poster suggested I re-write the three functions in assembly but I am not that good. There is a related post HERE regarding SHA256, where the gentlemen concerned experienced similar issues, though with a different language. His implementation was very similar to mine - Init, Update, Final. One suggestion was to use a buffer of 16Mb in that post. I have tried 4Kb, 8Kb, 64Kb, 256Kb, 512Kb and 1Mb. I haven't gone to 16Mb or anywhere near that - might that prove to be worthwhile? I read that once you go above about 1Mb programs usually go backward? Is there an obvious way to improve speed? I have included only the relevant parts in the hope it will make the task easier to read. ``` // Main parts of my code responsible for loop. // The SHA1 functions from the SHA1 Freepascal unit follow hSelectedDisk := Crea
- pattern minor 112d agoDrawing and Painting a Menu ComponentI have produced a working menu component for a project I'm working on, but would like to reduce the amount of code used and improve the methods - especially in the Paint implementation - still further, I feel like the function I've used and the way I've passed the variables to it is a bit 'hacky' - IOW, I bodged it. What methods could I use to increase the amount of encapsulation used in the drawing routine so I'm not defining variables in the Paint routine? The `y2` variable in particular is irritating. These are my drawing function and paint routine: ``` // Rectangle drawing function Function DrawRect(cv : TCanvas; x1, y1, x2, y2, chR, clR, i : integer; txts : AnsiString; Lrect : TRect) : TRect; begin with cv do begin // Test against Rect variables to set colour if (chR = i) and (clR = -1) then Brush.color := stateColor[bttn_on] else if (chR = i) and (clR = i) then Brush.color := stateColor[bttn_dwn] else Brush.color := stateColor[bttn_off]; // Define Link Rectangle Lrect := Rect(x1, y1, x2, y2*(i+1)); // Draw Rectangle Rectangle(Lrect); // Add text TextRect(Lrect, x1+5, y1+5, txts); // Return co-ordinates of drawn rectangle as function result result := Lrect; end; end; // Canvas painting procedure TOC_MenuPanel.Paint; var y1, x2, y2, count : Integer; begin inherited Paint; // Set length of array SetLength(MenuRects, fLinesText.Count); // Define Y1,Y2 x2 := Width - Width div 20; y1 := Width div 20; with Canvas do begin // Draw outerRectangle outside of For loop Brush.color := clMenu; Rectangle(0, 0, Width, Height); // Loop for drawing menu items if fLinesText.Count = 0 then exit else for count := 0 to fLinesText.Count - 1 do begin // Define Y2 y2 := TextHeight(fLinesText.strings[count])*2; // Cast rectangle draw function results to array for Mouse actions & draw rectangle MenuRects[count] := DrawRect(Canvas, 10, y1, x2, y2, cho