Chimaera

AutoIt Snippets

316 posts in this topic




#62 ·  Posted (edited)

Simple non-flickering key press-and-hold sensor.

#include <Misc.au3>

$hDll = DllOpen("user32.dll")
$shift = 0

While 1
   Switch _IsPressed('10', $hDll) ;Checks if Shift key pressed
      Case 1
         If $shift = 0 Then ConsoleWrite("Key pressed" & @LF)
         $shift = 1
      Case 0
         If $shift = 1 Then ConsoleWrite("Key released" & @LF)
         $shift = 0
   EndSwitch
   If _IsPressed('1B', $hDll) Then ExitLoop ;Exits if Esc key pressed
WEnd
DllClose($hDll)

Regards,
Cyberbit

Edited by cyberbit

_ArrayConcatenate2D · Aero Flip 3D · EPOCH (destroy timestamps) · File Properties Modifier · _GetFileType · UpdateEngine<new> · In-line Case (_ICase) <new>

[hr]

50% of the time, it works all the time. -PezoFaSho

Share this post


Link to post
Share on other sites

#63 ·  Posted (edited)

$sTmp = _IsDir('Folder')
; $sTmp = _IsDir('C:WINDOWS')
; $sTmp = _IsDir('C:Boot.ini')
If Not (@error Or $sTmp) Then
    MsgBox(0, ';)', 'File')
ElseIf $sTmp Then
    MsgBox(0, ';)', 'Folder')
Else
    MsgBox(0, ';)', 'Error')
EndIf

Func _IsDir($sTmp)
    $sTmp = FileGetAttrib($sTmp)
    Return SetError(@error, 0, StringInStr($sTmp, 'D', 2) > 0)
EndFunc

Edited by AZJIO

Share this post


Link to post
Share on other sites

_JumpRegistry('HKEY_CURRENT_USERSoftwareMicrosoftNotepad')



Func _JumpRegistry($sKey)

    Local $hWnd, $hControl, $aKey, $i

    If Not ProcessExists("regedit.exe") Then

        Run(@WindowsDir & 'regedit.exe')

        If Not WinWaitActive('[CLASS:RegEdit_RegEdit]', '', 3) Then Return SetError(1, 1, 1)

    EndIf

    If Not WinActive('[CLASS:RegEdit_RegEdit]') Then WinActivate('[CLASS:RegEdit_RegEdit]')



    $hWnd = WinGetHandle("[CLASS:RegEdit_RegEdit]")

    $hControl = ControlGetHandle($hWnd, "", "[CLASS:SysTreeView32; INSTANCE:1]")



    $aKey = StringSplit($sKey, '')

    $sKey = '#0'

    For $i = 1 To $aKey[0]

        ControlTreeView($hWnd, "", $hControl, "Expand", $sKey)

        $sKey &= '|' & $aKey[$i]

    Next

    ControlTreeView($hWnd, "", $hControl, "Expand", $sKey)

    ControlTreeView($hWnd, "", $hControl, "Select", $sKey)

EndFunc

1 person likes this

Share this post


Link to post
Share on other sites

#65 ·  Posted (edited)

Enumerate Removable Drives :::::: Another Contribution I hope its helpful! Sorry about the format got fed up trying to format when pasting it in. Perhaps someone can enlighten me on what I'm doing wrong. My code is ok in scite when I paste here the format goes even though I'm posting as autoit code.

;~ AutoIt Version: V3.3.6.1 [X32]
;~ Windows Version: WIN_XP [X86]
;~ Language: English (0409)
#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
local $free,$label,$Drive,$status,$usb
ToolTip("Enumerating Drives please wait...", 10, 10, "Loading drives...", 1)
Sleep(2000)
ToolTip("")

Local $aDrives = DriveGetDrive("REMOVABLE")

If Not IsArray($aDrives) Then
;lets check first if there is a USB Stick attached to machine.
$usb = 0
ToolTip("No removable drives found; NO USB Stick in port!", 10, 10, "NO USB Sticks...", 1)
Sleep(1000)
ToolTip("")
MsgBox(16, "No Removeable Drives", "No Removeable Drives Found Please Insert And Try Again")
ConsoleWrite("No removable drives found; NO USB Stick in port!")
Exit
Else
$usb = 1
For $i = 1 To $aDrives[0]
If $aDrives[$i] = "A:" Then ContinueLoop
$drive = StringUpper($aDrives[$i])
$status = DriveStatus($drive)
$free = Round(DriveSpaceFree($drive), 2)
$label = DriveGetLabel($aDrives[$i])
ConsoleWrite("**** Drive Number " & $i & " ****" & @CRLF & _
"Letter: " & StringUpper($aDrives[$i]) & @CRLF & _
"Label: " & DriveGetLabel($aDrives[$i]) & @CRLF & _
"Status: " & DriveStatus($aDrives[$i]) & @CRLF)
If $status = "UNKNOWN" Then
MsgBox(16, "USB Format", "Please format USB and run backup again", 4)
;Stick code in here to check return value and call format drive if required.
Exit
EndIf
If $i > 1 Then
MsgBox(16, "Only One USB drive Allowed", "Please remove one of the removeable drives and run again", 4)
Exit
Else
MsgBox(16, "USB Drive : - " & $label, Round(DriveSpaceTotal($drive) / 1012, 2) & "Gb" & " Drive has been allocated letter " & $drive & @CRLF & @CRLF & " Drive has " & $free & "Mb Free Space!")
EndIf
Next
ConsoleWrite($aDrives[0] & " Drives Loaded." & @CRLF & @CRLF)
EndIf
Exit
Edited by Ambient

Share this post


Link to post
Share on other sites

#66 ·  Posted (edited)

I've not seen a _FileMove in snippets.

FileWrite(@scriptdir & 'test.txt','Test')
_FileMove(@scriptdir & 'test.txt', @scriptdir & 'TEST', 1)
If @error Then MsgBox(0,"Error",@error)

Func _FileMove($sPath, $sDIR, $iOverwrite = 0)
    Local Const $FILENOTEXIST = 1, $COPYFAILED = 2, $DELETEFAILED = 3
    If Not FileExists($sPath) Then Return SetError($FILENOTEXIST,0,0)
    Local $FLAG = 8 + $iOverwrite
    If $iOverwrite > 9 Then    $iOverwrite = 9
    If Not  FileCopy($sPath, $sDIR, $FLAG) Then Return SetError($COPYFAILED,0,0)
    If Not FileDelete($sPath) Then Return SetError($DELETEFAILED,0,0)
    Return 1
EndFunc
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

#67 ·  Posted (edited)

:ph34r:



;### Rename a file ###
;$sFile = Full path to file
;$sRename = New Filename
;$iOverWrite = 0 or 1

;Success returns 1
;failure, returns 0 and sets @error
; 1 if FileMove fails, 
; 2 if $sFile does not exist
;@extended
; 0 if the new file does not already exist / existed
; 1 if the new file already exists / existed

$File = @ScriptDir & '\filetorename.txt'
FileWrite($File, 'Test')
_FileRename($File, 'newname.txt')
If @error Then MsgBox(0, "Error", @error)

Func _FileRename($sFile, $sRename, $iOverWrite = 0)
    Local Const $FILENOTEXIST = 2
    If Not FileExists($sFile) Then Return SetError($FILENOTEXIST, 0, 0)
    Local $_StringLen = StringLen($sFile)
    Local $_StringInStr = StringInStr($sFile, "\", 0, -1, $_StringLen)
    Local $_Count = $_StringLen - $_StringInStr
    Local $_Dir = StringLeft($sFile, $_StringInStr)
    Local $_NewFile = $_Dir & $sRename
    Local $_NewFileExists = FileExists($_NewFile)
    Local $_FileMove = FileMove($sFile, $_NewFile, $iOverWrite)
    Return SetError(Not $_FileMove, $_NewFileExists, $_FileMove)
EndFunc   ;==>_FileRename
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

#68 ·  Posted (edited)

_stringExtractPaths : returns the paths from a string as an array:

#include <Array.au3> ;used for _ArrayDisplay only

$sText = "Hello Autoit programmers! C:\Folder\Folder\File.ini "
$sText &= "this is a function that extracts paths from a string=C:\Windows\System32\shell32.dll "
$sText &= "\\192.168.0.1 \\192.168.0.151\Folder\file.ini \\192.168.0.126\Folder "
$sText &= "c:/folder/file.ini c:\folder\file.ini X:\Temp\Jo\autoit.txt! some text "
$sText &= "my site:http://www.jmontserrat.com googlehttps://www.google.co.jp some ftp link ftp://www.mysite.com/index ftps://www.mysite.com/index twitter;www.twitter.com "
$sText &= "rtp://www.mysite.com/index mms://www.mysite.com/index.php rtsp://www.mysite.com/index.php "
$sText &= "check this link:'http://www.autoitscript.com/forum/index.php?showtopic=9296&hl=' link http://www.autoitscript.com/forum/topic/51547-scilexer-udf/page__st__80#entry1024458 "
$sText &= "\\Computer12 \\computer\folder \\vfx_node02\testfolder\file.ini //vfx_node02/testfolder/file.ini"

$aPaths = _StringExtractPath($sText)
_ArrayDisplay($aPaths)

; #FUNCTION# ====================================================================================================================
; Name ..........: _StringExtractPath
; Description ...: Extracts the paths from a text and return an array of paths.
; Syntax ........: _StringExtractPath($sText)
; Parameters ....: $sText               - The String to extract the paths from.
; Return values .: 1D Array of paths. Array[0] contains the number of paths found.
; Author ........: Jmon
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _StringExtractPath($sText)
    Local $aRet[1] = [0], $a
    $a = StringRegExp($sText, '(?i)((?:(?:https?|rtp|mms|rtsp|file|ftps?)\:)?[\\|\/]{2}[\w-_]*[\w\\\/?&=.~;\-+!*_#%]*)|([a-z]:[\\\/][\w\.-_\\\/]*)|(w{3}\.[\w\\\/?&=.~;\-+!*_#%]*)', 3)
    If @error = 0 Then
        For $i = 0 To UBound($a) - 1
            If $a[$i] <> "" Then
                $aRet[0] += 1
                ReDim $aRet[$aRet[0] + 1]
                $aRet[$aRet[0]] = $a[$i]
            EndIf
        Next
    EndIf
    Return $aRet
EndFunc   ;==>_StringExtractPath

I had a hard time finding a regexp to find them all!

[EDIT] Sorry, it seems that the forum formatting messed up my post. I'll try to fix it. For the moment the example doesn't work...

[EDIT2] ok now it works.

[EDIT3] added other streaming protocols in the regexp. Thanks cyberbit

[EDIT4]Fixed again the same problem as edit1

Edited by jmon

Share this post


Link to post
Share on other sites

Download File From IE 8 - English

Func DownloadFromIE($path,$fileOk)
$IEVersionF = StringLeft(FileGetVersion(@ProgramFilesDir & "\Internet Explorer\iexplore.exe"),3)
$pathOk = $path & $fileOk
Sleep(1000)

ControlFocus("File Download", "", "[CLASS:Button; INSTANCE:2]")
ControlClick("File Download", "", "[CLASS:Button; INSTANCE:2]")
Sleep(1000)
ControlFocus("Save As", "", "[CLASS:Button; INSTANCE:2]")
ControlSend("Save As","","Edit1",$pathOk,@SW_ENABLE)
ControlClick("Save As","","[CLASS:Button; INSTANCE:2]")
Sleep(2000)
EndFunc

Share this post


Link to post
Share on other sites

#70 ·  Posted (edited)

This long, long function translates decimal Windows locale codes into human-readable names. I've added a wrapper to meet the Snippets guidelines.

I wrote this when I was using WMI to query the Win32_OperatingSystem for, among other things, the OS language.

Remember, these are the decimal codes, not the hex. The example returns English - United States.

The list comes from: http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7



Local $MyOSLanguage = 1033

ConsoleWrite(_OSLang($MyOSLanguage))



Func _OSLang($lang)

Switch $lang

Case 1078

Return "Afrikaans"

Case 1052

Return "Albanian"

Case 1118

Return "Amharic"

Case 5121

Return "Arabic - Algeria"

Case 15361

Return "Arabic - Bahrain"

Case 3073

Return "Arabic - Egypt"

Case 2049

Return "Arabic - Iraq"

Case 11265

Return "Arabic - Jordan"

Case 13313

Return "Arabic - Kuwait"

Case 12289

Return "Arabic - Lebanon"

Case 4097

Return "Arabic - Libya"

Case 6145

Return "Arabic - Morocco"

Case 8193

Return "Arabic - Oman"

Case 16385

Return "Arabic - Qatar"

Case 1025

Return "Arabic - Saudi Arabia"

Case 10241

Return "Arabic - Syria"

Case 7169

Return "Arabic - Tunisia"

Case 14337

Return "Arabic - United Arab Emirates"

Case 9217

Return "Arabic - Yemen"

Case 1067

Return "Armenian"

Case 1101

Return "Assamese"

Case 2092

Return "Azeri - Cyrillic"

Case 1068

Return "Azeri - Latin"

Case 1069

Return "Basque"

Case 1059

Return "Belarusian"

Case 2117

Return "Bengali - Bangladesh"

Case 1093

Return "Bengali - India"

Case 5146

Return "Bosnian"

Case 1026

Return "Bulgarian"

Case 1109

Return "Burmese"

Case 1027

Return "Catalan"

Case 2052

Return "Chinese - China"

Case 3076

Return "Chinese - Hong Kong SAR"

Case 5124

Return "Chinese - Macau SAR"

Case 4100

Return "Chinese - Singapore"

Case 1028

Return "Chinese - Taiwan"

Case 1050

Return "Croatian"

Case 1029

Return "Czech"

Case 1030

Return "Danish"

Case 1125

Return "Divehi; Dhivehi; Maldivian"

Case 2067

Return "Dutch - Belgium"

Case 1043

Return "Dutch - Netherlands"

Case 1126

Return "Edo"

Case 3081

Return "English - Australia"

Case 10249

Return "English - Belize"

Case 4105

Return "English - Canada"

Case 9225

Return "English - Caribbean"

Case 2057

Return "English - Great Britain"

Case 16393

Return "English - India"

Case 6153

Return "English - Ireland"

Case 8201

Return "English - Jamaica"

Case 5129

Return "English - New Zealand"

Case 13321

Return "English - Phillippines"

Case 7177

Return "English - Southern Africa"

Case 11273

Return "English - Trinidad"

Case 1033

Return "English - United States"

Case 12297

Return "English - Zimbabwe"

Case 1061

Return "Estonian"

Case 1080

Return "Faroese"

Case 1065

Return "Farsi - Persian"

Case 1124

Return "Filipino"

Case 1035

Return "Finnish"

Case 2060

Return "French - Belgium"

Case 11276

Return "French - Cameroon"

Case 3084

Return "French - Canada"

Case 9228

Return "French - Congo"

Case 12300

Return "French - Cote d'Ivoire"

Case 1036

Return "French - France"

Case 5132

Return "French - Luxembourg"

Case 13324

Return "French - Mali"

Case 6156

Return "French - Monaco"

Case 14348

Return "French - Morocco"

Case 10252

Return "French - Senegal"

Case 4108

Return "French - Switzerland"

Case 7180

Return "French - West Indies"

Case 1122

Return "Frisian - Netherlands"

Case 1071

Return "FYRO Macedonia"

Case 2108

Return "Gaelic - Ireland"

Case 1084

Return "Gaelic - Scotland"

Case 1110

Return "Galician"

Case 1079

Return "Georgian"

Case 3079

Return "German - Austria"

Case 1031

Return "German - Germany"

Case 5127

Return "German - Liechtenstein"

Case 4103

Return "German - Luxembourg"

Case 2055

Return "German - Switzerland"

Case 1032

Return "Greek"

Case 1140

Return "Guarani - Paraguay"

Case 1095

Return "Gujarati"

Case 1037

Return "Hebrew"

Case 1279

Return "HID (Human Interface Device)"

Case 1081

Return "Hindi"

Case 1038

Return "Hungarian"

Case 1039

Return "Icelandic"

Case 1136

Return "Igbo - Nigeria"

Case 1057

Return "Indonesian"

Case 1040

Return "Italian - Italy"

Case 2064

Return "Italian - Switzerland"

Case 1041

Return "Japanese"

Case 1099

Return "Kannada"

Case 1120

Return "Kashmiri"

Case 1087

Return "Kazakh"

Case 1107

Return "Khmer"

Case 1111

Return "Konkani"

Case 1042

Return "Korean"

Case 1088

Return "Kyrgyz - Cyrillic"

Case 1108

Return "Lao"

Case 1142

Return "Latin"

Case 1062

Return "Latvian"

Case 1063

Return "Lithuanian"

Case 2110

Return "Malay - Brunei"

Case 1086

Return "Malay - Malaysia"

Case 1100

Return "Malayalam"

Case 1082

Return "Maltese"

Case 1112

Return "Manipuri"

Case 1153

Return "Maori"

Case 1102

Return "Marathi"

Case 2128

Return "Mongolian"

Case 1104

Return "Mongolian"

Case 1121

Return "Nepali"

Case 1044

Return "Norwegian - Bokml"

Case 2068

Return "Norwegian - Nynorsk"

Case 1096

Return "Oriya"

Case 1045

Return "Polish"

Case 1046

Return "Portuguese - Brazil"

Case 2070

Return "Portuguese - Portugal"

Case 1094

Return "Punjabi"

Case 1047

Return "Raeto-Romance"

Case 2072

Return "Romanian - Moldova"

Case 1048

Return "Romanian - Romania"

Case 1049

Return "Russian"

Case 2073

Return "Russian - Moldova"

Case 1083

Return "Sami Lappish"

Case 1103

Return "Sanskrit"

Case 3098

Return "Serbian - Cyrillic"

Case 2074

Return "Serbian - Latin"

Case 1072

Return "Sesotho (Sutu)"

Case 1074

Return "Setsuana"

Case 1113

Return "Sindhi"

Case 1115

Return "Sinhala; Sinhalese"

Case 1051

Return "Slovak"

Case 1060

Return "Slovenian"

Case 1143

Return "Somali"

Case 1070

Return "Sorbian"

Case 11274

Return "Spanish - Argentina"

Case 16394

Return "Spanish - Bolivia"

Case 13322

Return "Spanish - Chile"

Case 9226

Return "Spanish - Colombia"

Case 5130

Return "Spanish - Costa Rica"

Case 7178

Return "Spanish - Dominican Republic"

Case 12298

Return "Spanish - Ecuador"

Case 17418

Return "Spanish - El Salvador"

Case 4106

Return "Spanish - Guatemala"

Case 18442

Return "Spanish - Honduras"

Case 2058

Return "Spanish - Mexico"

Case 19466

Return "Spanish - Nicaragua"

Case 6154

Return "Spanish - Panama"

Case 15370

Return "Spanish - Paraguay"

Case 10250

Return "Spanish - Peru"

Case 20490

Return "Spanish - Puerto Rico"

Case 1034

Return "Spanish - Spain (Traditional)"

Case 14346

Return "Spanish - Uruguay"

Case 8202

Return "Spanish - Venezuela"

Case 1089

Return "Swahili"

Case 2077

Return "Swedish - Finland"

Case 1053

Return "Swedish - Sweden"

Case 1114

Return "Syriac"

Case 1064

Return "Tajik"

Case 1097

Return "Tamil"

Case 1092

Return "Tatar"

Case 1098

Return "Telugu"

Case 1054

Return "Thai"

Case 1105

Return "Tibetan"

Case 1073

Return "Tsonga"

Case 1055

Return "Turkish"

Case 1090

Return "Turkmen"

Case 1058

Return "Ukrainian"

Case 0

Return "Unicode"

Case 1056

Return "Urdu"

Case 2115

Return "Uzbek - Cyrillic"

Case 1091

Return "Uzbek - Latin"

Case 1075

Return "Venda"

Case 1066

Return "Vietnamese"

Case 1106

Return "Welsh"

Case 1076

Return "Xhosa"

Case 1085

Return "Yiddish"

Case 1077

Return "Zulu"

EndSwitch

EndFunc
Edited by newsman220

Share this post


Link to post
Share on other sites

#71 ·  Posted (edited)

This is really jchd's code, but I have optimized it slightly. Here is the post by jchd. I thought it was so useful that it deserved to be posted here. I hope you agree with me.

Func _ArrayShuffle(ByRef $aArray)
    If IsArray($aArray) = 0 Or UBound($aArray, 0) > 1 Then Return SetError (1)

    Local $vTemp, $r, $iBound = UBound($aArray) -1
    For $i = 0 To $iBound
        $r = Random(0, $iBound, 1)
        $vTemp = $aArray[$i]
        $aArray[$i] = $aArray[$r]
        $aArray[$r] = $vTemp
    Next
EndFunc

For a multidimensional version see

Edited by czardas

Share this post


Link to post
Share on other sites

#72 ·  Posted (edited)

GuiCtrlSetOnTop: This snippet is to set your control on top of others:

#include <WinAPI.au3>
#include <APIConstants.au3>

Global $GUI, $LABEL1, $LABEL2, $LABEL3
$GUI = GUICreate("Test", 800, 600)
GUISetState()
$LABEL1 = GUICtrlCreateLabel("under", 20, 20, 500, 300)
GUICtrlSetBkColor(-1, 0xFF0000)
$LABEL2 = GUICtrlCreateLabel("above", 40, 60, 500, 300)
GUICtrlSetBkColor(-1, 0x00FF00)
$LABEL3 = GUICtrlCreateLabel("above 2", 60, 80, 500, 300)
GUICtrlSetBkColor(-1, 0x0000FF)

GuiCtrlSetOnTop($LABEL1)
Sleep(1000)
GuiCtrlSetOnTop($LABEL3)
Sleep(1000)
GuiCtrlSetOnTop($LABEL2)

Do
    Sleep(50)
Until GUIGetMsg() = -3
Exit

; #FUNCTION# ====================================================================================================================
; Name ..........: GuiCtrlSetOnTop
; Description ...: Sets a control on top of others, by changing the z-ordering.
; Syntax ........: GuiCtrlSetOnTop($iCtrlID)
; Parameters ....: $iCtrlID             - A control ID or Handle.
; Return values .:  True: Success
;                   False: Failure
; Author ........: jmon
; Modified ......:
; Remarks .......: Need to include <WinAPI.au3> and <APIConstants.au3>
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func GuiCtrlSetOnTop($iCtrlID)
    Local $hWnd = $iCtrlID
    If Not IsHWnd($hWnd) Then $hWnd = GUICtrlGetHandle($iCtrlID)
    Return _WinAPI_SetWindowPos($hWnd, $HWND_BOTTOM, 0, 0, 0, 0, $SWP_NOMOVE + $SWP_NOSIZE + $SWP_NOCOPYBITS)
EndFunc
Edited by jmon

Share this post


Link to post
Share on other sites

You are correct. True Diceware passphrases arn't distinguished from random gibberish containing spaces. Suggested improvement 1 (checking alphanumeric and space) is easily implemented:

#cs _CalculateBitEntropy
Name: _CalculateBitEntropy
Description: Calculate the bit entropy of a string.
Author: dany
Parameters: $sStr - String: String to evaluate.
$fCase - Boolean: Do case-sensitive evaluation, default true.
Return values: Success: - Float: Bit entropy.
Failure: - 0 and sets @error
Link: http://en.wikipedia.org/wiki/Password_strength#Entropy_as_a_measure_of_password_strength
#ce
Func _CalculateBitEntropy($sStr, $fCase = True)
If IsBinary($sStr) Then $sStr = BinaryToString($sStr)
If Not IsString($sStr) Then Return SetError(1, 0, 0)
Local $aDice, $iH = 0, $iLen = StringLen($sStr)
If 0 = $iLen Then Return SetError(2, 0, 0)
$aDice = StringSplit($sStr, ' ')
If 1 < $aDice[0] And StringRegExp($sStr, '^[[:alnum:] ]+$') Then Return $aDice[0] * 12.925
If StringIsDigit($sStr) Then
$iH = 3.3219
ElseIf StringIsXDigit($sStr) Then
$iH = 4.0000
ElseIf StringIsAlpha($sStr) Then
$iH = 4.7004
If $fCase Then
If StringRegExp($sStr, '[[:lower:]]') And StringRegExp($sStr, '[[:upper:]]') Then $iH = 5.7004
EndIf
ElseIf StringIsAlNum($sStr) Then
$iH = 5.1699
If $fCase Then
If StringRegExp($sStr, '[[:lower:]]') And StringRegExp($sStr, '[[:upper:]]') Then $iH = 5.9542
EndIf
ElseIf StringRegExp($sStr, '^[^[:cntrl:]x7F]+$') Then
$iH = 6.5699
ElseIf _StringRegExp($sStr, '^[^[:cntrl:]x7Fx81x8Dx8Fx90x9D]+$') Then
$iH = 7.7682
EndIf
Return $iH * $iLen
EndFunc

However, I'm not going to implement a check if the words are in a Diceware list, as there is no standard list. Besides this function only calculates bit entropy, it doesn't care about the validity of the words that's the job of a login script.

Thanks for the feedback :)

edit: optimized regepx.

This does not work: ERROR: _StringRegExp(): undefined function.

Share this post


Link to post
Share on other sites

#74 ·  Posted (edited)

:P

Edit:

A function to split a string based on a regular expression.

; _StringRegExpSplit example.
Global $sString = '1. A numbered list.' & @CRLF & _
        '2. Second item.' & @CRLF & _
        '3. Last item.'
Global $aListItems = _StringRegExpSplit($sString, '[0-9]+. ')

; #FUNCTION# ===================================================================
; Name...........: _StringRegExpSplit
; Description ...: Split a string according to a regular exp[b][/b]ression.
; Syntax.........: _StringRegExpSplit($sString, $sPattern)
; Parameters ....: $sString - String: String to split.
;                 $sPattern - String: Regular exp[b][/b]ression to split on.
; Return values .: Success - Array: Array of substrings, the total is in $array[0].
;                 Failure - Array: The count is 1 ($array[0]) and the full string is returned ($array[1]) and sets @error:
;                 |1 Delimiter not found.
;                 |2 Bad RegExp pattern, @extended contains the offset of the error in the pattern.
; Author ........: dany
; Modified ......:
; Remarks .......:
; Related .......:
; ==============================================================================
Func _StringRegExpSplit($sString, $sPattern)
    Local $aRet[2] = [1, $sString], $sSplit = StringRegExpReplace($sString, $sPattern, '___SPLIT___')
    If @error Then Return SetError(2, @extended, $aRet)
    If 0 = @extended Then Return SetError(1, 0, $aRet)
    Return StringSplit($sSplit, '___SPLIT___', 1)
EndFunc ;==>_StringRegExpSplit
Edited by dany

[center]Spiderskank Spiderskank[/center]GetOpt Parse command line options UDF | AU3Text Program internationalization UDF | Identicon visual hash UDF

Share this post


Link to post
Share on other sites

#75 ·  Posted (edited)

czardas

Func _StringRegExpSplit($sString, $sPattern)
    Local $aRet[2] = [1, $sString], $spr = _GetSeparator($sString), $sSplit = StringRegExpReplace($sString, $sPattern, $spr)
    If @error Then Return SetError(2, @extended, $aRet)
    If Not @extended Then Return SetError(1, 0, $aRet)
    Return StringSplit($sSplit, $spr, 1)
EndFunc   ;==>_StringRegExpSplit

Func _GetSeparator($sString)
    For $i = 1 To 31
        $s = Chr($i)
    ; $s = Chr($i)&Chr($i+1)&Chr($i)
        If Not StringInStr($sString, $s) Then Return $s
    Next
    Return SetError(1)
EndFunc   ;==>_GetSeparator
Edited by AZJIO

Share this post


Link to post
Share on other sites

#76 ·  Posted (edited)

czardas

Universal it won't turn out, always there will be restrictions. It is necessary to solve for a concrete case.

Func _GetSeparator($sString)
    Local $d, $s
    For $x = 1 To 9 Step 2
        For $i = 1 To 31
            $s = ''
            $d = 1
            For $z = 1 To $x
                If $d Then
                    $d = 0
                Else
                    $d = 1
                EndIf
                $s &= Chr($i + $d)
            Next
            If Not StringInStr($sString, $s) Then Return $s
        Next
    Next
    Return SetError(1)
EndFunc   ;==>_GetSeparator
Edited by AZJIO

Share this post


Link to post
Share on other sites

#77 ·  Posted (edited)

Edit

I just though of something. Perhaps first converting to binary and then splitting would work (any non hex character could be used as a universal delimiter).

Well no, it's just a different format, the problem stays the same. The non-hex character might just be the data I want to keep.

I chose ___SPLIT___ because it's rather unlikely to turn up in everyday sentences. Your question is valid nonetheless and I'm intrigued by the offered solutions.

But it would be easier to just change it to ___STRING___REGEXP___SPLIT___. You could check for ___SPLIT___ in the string and in the highly unlikely case it's in there use another overly long placeholder, put a few in an array and loop over them. Chances on collisions are very small and placeholders are a much used technique in template parsers, see the Wiki markup language.

edit:

; #FUNCTION# ===================================================================
; Name...........: _StringRegExpSplit
; Description ...: Split a string according to a regular exp<b></b>ression.
; Syntax.........: _StringRegExpSplit($sString, $sPattern)
; Parameters ....: $sString - String: String to split.
;                  $sPattern - String: Regular exp<b></b>ression to split on.
; Return values .: Success - Array: Array of substrings, the total is in $array[0].
;                  Failure - Array: The count is 1 ($array[0]) and the full string is returned ($array[1]) and sets @error:
;                  |1 Delimiter not found.
;                  |2 Bad RegExp pattern, @extended contains the offset of the error in the pattern.
; Author ........: dany
; Modified ......:
; Remarks .......:
; Related .......:
; ==============================================================================
Func _StringRegExpSplit($sString, $sPattern)
    Local $iDelim, $aDelim[4] = ['___SPLIT___', '___STRING___REGEXP___SPLIT___', '___SPLIT_DELIMITER___', 0]
    Local $aRet[2] = [1, $sString], $sSplit
    For $iDelim = 0 To 3
        If Not StringInStr($sString, $aDelim[$iDelim]) Then ExitLoop
    Next
    If 3 = $iDelim Then Return SetError(3, 0, 0) ; All possible delimiters are in the string!
    $sSplit = StringRegExpReplace($sString, $sPattern, $aDelim[$iDelim])
    If @error Then Return SetError(2, @extended, $aRet)
    If 0 = @extended Then Return SetError(1, 0, $aRet)
    Return StringSplit($sSplit, $aDelim[$iDelim], 1)
EndFunc ;==>_StringRegExpSplit

edit: sorry, posted incomplete code.

You could also generate a random alphanumeric string on the spot and use that as a placeholder delimiter.

edit 2: I'll look into a better revised version tonight, gotta go to work :)

Edited by dany

[center]Spiderskank Spiderskank[/center]GetOpt Parse command line options UDF | AU3Text Program internationalization UDF | Identicon visual hash UDF

Share this post


Link to post
Share on other sites

#78 ·  Posted (edited)

Thanks for your suggestions, czardas and AZJIO. You're right about the delimiter being overly long but it was primarily meant as an example, although the longer the delimiter the less efficient the string lookup and replacing becomes...

Here's my revised version, it generates a temp delimiter on the fly that always starts with Chr(1). There's also a little part at the end to correct the array entries when the string passed was binary.

edit:

; #FUNCTION# ===================================================================
; Name...........: _StringRegExpSplit
; Description ...: Split a string according to a regular exp<b></b>ression.
; Syntax.........: _StringRegExpSplit($sString, $sPattern)
; Parameters ....: $sString - String: String to split.
;                  $sPattern - String: Regular exp<b></b>ression to split on.
; Return values .: Success - Array: Array of substrings, the total is in $array[0].
;                  Failure - Array: The count is 1 ($array[0]) and the full string is returned ($array[1]) and sets @error:
;                  |1 Delimiter not found.
;                  |2 Bad RegExp pattern, @extended contains the offset of the error in the pattern.
;                  |3 No suitable placeholder delimiter could be constructed.
; Author ........: dany
; Modified ......: czardas, AZJIO
; Remarks .......:
; Related .......:
; ==============================================================================
Func _StringRegExpSplit($sString, $sPattern)
    Local $sSplit, $aError[2] = [1, $sString], $sDelim = Chr(1)
    While StringInStr($sString, $sDelim)
        $sDelim &= Chr(Random(0, 255, 1))
        If 32 = StringLen($sDelim) Then Return SetError(3, 0, 0)
    WEnd
    $sSplit = StringRegExpReplace($sString, $sPattern, $sDelim)
    If @error Then Return SetError(@error, @extended, $aError)
    If @extended = 0 Then Return SetError(1, 0, $aError)
    If Not IsBinary($sString) Then Return StringSplit($sSplit, $sDelim, 1)
    $sSplit = StringSplit($sSplit, $sDelim, 1)
    For $i = 2 To $sSplit[0]
        $sSplit[$i] = '0x' & $sSplit[$i]
    Next
    Return $sSplit
EndFunc

Example:

#include <Array.au3>
Global $sString = 'list:1.a2.b3.c'
_ArrayDisplay(_StringRegExpSplit($sString, '[0-9]+.'))
Global $bBinary = Binary($sString)
_ArrayDisplay(_StringRegExpSplit($bBinary, '3[0-9]2E'))
Edited by dany

[center]Spiderskank Spiderskank[/center]GetOpt Parse command line options UDF | AU3Text Program internationalization UDF | Identicon visual hash UDF

Share this post


Link to post
Share on other sites

#79 ·  Posted (edited)

$sDelim &= Chr(Random(0, 255, 1))

Do you know why I reduced the range up to 31?

The regular exp<b></b>ression must not be a combination of '1', '2' ... '9' or '$1', '$2' ... '$9'. Because it inserts the Group.

$ = Chr(36)

= Chr(92)

Chr(0) - sometimes that causes problems.

#include <Array.au3>
_Test(Chr(1))
_Test(Chr(0)) ; problems
Func _Test($spr)
    Dim $arr[6] = [1, 2, 3, 4, 5, 6]
    $Line = $spr & _ArrayToString($arr, $spr, 1) & $spr
    $aTmp = StringRegExp($Line, '(?i)' & $spr & '3' & $spr, 3)
    If Not @error And UBound($aTmp) = 1 Then
        MsgBox(0, 'Yes?', $aTmp[0])
    Else
        MsgBox(0, 'No', 'Error')
    EndIf
EndFunc

Any metacharacter causes problems: '?^()*+['.

Edited by AZJIO

Share this post


Link to post
Share on other sites

#80 ·  Posted (edited)

What about something like.

$Passedstring = "BLAHDFRTUUJHGTFDEER"

_Delim($Passedstring)

Func _Delim($String)
    Local $delim = '', $rtn = ''
    Do
        For $i = 0 To 3
            $delim &= Chr(Random(65, 122, 1))
        Next
        $rtn = $delim
        $delim = ''
    Until Not StringInStr($String, $rtn, 1)
    Return $rtn
EndFunc   ;==>_Delim
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


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