A collection of small ahk functions

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
LinearSpoon
Posts: 156
Joined: 29 Sep 2013, 22:55

Re: A collection of small ahk functions

29 Jul 2014, 14:26

toralf wrote:What is the advantage of bitwise-and and bitwise-exclusiv-or over the tenary operator?

Code: Select all

min(x, y){
  Return x < y ? x : y
}
Same should apply for Maximum (x < y ? y : x).
It avoids branching code. A modern cpu will try to guess which way the branch will go and start executing code before it actually knows the result of the ternary. The problem is that if it guesses wrong, it has to back up and undo everything it did, which is very expensive relative to the cost of a few bitwise operations.
More info: http://en.wikipedia.org/wiki/Branch_predictor

That said, the disadvantage is that it's difficult to understand what the purpose of the function is at a glance, and it won't work on floating point numbers. There is also the issue of AHK being an interpreted language, and the overhead of the expression parser might actually make jNizM's function slower than a simple ternary.

Bonus: min and max functions that I use

Code: Select all

Msgbox % max(12, 13, 29, 99)
temp := [12, 13, 29, 99]
Msgbox % min(temp*) ;for use on arrays

max(max, n*)
{
  for k,v in n
    if (v > max)
      max := v
  return max
}

min(min, n*)
{
  for k,v in n
    if (v < min)
      min := v
  return min
}
toralf
Posts: 868
Joined: 27 Apr 2014, 21:08
Location: Germany

Re: A collection of small ahk functions

29 Jul 2014, 14:41

i tried to test the speed of the 3 functions.
The tenary operator was the fastes.
The bitwise ^& took twice as long.
The for loop took 3 times as long. But at least has the option to work with more then 2 parameters.
ciao
toralf
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

29 Jul 2014, 14:46

[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: A collection of small ahk functions

30 Jul 2014, 00:45

It avoids branching code. A modern cpu will try to guess which way the branch will go and start executing code before it actually knows the result of the ternary. The problem is that if it guesses wrong, it has to back up and undo everything it did, which is very expensive relative to the cost of a few bitwise operations.
More info: http://en.wikipedia.org/wiki/Branch_predictor

That said, the disadvantage is that it's difficult to understand what the purpose of the function is at a glance, and it won't work on floating point numbers. There is also the issue of AHK being an interpreted language, and the overhead of the expression parser might actually make jNizM's function slower than a simple ternary.
I think the call of the UDF has more instructions than the whole ternary construct there.
Recommends AHK Studio
julka
Posts: 14
Joined: 06 Feb 2014, 02:31

Re: A collection of small ahk functions

01 Aug 2014, 07:10

msgbox with custom buttons.

Code: Select all

/*
Usual MsgBox, Text or MsgBox [, Options, Title, Text, Timeout]
with 3 extra parameters - custom button texts

If you pass text for a button, options that determine the buttons are ignored

Returns the text of the button pressed by the user
    or the word Timeout followed by the seconds which were given
	if user was too slow. Your problems if you name your buttons so.
	Seriusly.

Important! If you want to have custom text for 1 button,
	you have to pass text for all buttons
	
Important! You cannot have label named ¥Ω¦§ɵǕɶʱ͏ in your script.
	How did you manage tho...

msgbox % julka_msgbox()
msgbox % "You've chosen " julka_msgbox("I like trains.",,,,"Ok...","Woot?")
msgbox % "You've chosen " julka_msgbox(0x4,"Test","This is a test.")
msgbox % "You've chosen " julka_msgbox(0x3,"Train","While this is a train.",,"True","False")
msgbox % julka_msgbox("",,"You have 1 second to press this useful button.",1,"Congrats!")
*/

julka_msgbox(Options:=0,Title:="",Text:="",Timeout:="",B1:="",B2:="",B3:="")
{
	static s_Options,s_Title,s_Text,s_TimeOut,s_B1,s_B2,s_B3

	s_Options:=(Text!="") ? Options : 0
	s_Title:=(Title!="") ? Title : A_ScriptName
	s_Text:=(Text!="") ? Text : Options ? Options : "Press OK to continue"
	s_TimeOut:=Timeout
	if B1, s_B1:=B1
		if B2, s_B2:=B2
			if B3, s_B3:=B3
				s_Options:=(s_Options&0xFFFFE9)|0x3
			else s_Options:=(s_Options&0xFFFFE9)|0x4
		else s_Options:=(s_Options&0xFFFFE9)
	else
	{
		t:=s_Options&6
		s_Options:=s_Options&0xFFFFE9
		if (t=0)
			s_B1:="OK"
		else if (t=1)
			s_B1:="OK",s_B2:="Cancel",s_Options:=s_Options|0x4	
		else if (t=2)
			s_B1:="Abort",s_B2:="Retry",s_B3:="Ignore",s_Options|=0x3	
		else if (t=3)
			 s_B1:="Yes",s_B2:="No",s_B3:="Cancel",s_Options|=0x3
		else if (t=4)
			s_B1:="Yes",s_B2:="No",s_Options|=0x4
		else if (t=5)
			s_B1:="Retry",s_B2:="Cancel",s_Options|=0x4
		else 
			s_B1:="Cancel",s_B2:="Try Again",s_B3:="Continue",s_Options|=0x3	
	}
	SetTimer, ¥Ω¦§ɵǕɶʱ͏, 15
	msgbox % s_Options ,% s_Title,% s_Text,% s_TimeOut
	IfMsgBox, OK
		return s_B1
	IfMsgBox, YES 
		return s_B1
	IfMsgBox, NO
		return s_B2	
	ifMsgbox, Cancel
		return s_B3
	return "Timeout" Timeout
	
	¥Ω¦§ɵǕɶʱ͏:
	{	
		IfWinNotExist, % s_Title
			return  ; Keep waiting.
		SetTimer, ¥Ω¦§ɵǕɶʱ͏, off
		WinActivate
		ControlSetText, Button1, % "&" s_B1
		if (s_Options&6)
			ControlSetText, Button2, % "&" s_B2
		if (s_Options&6=3)
			ControlSetText, Button3, % "&" s_B3	
		return
	}
}
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: A collection of small ahk functions

01 Aug 2014, 08:07

jNizM wrote:I just found it here and shared it:
Bit Twiddling Hacks

more here:
- Low Level Bit Hacks You Absolutely Must Know
- Bit Twiddling Hacks
- Bit-Twiddling
Cool, thanks jNizM
User avatar
jballi
Posts: 724
Joined: 29 Sep 2013, 17:34

Re: A collection of small ahk functions

01 Aug 2014, 18:17

Coco wrote:
jNizM wrote:I just found it here and shared it:
Bit Twiddling Hacks

more here:
- Low Level Bit Hacks You Absolutely Must Know
- Bit Twiddling Hacks
- Bit-Twiddling
Cool, thanks jNizM
Yes, thanks jNizM for the links. I went through the tricks/hacks very briefly. Most were over my head and/or I have no current use for, a few where just replacements to basic arithmetic operations, but a few were very clever. The hacks for counting the number of bits set were simple but elegant and efficient. Once again, thanks for the links.
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

04 Aug 2014, 02:18

StringReverse

Code: Select all

StringReverse(str)
{
    static rev := A_IsUnicode ? "_wcsrev" : "_strrev"
    DllCall("msvcrt.dll\" rev, "Ptr", &str, "CDECL")
    return str
}

MsgBox % StringReverse("01234 56789")        ; ==> 98765 43210
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
julka
Posts: 14
Joined: 06 Feb 2014, 02:31

Re: A collection of small ahk functions

05 Aug 2014, 12:30

Updated my msgbox to work with non-english locales.

Code: Select all

/*
Usual MsgBox, Text or MsgBox [, Options, Title, Text, Timeout]
with 3 extra parameters - custom button texts

If you pass text for a button, options that determine the buttons are ignored

Returns the text of the button pressed by the user or the word Timeout.
	Your problems if you name your buttons so.
		Seriusly.

Important! If you want to have custom text for 1 button,
	you have to pass text for all buttons
	
Important! You cannot have label named ¥Ω¦§ɵǕɶʱ͏ in your script.
	How did you manage though...

Important! Try "Try Again" button in second example.
	Too lazy to fix, since it is the only case when returned value
	will not match the button text.
		If you need exact match, check third example.
			Notice, how options are ignored.
	
msgbox % "You've chosen " julka_msgbox("I like trains.",,,,"Ok...","Woot?")
msgbox % "You've chosen " julka_msgbox(0x6,"Test","This is a test.")
msgbox % "You've chosen " julka_msgbox(0x6,"Train","While this is a train.",,"Cancel","Try Again")
msgbox % julka_msgbox("",,"You have 1 second to press this useful button.",1,"Congrats!")

Thanks titbit, tlm and GeekDude for proof-reading
*/

julka_msgbox(Options:=0,Title:="",Text:="",Timeout:="",B1:="",B2:="",B3:="")
{
	static s_Options,s_Title,s_Text,s_TimeOut,s_B1,s_B2,s_B3

	s_Options:=(Text!="") ? Options : 0
	s_Title:=(Title!="") ? Title : A_ScriptName
	s_Text:=(Text!="") ? Text : Options ? Options : "Press OK to continue"
	s_TimeOut:=Timeout
	if B1
	{
		s_B1:=B1
		if B2, s_B2:=B2
			if B3, s_B3:=B3
				s_Options-=Mod(s_Options,6)-3
			else s_Options-=Mod(s_Options,6)-4
		else s_Options-=Mod(s_Options,6)
	}
	SetTimer, ¥Ω¦§ɵǕɶʱ͏, 15
	msgbox % s_Options ,% s_Title,% s_Text,% s_TimeOut
	;If you can shrink following code, pm julka
	IfMsgBox, %s_B1%
		result:=s_B1
	else IfMsgBox, %s_B2%
			result:=s_B2	
	else ifMsgbox, %s_B3%
		result:=s_B3
	else IfMsgBox, OK
		result:=s_B1
	else IfMsgBox, Yes
		result:=s_B1
	else IfMsgBox, No
		result:=s_B2
	else IfMsgBox, Cancel
		result:=s_B3
	else result:="Timeout"
	s_Options:=s_Title:=s_Text:=s_TimeOut:=s_B1:=s_B2:=s_B3:=""
	return result
	
	¥Ω¦§ɵǕɶʱ͏:
	{	
		IfWinNotExist, % s_Title
			return  ; Keep waiting.
		SetTimer, ¥Ω¦§ɵǕɶʱ͏, off
		WinActivate
		if (s_B1)
			ControlSetText, Button1, % "&" s_B1
		else
		{
			ControlGetText,s_B1, Button1,%s_Title%
			s_B1:=RegExReplace(s_B1,"(\&(?!\&))|\s")
		}
		if (s_B2)
			ControlSetText, Button2, % "&" s_B2
		else
		{
			ControlGetText,s_B2, Button2,%s_Title%
			s_B2:=RegExReplace(s_B2,"(\&(?!\&))|\s")
		}
		if (s_B3)
			ControlSetText, Button3, % "&" s_B3
		else
		{
			ControlGetText,s_B3, Button3,%s_Title%
			s_B3:=RegExReplace(s_B3,"(\&(?!\&))|\s")
		}	
		return
	}
}
julka
Posts: 14
Joined: 06 Feb 2014, 02:31

Re: A collection of small ahk functions

11 Aug 2014, 02:23

Code: Select all

;Function similar to InSrt(), just the array is searched for a string.
;Specifying depth 0 or less will force to search the entire array.
InArr(Arr,query,depth:=5)
{
	
	for k,v in Arr
	{
		if (IsObject(v)&&(depth-1))
		{
			if (t:=InArr(v,query,depth-1))
				return k "." t
		}		
		else if (query=v)
			return k
	}		
	return ""		
}
kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: A collection of small ahk functions

18 Aug 2014, 10:46

GCD
Find the greatest common divisor (GCD) of two numbers using the euclidean algorithm.

Code: Select all

gcd(a, b) {
    while b
        b := Mod(a|0, a:=b)
    return, a
}
Example
MsgBox, % gcd(18, 48)

Output
6

There was some discussion of the speed of this function in this thread. This version seems to be about 20% faster than the fastest version.
guest3456
Posts: 3463
Joined: 09 Oct 2013, 10:31

Re: A collection of small ahk functions

18 Aug 2014, 12:26

fastest would have to be MCode, no?

kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: A collection of small ahk functions

18 Aug 2014, 12:48

Yep.
Not sure if MCode would be appropriate for this thread though since it is "ahk functions".
kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: A collection of small ahk functions

18 Aug 2014, 14:54

MCode GCD
Find the greatest common divisor (GCD) of two numbers using the euclidean algorithm.
I had been meaning to make an MCode version. guest3456's comment finally gave me the motivation. This runs in about 37% of the time it takes the function above, so it is much faster.

Code: Select all

gcd(a, b) {
	static gcd, x := MCode(gcd, "5589E583E4F083EC10E800000000EB1C8B450C8944240C8B450889C2C1FA1FF77D0C89550C8B44240C894508837D0C000F95C084C075D98B4508C9C3")
	return dllcall(&gcd, "Int",a, "Int",b)
}

; http://www.autohotkey.com/board/topic/19483-machine-code-functions-bit-wizardry/
MCode(ByRef code, hex) { ; allocate memory and write Machine Code there
	VarSetCapacity(code, StrLen(hex) // 2)
	Loop % StrLen(hex) // 2
		NumPut("0x" . SubStr(hex, 2 * A_Index - 1, 2), code, A_Index - 1, "Char")
}
Example
MsgBox, % gcd(18, 48)

Output
6

Source

Code: Select all

using namespace std;

int main (int a, int b)
{
    int t;
   
    while (b != 0)
    {
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}
Last edited by kon on 18 Aug 2014, 16:44, edited 2 times in total.
guest3456
Posts: 3463
Joined: 09 Oct 2013, 10:31

Re: A collection of small ahk functions

18 Aug 2014, 16:21

did you generate the mcode locally? seems the online generator is offline http://bentschi.no-ip.org/mcode/

kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: A collection of small ahk functions

18 Aug 2014, 16:33

Yeah, I don't have Microsoft Visual Studio Express on the computer I am currently working on so I used Dev C++ with the compiler option -Wa,-aln=foo.s (foo.s is the output file name).
Then I used this script to strip the hex codes from the foo.s file:

Code: Select all

Gui, -Caption +Border +LastFound
Gui, Margin, 10, 10
Gui, Font, s10 bold
Gui, Add, Text, vT1 y100, Drag and drop a file.
GuiControlGet, T1, Pos
Gui, Add, Button,  w%T1W% Default, Close
Gui, Show
return

GuiDropFiles:
Loop, parse, A_GuiEvent, `n
{
    FileRead, ThisFile, % A_LoopField
	p := 1, m := "", Output := ""
	while p := RegexMatch(ThisFile, "mi)^\s*\d+(\s[\dA-F]{4}\s|\s{6})([\dA-F]+)", m, p + StrLen(m))
		Output .= m2
	if (Output) {
		SplitPath, A_LoopField, OutFileName, OutDir, OutExt, OutNameNoExt
		FileAppend, % Output, % OutDir "\MCode_" OutNameNoExt ".txt"
	}
}
return

ButtonClose:
ExitApp
User avatar
joedf
Posts: 8959
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: A collection of small ahk functions

18 Aug 2014, 17:11

Thanks for sharing!!! :D
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

28 Aug 2014, 02:50

Start Control Panel Applications (Shortcuts)
just run it (1by1)

Code: Select all

ComObjCreate("shell.application").ControlPanelItem("appwiz.cpl")      ; => Add/Remove Programs
ComObjCreate("shell.application").ControlPanelItem("calc")            ; => Calculator
ComObjCreate("shell.application").ControlPanelItem("control")         ; => Control Panel
ComObjCreate("shell.application").ControlPanelItem("dcomcnfg")        ; => Component Services
ComObjCreate("shell.application").ControlPanelItem("compmgmt.msc")    ; => Computer Management
ComObjCreate("shell.application").ControlPanelItem("timedate.cpl")    ; => Date and Time Properties
ComObjCreate("shell.application").ControlPanelItem("dfrgui")          ; => Defragment User Interface
ComObjCreate("shell.application").ControlPanelItem("devmgmt.msc")     ; => Device Manager
ComObjCreate("shell.application").ControlPanelItem("hdwwiz.cpl")      ; => Device Manager
ComObjCreate("shell.application").ControlPanelItem("diskmgmt.msc")    ; => Disk Management
ComObjCreate("shell.application").ControlPanelItem("eventvwr.msc")    ; => Event Viewer
ComObjCreate("shell.application").ControlPanelItem("gpedit.msc")      ; => Group Policy Editor
ComObjCreate("shell.application").ControlPanelItem("iexplore")        ; => Internet Explorer
ComObjCreate("shell.application").ControlPanelItem("inetcpl.cpl")     ; => Internet Properties
ComObjCreate("shell.application").ControlPanelItem("secpol.msc")      ; => Local Security Settings
ComObjCreate("shell.application").ControlPanelItem("lusrmgr.msc")     ; => Local Users and Groups
ComObjCreate("shell.application").ControlPanelItem("logoff")          ; => Logs You Out Of Windows
ComObjCreate("shell.application").ControlPanelItem("main.cpl")        ; => Mouse Properties
ComObjCreate("shell.application").ControlPanelItem("ncpa.cpl")        ; => Network Connections
ComObjCreate("shell.application").ControlPanelItem("notepad")         ; => Notepad
ComObjCreate("shell.application").ControlPanelItem("perfmon.msc")     ; => Performance Monitor
ComObjCreate("shell.application").ControlPanelItem("powercfg.cpl")    ; => Power Configuration
ComObjCreate("shell.application").ControlPanelItem("intl.cpl")        ; => Regional Settings
ComObjCreate("shell.application").ControlPanelItem("mstsc")           ; => Remote Desktop
ComObjCreate("shell.application").ControlPanelItem("wscui.cpl")       ; => Security Center
ComObjCreate("shell.application").ControlPanelItem("services.msc")    ; => Services
ComObjCreate("shell.application").ControlPanelItem("fsmgmt.msc")      ; => Shared Folders/MMC
ComObjCreate("shell.application").ControlPanelItem("shutdown")        ; => Shuts Down Windows
ComObjCreate("shell.application").ControlPanelItem("snippingtool")    ; => Snipping Tool
ComObjCreate("shell.application").ControlPanelItem("sndvol")          ; => Sound Volume
ComObjCreate("shell.application").ControlPanelItem("mmsys.cpl")       ; => Sounds and Audio
ComObjCreate("shell.application").ControlPanelItem("StikyNot")        ; => Sticky Note
ComObjCreate("shell.application").ControlPanelItem("msconfig")        ; => System Configuration Utility
ComObjCreate("shell.application").ControlPanelItem("msinfo32")        ; => System Information
ComObjCreate("shell.application").ControlPanelItem("sysdm.cpl")       ; => System Properties
ComObjCreate("shell.application").ControlPanelItem("taskmgr")         ; => Task Manager
ComObjCreate("shell.application").ControlPanelItem("netplwiz")        ; => User Accounts
ComObjCreate("shell.application").ControlPanelItem("utilman")         ; => Utility Manager
ComObjCreate("shell.application").ControlPanelItem("firewall.cpl")    ; => Windows Firewall
ComObjCreate("shell.application").ControlPanelItem("wf.msc")          ; => Windows Firewall with Advanced Security
ComObjCreate("shell.application").ControlPanelItem("wmimgmt.msc")     ; => Windows Management Infrastructure
ComObjCreate("shell.application").ControlPanelItem("wuapp")           ; => Windows Update App Manager
ComObjCreate("shell.application").ControlPanelItem("write")           ; => Wordpad
ComObjCreate("shell.application").ShutdownWindows()                   ; => Shutdown Menu
new ActiveXObject("shell.application").ControlPanelItem("control"); in .js
CreateObject("shell.application").ControlPanelItem("control") in .vbs
Last edited by jNizM on 28 Aug 2014, 03:57, edited 6 times in total.
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
just me
Posts: 9458
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: A collection of small ahk functions

28 Aug 2014, 03:23

This is getting unclear. What about a TOC in the first post?

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: kaka2 and 135 guests