Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 10/30/2017 in all areas

  1. Original post edited to present prompt before update download as well
    2 points
  2. I've made this HTTP lib to simplify HTTP requests, mainly when dealing about POST data or file uploads. Three functions are available: string _HTTP_Get ( string $sURL ) string _HTTP_Post ( string $sURL , string $sPostData ) string _HTTP_Upload ( string $sURL , string $sFilePath , string $sFileField , string $sPostData = '' , string $sFilename = Default) Additionaly, two helper functions are also available: URLEncode($sStr) URLDecode($sStr) Full documentation: https://github.com/jesobreira/HTTP.au3/blob/master/README.md Fork me on Github: https://github.com/jesobreira/HTTP.au3 Download lib + docs: https://github.com/jesobreira/HTTP.au3/archive/master.zip
    1 point
  3. Simulated Annealing (SA) is a simple technique for finding an acceptable solution (but not necessarily always the absolute best one that exists!) to very hard combinatorial problems, that is, ones for which a brute-force approach of cycling through all possible alternatives to find the global optimum just takes too darn long. Typically, one would be seeking some specific sequence or permutation of a (sub)set, and the number of possibilities is astronomically large. In addition, for SA to be applicable, you'll need to be able to quantify in some way how good any particular trial solution is, or how far distant from the ideal result. The real power of SA lies in these so-called cost functions; you can define as many as you like, with different weights if you like, and these conditions are even allowed to be conflicting. User-defined settings define how tenaciously it should be exploring solution space before homing in on a region with desirable properties, and finding its minimum. You can think of it as a learning algorithm that is allowed to make lots of mistakes in the beginning, before gradually avoiding ever more potentially bad decisions. A simple Analogy: You're standing in the middle of an extensive, rough terrain with hills, ridges, bumps, valleys, and tiny, deep depressions. You've got a GPS altimeter to tell you how high above sea-level you currently are, but this area is perpetually shrouded in thick fog. Now find the lowest point. And quickly please. Now what? There's no time to systematically grid and traverse the entire area, and you cannot see more than a few feet ahead. Following the local gradient down-slope will likely get you stuck at a very local minimum, whereas a much lower point may be just beyond the hext hill. Luckily, you brought your magic boots (the red ones with the twinkling silver stars). These allow you to make huge leaps through the fog, landing safely somewhere else. And although you don't know in advance where you'll end up, the boots magically remember their last-previous departure point, so if you don't like your new surroundings, you can go back one jump (but never more than that). Now to find the lowest point in the landscape, you keep tracking your altimeter changes with every jump. Some jumps will get you to higher ground, others might land you in a deep valley. The trick is not to settle for ever-lower heights immediately, but to allow going back up ever so often, so you can get beyond some high ridge behind which you might find a much lower depression than your best-previous result. Crucially, to decide whether or not to gain height in the misty terrain, you roll some dice you've got in your pocket, and the more jumps you've made, the lower you make the upper bound below which you would still go back uphill. So in the beginning you'll be jumping all over the place (allowing you to sample the terrain extensively), but eventually you'll be limiting yourself to some deep valley you've found, which might be the deepest one all round, but even if not, it will still be a pretty good guess. And you will have found this deep valley in a tiny fraction of the time it would take to do a full land survey. Simulated annealing needs to be defined in terms of the specific problem you're trying to solve. So it's not possible to provide you with a generic UDF that'll figure out in advance what your ideal solution would look like (for example, in the analogy above, we might be looking for the highest point instead of the lowest one). You need to define that ideal in terms of one or more cost functions that SA will then attempt to minimise. What can be done is to provide you with specific examples. Example 1. From a list of user-defined pre-supplied values, select the fewest terms that sum to (or approximate) a predefined target total. This solution was written in response to this thread. Current cost updates are periodically written to console. This example attempts to satisfy two conditions simultaneously: getting a sum that matches the target, and using the smallest number of terms. ; Simulated Annealing example (combinatorial minimisation), by RTFC (22 Feb 2016) ; Note that this algorithm converges on A *local* minimum (in terms of the ; user-defined cost-function(s)), which is not necessarily THE *global* minimum. ; Note also that the search path, duration, and final result may differ from run to run. ; Several parameters can be tweaked to adjust this. #include <Array.au3> #include <Math.au3> Global $temperat,$path,$kk,$nswap,$nswapstep,$cost,$altcost,$tempstep Global $costadjust,$ttlsites,$totalcost,$factor,$maxsumlength,$maxsize Global $site1,$site2,$index1,$index2,$weight_sum,$weight_length Global $options,$sumlength,$prevlength ; initialise SRandom(@SEC+@AutoItPID) ; initialise radnomising seed $verbose=True ; T: write regular progress updates to console $factor=1 ; optional Oracle-response adjustment (not used here) $prevlength=$sumlength ; to enable reverting to previous state after _TryChange $minsumlength=0 ; if nothing else is know, we'll start with a single array entry (base-0) $options=10 ; larger value = larger likelihood of swapping vs changing sumlength if $options<3 then Exit ; minimum size for this set-up (see Func _TrySwap) ; adjust the balance of conditions here (see _Cost function) $weight_sum=1 ; relative importance of matching condition 1 (sum = target) $weight_length=1 ; relative importance of matching condition 2 (lowest number of terms) ; summation results buffer Global $bestsum[10] Global $bestsumlength=UBound($bestsum) ; define the summation result we wish to achieve (try different values here!) $target = 27 ; Note: if you change this value, you may have to adjust $minsumlength below as well! ; define our array of summation terms to select from $dim=9 ; this is just the way this problem was presented $ttlsites=$dim*$dim $maxsize=$ttlsites-1 $maxsumlength=$ttlsites-2 ; need at least one tail slot for swapping ; enable this for the predefined problem... $doIntegerTest=True ; False if $doIntegerTest Then Global $aArray = [9,2,2,3,1,1,6,3,4, _ 4,2,3,4,5,6,7,8,7, _ 7,2,3,4,5,1,7,2,2, _ 2,2,3,1,5,5,7,1,4, _ 3,2,1,2,3,6,6,6,4, _ 3,2,3,4,5,6,7,8,3, _ 2,2,3,8,1,4,7,1,2, _ 1,7,3,5,5,6,7,1,2, _ 7,2,3,7,5,1,7,8,9] ; in this specific case, we already know that we'll need at least 4 terms ; because a) 9=max value in array, b) there are only 2 nines in the array, and c) target =3x9 $minsumlength=3 ; base-0, so 4 entries altogether Else ; OR use this for random floats in range 1-$dim (just as an example) Global $aArray[$ttlsites] For $cc=0 to $maxsize $aArray[$cc]=random(1,$dim,0) ; non-integer values used here! Next ; no clue about this constraint in this case $minsumlength=0 ; one entry (base-0) EndIf ;______START OF ANNEALING ROUTINE____________ $nover =1000 ; maximum number of changes at any temperature (for more complicated problems, set this several orders of magnitude higher) $nlimit=Int($nover/4) ; maximum number of successful changes before continuing $nwrite=Int($nover/5) ; default status update interval if verbose=.t. $tempsteps=100 ; number of temperature steps to try $tfactor=0.95 ; annealing schedule: temperature is reduced by this factor after each step While True $temperat=0.5 ; initial temperature; smaller = more aggressive + more myopic search $absimp=0 ; counter $nswapstepzero=0 ; counter $sumlength=$minsumlength ; base-0 ; prep the cost vars $totalcost=_Cost() $cost=$totalcost $lowestcost=$totalcost $initcost=$totalcost ; main loop starts here For $tempstep=1 to $tempsteps ; try up to N temperature steps $nswap=0 $nswapstep=0 For $kk=1 to $nover _TrySwap() ; swap and determine cost adjustment Switch _AskOracle() ; Feel the Force, Luke. Case True $nswap+=1 $totalcost+=$costadjust $cost=$altcost If $lowestcost>$totalcost Then $nswapstep+=1 $absimp+=1 $lowestcost=$totalcost ; ensure results buffer is sufficiently large If $bestsumlength<=$sumlength Then $bestsumlength+=5 ReDim $bestsum[$bestsumlength] EndIf ; flush current-best summation For $bc=0 to $sumlength-1 $bestsum[$bc]=$aArray[$bc] Next ; pad tail with zeroes For $bc=$sumlength to $bestsumlength-1 $bestsum[$bc]=0 Next _ScreenOut() If $totalcost<=0 Then ExitLoop Endif Case Else ; restore the previous state $sumlength=$prevlength $aArray[$index1]=$site1 $aArray[$index2]=$site2 EndSwitch ; show we're still alive If $verbose And mod($kk,$nwrite)=0 Then _ScreenOut() If $nswap>=$nlimit Or $lowestcost<=0 then ExitLoop Next ; optional early-out scenario (disable for a more thorough search) If $nswapstep=0 then $nswapstepzero+=1 If $nswapstepzero=10 then ExitLoop ; no more improvements in the last N temperature steps ; reduce temperature = likelihood of following a trajectory away from the nearest LOCAL optimum (in the hope of getting nearer to the GLOBAL optimum) $temperat*=$tfactor Next ; present final result _Arraysort($bestsum) ; just for clarity $summation="Best result so far (at a cost of " & $lowestcost & ") is: " & @CRLF $terms=0 $result=0 For $cc=0 to $sumlength If $aArray[$cc]>0 then $summation&=$aArray[$cc] & "+" $result+=$aArray[$cc] $terms+=1 Endif Next $summation=StringTrimRight($summation,1) & " = " & $result & " (target = " & $target & ")" & @CRLF $summation&="Number of summation terms: " & $terms & @CR & "Temperature steps: " & $tempstep & @CR & @CR & "Press <Ok> to try again, <Cancel> to Quit" if Msgbox($MB_OKCANCEL,"Simulated Annealing Test Result",$summation)=$IDCANCEL then Exit ; shuffle entries a bit for variety For $cc=1 to $maxsize*10 $index1=random(0,$maxsize,1) $index2=random(0,$maxsize,1) $tmp=$aArray[$index1] $aArray[$index1]=$aArray[$index2] $aArray[$index2]=$tmp Next WEnd Exit Func _AskOracle() If $costadjust<0 Then Return True Else ; this is where all the magic happens! Return (random()<Exp(-($costadjust*$factor)/$temperat)) Endif EndFunc Func _TrySwap() $index1=0 ; these vars are all Globals $index2=0 $altcost=0 $prevlength=$sumlength ; decide whether to reduce/increase number of terms, or swap an existing term Switch Random(1,$options,1) Case 1 ; crop $sumlength=_Max($minsumlength,$sumlength-1) Case 2 ; extend $sumlength=_Min($maxsumlength,$sumlength+1) Case Else ; this likelhood is determined by the value of $options (>=3) $index1=random(0,$sumlength,1) $index2=random($sumlength+1,$maxsize,1) EndSwitch ; store current contents, in case we decide later that this was a bad idea $site1=$aArray[$index1] $site2=$aArray[$index2] ; swap contents for now $aArray[$index1]=$site2 $aArray[$index2]=$site1 ; compute the new sum (as either length or content has changed) $altcost=_Cost() ; performance difference between original and new state $costadjust=$altcost-$cost ; $cost is already filled in previous pass EndFunc Func _Cost() Local $cc,$result=0 For $cc=0 to $sumlength $result+=$aArray[$cc] Next Return (Abs($result-$target)*$weight_sum) + (($sumlength-$minsumlength)*$weight_length) EndFunc Func _ScreenOut() ConsoleWrite("Simulated Annealing. Initial total cost: " & $initcost & @CRLF) ConsoleWrite("Step: " & $tempstep & " of " & $tempsteps & "; Temperature: " & $temperat & @CRLF) ConsoleWrite("Executed Swaps: " & $nswap & "; Lowest Cost so far: " & $lowestcost & @CRLF) ConsoleWrite("Total Improvements: " & $absimp & "; Improvements this step: " & $nswapstep & @CRLF & @CRLF) EndFunc Example 2. The Travelling Salesman problem (TSP) This is a classic combinatorial minimisation problem, and relevant to real-world logistics: to find the shortest route for visiting all cities exactly once, before returning to the original starting point. As it is quite entertaining to see how the algorithm gradually solves this brain teaser, I've added a simple GUI that visualises the cities (red circles) and the changing routes between them (blue). The problem becomes exponentially harder to solve when the number of cities is increased. This example (adapted from Press et al., Numerical recipes, 2nd ed., pp. 438-443) employs a single cost function of the total route distance. TSP.au3 It's important to stress that simulated annealing cannot guarantee that the global optimum will always be found, only that it will likely come up with a fairly good solution, and much faster than brute force ever could. If that's good enough for you, then those red, silver-starred boots might fit you too.
    1 point
  4. [New Version] - 27 Jan 22 New: The GUIScrollbar_Ex UDF now recognises Win-D and taskbar desktop clearance commands and runs the correct minimize/restore code automatically. The previous UDF _Minimize and _Restore commands have been superceded by a single _EventMonitor function which runs in the script idle loop. This is a script-breaking change, but I hope that the additional functionality is worth the small effort it will take to alter your scripts. New UDFs, examples in zip file below. Previous changes: Changelog.txt Are you bemused by scrollbars? > Do you find them too difficult to use? > Then you need the GUIScrollbars_Ex UDF! Just download the zip at the end of the post and run this short script with the UDF in the same folder. No tricky calculations, no complicated functions to master - just easy to use, accurate scrollbars with one command! [size=5]#include <guiconstantsex.au3> #include "GUIScrollbars_Ex.au3" ; Create GUI with red background $hGUI = GUICreate("Test", 500, 500) GUISetBkColor(0xFF0000, $hGUI) ; Create a 1000x1000 green label GUICtrlCreateLabel("", 0, 0, 1000, 1000) GUICtrlSetBkColor(-1, 0x00FF00) GUISetState() ; Generate scrollbars - Yes, this is all you need to do!!!!!!!!!!!!!!!!!!!! _GUIScrollbars_Generate($hGUI, 1000, 1000) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd[/size] Try it today and see how easy it is! I have been trying for some time to understand how scrollbars work and how to get them closely to match the area I want to display. After much research and headscratching I have come up with 2 UDFs which I hope will be of use to others. Apologies for the length of this post, but scrollbars are complex beasts and as I did this mainly for the less experienced user I want to make sure that they understand what is going on. The 2 UDFs are: GUIScrollbars_Ex.au3 - This gives you scrollbars sized to your GUI in one simple command - with no other includes or commands needed. The UDF is designed for those who would not normally use scrollbars because the whole process looks too complicated. It also includes a command to enable you to scroll page by page, thus making it easy to scroll to anywhere on the GUI with only simple calulations based on the values you used to create the GUIs. [New] Ability to have recalculated scrollbars on resizeable GUIs. GUIScrollbars_Size.au3 - This calculates the Page and Max numbers for the user to feed into the _GUIScrollbar_SetScrollInfoPage/Max commands. The UDF is aimed at the more experienced user and is particularly useful when you have a GUI with a dynamic scroll size (i.e. adding or subtracting controls to the scrollable area as the script runs). First, a short tutorial for those who are interested in how the scrollbars affect your GUI and what it is that the UDFs calculate: All the files mentioned here are in a downloadable zip file at the end of the post. GUIScrollbars_Size.au3 As mentioned previously, the GUIScrollbars_Size.au3 UDF is aimed at the more experienced user who wants to use the full range of _GUIScrollbar comands, but would like a quick way of getting the required Page and Max values. It uses no other include files so you will need to include GUIScrollbars.au3 yourself, as well as the necessary GUIRegisterMsg and procedures for WM_VSCROLL and WM_HSCROLL. The syntax is simple - the size of the scrollable GUI and either the handle of the GUI you have created to hold the scrollbars or the size of the one you are going to create. It returns a 6-element array including the Page and Max values for the scrollbars and factors to compensate for the "shrinkage" of the GUI if you had already drawn some controls and wished to add others. Of interest, the returned Max value is biased not to clip the edges of the GUI - reducing it by 1 makes a tighter fit but can lead to some clipping. (If that does not make sense, please see the tutorial above for more details) The Size_Example_1 script to show the UDF in action - the "Pass Size" button shows the effect of creating the scrollbars BEFORE the controls, the "Pass Handle" button shows what happens if the scrollbars are created AFTER the controls. If you do not understand why there is a difference - go and read the tutorial above ! You will need to have the GUIScrollbar_Size.au3 UDF in the same folder. Where this UDF really helps is if you have a scrollable GUI of variable size - if the number of controls varies with user selections for example. All you need to do is to rerun the UDF with the new size of the scrollable GUI and it produces a new Max value for you to use. The Size_Example_2 script shows how the function enables you to dynamically size your scrollbars depending on the number of controls required. As before it requires the GUIScrollbar_Size.au3 UDF in the same folder. -------- Now the "simple" GUIScrollbars_Ex.au3 (which is actually the more complex internally as you would expect). This UDF is intended to be the single point of call for creating scrollbars on a GUI - it will automatically add the GUIScrollbars UDF and the WM_VSCROLL and WM_HSCROLL GUIRegisterMsg commands and procedures to your script - so you need no commands other than those within the UDF itself. These commands are _GUIScrollbars_Generate and _GUIScrollbars_Scroll_Page. As you might expect, _GUIScrollbars_Generate generates scrollbars for your GUI. It is usually called AFTER you have added all the controls and all you need to use it is the GUI handle and the size of the underlying GUI you want to scroll. If you so wish, you can also decide to generate the scrollbars BEFORE the controls on the scrollable GUI, and you can choose if you want to risk not quite reaching the edge of the GUI when the scrollbars are at the maximum position. So a basic call could be as simple as: _GUIScrollbars_Generate ($hGUI, 1000, 1000) which would put scrollbars on the $hGUI window allowing a 1000x1000 underlying GUI to be displayed. _GUIScrollbars_Scroll_Page lets you scroll a page at a time. If your GUI was 200 pixels wide, you would have 1000/200 = 5 pages to scroll before reaching the edge - no need to know what the actual Page and Max values are, just use this simple division based on the number you use to draw the GUIs. So: _GUIScrollbars_Scroll_Page ($hGUI, 3) would scroll to the third page - it would display the area between 400 and 600 pixels of the full 1000 pixel width. If you ask for a page over the maximum available, you just scroll to the maximum position - asking for page 1 resets you to the origin. Ex_Example_1 shows the UDF working. You can decide whether to have both or just one scrollbar, whether to create the scrollbars before or after the controls, and whether you want the maximum scroll to be tight to the edge or leave a border. Just select the options you want - the script selects a random width and height for both the scrollbar GUI and the underlying GUI - and press the "Scroll" button to show a single page scroll down and/or right followed by a scroll to the bottom right corner of the GUI. There are labels to let you see the size of the GUI and the accuracy of the page scrolls (please read the tutorial above to understand why these are almost certainly inaccurate). The script requires the GUIScrollbars_Ex.au3 UDF in the same folder. Ex_Example_2 is a really simple example to show how easy generating scrollbars can now become! As you can see - no other includes, no GUIRegisterMsg commands, no WM_H/VSCROLL procedure functions. Just accurate scrolling and proportional thumb sizes. Ex_Example_3 shows the automatic calculation of control positions. Ex_Example_4 shows how to initiate the cursor keys to scroll the GUI as well. [New] Ex_Example_5 shows how to use the new _GUIScrollbarsEx_Resizer function. I hope these 2 UDFs are useful to AutoIt users - I certainly find them so. Here is a zip file with the UDFs and examples: Scrollbars.zip My grateful thanks to the authors of the GUIScrollbars and WinAPI UDFs for their code, some of which I have plundered. And as always I welcome constructive criticism and/or effusive congratulations. M23
    1 point
  5. Hi Folks, I've been very fond of portable software. Some of the portable programs are quite large, so to make the using fancier, I started to compress the portable applications into a WinRar SFX Archive which extracts the software to the tempdir, starts the software and afterward deletes the whole temp Dir. But it got cumbersome to manually extract the icon from the exe, make all necessary settings in the WinRar GUI - so I wrote this script. Nothing spectacular, but (in my eyes) very useful. After that, I added some other options to make it a little more versatile. Features: if we have a 32Bit and a 64Bit version, it can launch the correct Version (32Bit or 64Bit) fitting to the system the SFX is started on (contains a small exe file "universal_launcher.exe" which expects two parameters for the 32Bit.exe and 64Bit.exe, checks the current system for 64Bit and then runs the correct file). Powerbasic Sourcecode of the exe file is included, of course. automatically extracts the icon from the chosen exe and uses it as icon for the SFX if the chosen exe file has a version number in it, the version is put in the resulting SFX's filename can just extract the files to a user-chosen directory OR can just extract the files to the program files directory (and, optionally, create a desktop shortcut) OR extract the files to a temp directory and run an exe Have fun with it best regards, Marc MakeSFX v1.2.zip MakeSFXv1.3.zip
    1 point
  6. Gianni

    TSP art generator

    After reading this page, (http://www.drububu.com/illustration/tsp/index.html) I was curious and I put together this script. it is not a "stand alone" script, as it uses some third parties programs*, but in few steps it acomplish the conversion to the TSP art. The generated images are quite nice, but you have to try more attempts to find the right combinations of parameters for different source images. Best results can easily obtained with schematic black and wite images. Drag and drop for example something like in this link. Also, set the "Variable thickness line" option and try with the image at this link for another example: (https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/david-michelangelo-murphy-elliott.jpg) Since used programs generate also some temporay files, please save this script and the dependencies into a single folder so to avoid the scattering of files around and also allowing the main script to find the needed programs. Example of an TSP art generated with this script and related programs (the image on the left is converted in the image on the right) just drag and drop images on the GUI of the script and all is done automatically. * Here are the links to download the needed "dependencies": ( just put all the stuff in a single folder along with the script.) voronoi.exe http://www.drububu.com/illustration/tsp/voronoi.zip stippler.dll also contained in the above archive concorde.exe http://www.math.uwaterloo.ca/tsp/concorde/downloads/codes/cygwin/concorde.exe.gz this program needs the cygwin dll (a very nice one) (I've used 7zip to open this archive) cygwin1.dll https://cygwin.com/snapshots/ get one x86 cygwin1-xxxxxxxx.dll.xz (only dll) svg_extract.exe http://www.drububu.com/illustration/tsp/svg_extract.zip tsp2svg.exe http://www.drububu.com/illustration/tsp/tsp2svg.zip here the script: ; TSP Art generator #include <FileConstants.au3> #include <WinAPISys.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <GuiEdit.au3> #include <GDIPlus.au3> If Not _CheckDependencies() Then Exit ; can't run without dependencies. Global $bDropped, $sFile, $bDropAllowed = True ; create a blank file, or empty it if it's already created Global $hTail, $sLogFile = FileGetShortName(@ScriptDir & "\LogFile.txt") _GDIPlus_Startup() ; just for image format conversion to PNG (if needed) $Form1 = GUICreate("TSP art generator", 500, 650, -1, -1, -1, $WS_EX_ACCEPTFILES) ; --- options $Combo1 = GUICtrlCreateCombo("", 350, 505, 60, 25) GUICtrlCreateLabel("Sampling points", 415, 510, 80, 25) GUICtrlSetData($Combo1, "1000|2000|4000|6000|8000|10000|20000|40000|60000", "4000") ; some sampling rate $Checkbox1 = GUICtrlCreateCheckbox("Variable thickness line", 350, 535, 145, 25) $Checkbox2 = GUICtrlCreateCheckbox("Color (voronoi only)", 350, 565, 145, 25) ; --- Log viewer Global $hLog = GUICtrlCreateEdit("", 5, 500, 340, 145, BitOR($WS_VSCROLL, $WS_HSCROLL, $ES_AUTOVSCROLL, $ES_AUTOHSCROLL, $ES_MULTILINE, $ES_READONLY)) ; log viewer GUICtrlSetBkColor(-1, 0x000000) GUICtrlSetColor(-1, 0x00FF00) GUICtrlSetFont(-1, 9, -1, -1, "Courier New") ; following is a transparent control over the browser control ; purpose is to avoid that the drop event is captured by the browser control $hGlass = GUICtrlCreateLabel("", 0, 0, 500, 650) GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT) ; This is like a glass over the following underlying browser Control GUICtrlSetCursor(-1, 2) ; Cursor is an arrow (instead of the default I-beam) ; --- Embed a browser control Global $oIE = ObjCreate("Shell.Explorer.2") $hIE = GUICtrlCreateObj($oIE, 5, 5, 490, 490) $oIE.navigate("about:blank") AutoItSetOption("GUIOnEventMode", 1) GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit") GUIRegisterMsg($WM_DROPFILES, "WM_DROPFILES") GUISetState(@SW_SHOW, $Form1) _LogPrint(@CRLF & _ "Hello," & @CRLF & _ "Drag and dropping images here above," & @CRLF & _ "will be converted into a TSP Art." & @CRLF & _ "have fun...") ; --- Main loop While 1 $nMsg = GUIGetMsg() Select Case $nMsg = $GUI_EVENT_CLOSE _Exit() Case $bDropped = True $bDropped = False $bDropAllowed = False ; Drop not allowed while generating _Generate_PST_Art() $bDropAllowed = True EndSelect WEnd ; --- Call externa programs the right sequence Func _Generate_PST_Art() _EmptyLog() ; empty the temporary log file _checkFileFormat($sFile) ; if dropped image isn't a PNG convert it to PNG _ShowInBrowser($sFile) ; show dropped image in the browser control ; step 1) Transform PNG image into a voronoi svg image ; ============================================================================ If GUICtrlRead($Checkbox1) = $GUI_CHECKED Then ; variable thickness line? $sOptions = "" Else $sOptions = " -f " ; fixed radus EndIf If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then ; color points for voronoi? $sOptions = " -c " & $sOptions EndIf ; _call_External_Program(".\voronoi.exe " & $sOptions & "-s " & GUICtrlRead($Combo1) & " -n -I " & $sFile & " -O out.svg", True) _call_External_Program(FileGetShortName(@ScriptDir & '\voronoi.exe') & $sOptions & ' -s ' & GUICtrlRead($Combo1) & ' -n -I ' & $sFile & ' -O out.svg', True) _ShowInBrowser(FileGetShortName(@ScriptDir & "\out.svg")) ; show generated voronoi image in the browser control ; ; step 2) Extract points from the voronoi svg image and save to positions.tsp file ; for later input by the concorde TSP solver ; ============================================================================ _call_External_Program(FileGetShortName(@ScriptDir & '\svg_extract.exe') & " out.svg") _LogPrint("... going to next step ...") ; ; step 3) Resolve the Traveling Salesman Problem using the very good ; concorde.exe program (it needs the presence of the cygwin1.dll to work) ; ============================================================================ _call_External_Program(FileGetShortName(@ScriptDir & "\concorde.exe") & " -V -o tour.cyc positions.tsp", True) _LogPrint("... going to next step ...") ; ; step 3a) some adjustments to the tour.cyc file generated by concorde.exe ; ============================================================================ $hfile = FileOpen(FileGetShortName(@ScriptDir & '\tour.cyc')) Local $sContent = FileRead($hfile) FileClose($hfile) FileDelete(FileGetShortName(@ScriptDir & '\tour.cyc')) $sContent = StringReplace($sContent, Chr(0x20), Chr(0x0A)) _LogPrint("Replaced 0x20 with 0x0A " & @extended & " times.") $sContent = StringReplace($sContent, Chr(0x0A) & Chr(0x0A), Chr(0x0A)) _LogPrint("Replaced 0x0A 0x0A with 0x0A " & @extended & " times." & @CRLF) Local $x = StringInStr($sContent, Chr(0x0A)) ; first 0A $sContent = StringMid($sContent, $x + 1) ; remove first data (it's the number of points, not a point) $hfile = FileOpen(FileGetShortName(@ScriptDir & '\tour.cyc'), $FO_OVERWRITE + $FO_BINARY) FileWrite($hfile, $sContent) ; save adjusted data FileFlush($hfile) FileClose($hfile) ; ; step 4) "merge" data from out.svg and tour.cyc into the final tsp_art.svg file ; ============================================================================ If GUICtrlRead($Checkbox1) = $GUI_CHECKED Then $sOptions = " +w" ; variable thickness line Else $sOptions = "" ; fixed thickness line EndIf $sOptions = FileGetShortName(@ScriptDir & "\tsp2svg.exe") & " out.svg tour.cyc" & $sOptions _call_External_Program($sOptions) _ShowInBrowser(FileGetShortName(@ScriptDir & "\tsp_art.svg")) _LogPrint(@CRLF & _ "+-----------------------------------+" & @CRLF & _ "| End of conversion --> tsp_art.svg |" & @CRLF & _ "+-----------------------------------+" & @CRLF) EndFunc ;==>_Generate_PST_Art ; === Functions Func _call_External_Program($sCommand, $bVerbose = False) Local $sLine If $bVerbose = True Then $sCommand = @ComSpec & " /c " & $sCommand & ">>" & $sLogFile & " 2>>&1" EndIf Local $hPid = Run($sCommand, ".", @SW_HIDE) If Not $hPid Then _LogPrint("Error on run external program" & @CRLF) Return SetError(1) EndIf Do If $bVerbose Then $sLine = FileReadLine($hTail) If Not @error Then _LogPrint($sLine) EndIf EndIf Until Not ProcessExists($hPid) If $bVerbose Then $sLine = "..." ; "Task execution terminated ...." Do _LogPrint($sLine) $sLine = FileReadLine($hTail) Until @error EndIf EndFunc ;==>_call_External_Program Func _LogPrint($sLine) If StringLen(GUICtrlRead($hLog)) > 25000 Then ; Max Len of a CtrlBox is 30000 char _GUICtrlEdit_SetText($hLog, StringRight(GUICtrlRead($hLog), 20000)) ; short the content of CtrlBox to 20000 char EndIf _GUICtrlEdit_AppendText($hLog, $sLine & @CRLF) EndFunc ;==>_LogPrint Func WM_DROPFILES($hWnd, $iMsg, $wParam, $lParam) If $bDropAllowed Then Local $sExt = ".bmp|.png|.jpg|.gif" ; img drop filtering thanks to @UEZ Local $aFileList = _WinAPI_DragQueryFileEx($wParam) If Not @error Then For $i = 1 To $aFileList[0] If StringInStr($sExt, StringRegExpReplace($aFileList[$i], ".*(\.+)", "$1")) Then $bDropped = True $sFile = FileGetShortName($aFileList[$i]) ExitLoop EndIf Next Else _LogPrint("Error on drop" & @CRLF) EndIf _WinAPI_DragFinish($wParam) _LogPrint("Droped: " & $sFile & @CRLF) Return 0 EndIf EndFunc ;==>WM_DROPFILES Func _ShowInBrowser($sImg) ; setup Javascript engine with also embeded the "entity" library If StringRight($sImg, 3) = "svg" Then Else EndIf ; *** create a minimal 'html' page listing for the browser control Local $sHTML = "<HTML><HEAD>" & @CRLF & _ "<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" />" & @CRLF & _ "</HEAD>" & @CRLF & _ "<body>" & @CRLF & _ '<img src="' & $sImg & '" style="width:100%; height:100%;" />' & @CRLF & _ "</body>" & @CRLF & _ "</HTML>" & @CRLF ; html closing tags ; *** end of html page listing ; _LogPrint(">_" & @CRLF) $oIE.navigate('about:blank') While Not String($oIE.readyState) = 'complete' ; wait for about:blank Sleep(100) WEnd $oIE.document.Write($sHTML) ; inject lising directly to the HTML document: $oIE.document.close() ; close the write stream Sleep(1000) $oIE.document.execCommand("Refresh") EndFunc ;==>_ShowInBrowser Func _checkFileFormat($sFile) Local $hImage = _GDIPlus_ImageLoadFromFile($sFile) Local $aFormat = _GDIPlus_ImageGetRawFormat($hImage) If $aFormat[1] <> "PNG" Then _ConvertToPNG($hImage) _GDIPlus_ImageDispose($hImage) EndFunc ;==>_checkFileFormat Func _ConvertToPNG(ByRef $hImage) Local $CLSID = _GDIPlus_EncodersGetCLSID('PNG') $sFile = FileGetShortName(@ScriptDir & "\Input.png") _GDIPlus_ImageSaveToFileEx($hImage, $sFile, $CLSID) EndFunc ;==>_ConvertToPNG Func _EmptyLog() FileClose($hTail) $hTail = FileOpen($sLogFile, $FO_OVERWRITE) FileWrite($hTail, "Start log: " & @YEAR & '/' & @MON & '/' & @MDAY & ' ' & @HOUR & ':' & @MIN & ':' & @SEC & @CRLF) FileFlush($hTail) FileClose($hTail) $hTail = FileOpen($sLogFile) ; read only EndFunc ;==>_EmptyLog Func _CheckDependencies() Local $iDependencie = 0 $iDependencie += FileExists(@ScriptDir & "\voronoi.exe") ; http://www.drububu.com/illustration/tsp/voronoi.zip $iDependencie += FileExists(@ScriptDir & "\stippler.dll") ; " also contained in the above archive $iDependencie += FileExists(@ScriptDir & "\concorde.exe") ; http://www.math.uwaterloo.ca/tsp/concorde/downloads/codes/cygwin/concorde.exe.gz $iDependencie += FileExists(@ScriptDir & "\cygwin1.dll") ; get one from here https://cygwin.com/snapshots/ get cygwin1-xxxxxxxxx.dll.xz $iDependencie += FileExists(@ScriptDir & "\svg_extract.exe") ; http://www.drububu.com/illustration/tsp/svg_extract.zip $iDependencie += FileExists(@ScriptDir & "\tsp2svg.exe") ; http://www.drububu.com/illustration/tsp/tsp2svg.zip Return $iDependencie = 6 EndFunc ;==>_CheckDependencies Func _Exit() _GDIPlus_Shutdown() FileClose($hTail) AutoItSetOption("GUIOnEventMode", 0) GUIRegisterMsg($WM_DROPFILES, "") Exit EndFunc ;==>_Exit
    1 point
  7. Found a visual basic script online which searches for, downloads, and installs all available Windows updates available for the current operating system. It also lets you choose the "source" you obtain the updates from. I wanted to convert it over to autoit and share, as this was the only missing piece in my automated os deployment script, which is now complete.. Note that you will need attached udf for script to work. The original vbscript can be found here. All credit goes to author of original script. #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_SaveSource=y #AutoIt3Wrapper_Res_Language=1033 #AutoIt3Wrapper_Res_requestedExecutionLevel=highestAvailable #AutoIt3Wrapper_Add_Constants=n #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.15.0 (Beta) Author: myName Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here ;ServerSelection values #include <console.au3> $ssDefault = 0 $ssManagedServer = 1 $ssWindowsUpdate = 2 $ssOthers = 3 $intSearchStartChar = 1 Local $strTitle Cout ( "searching for updates..." & @CRLF ) $updateSession = ObjCreate("Microsoft.Update.Session") $updateSearcher = $updateSession.CreateupdateSearcher() $updateSearcher.ServerSelection = $ssWindowsUpdate $searchResult = $updateSearcher.Search("IsInstalled=0 and Type='Software'") cout ( "List of applicable items on the machine:" & @CRLF & @CRLF ) For $i = 0 to Int ( $searchResult.Updates.Count ) - 1 Step 1 $update = $searchResult.Updates.Item($i) cout ( ( $i + 1 ) & ". " & $update.Title & @CRLF ) Next If Int ( $searchResult.Updates.Count ) = 0 Then cout ( "There are no applicable updates." & @CRLF ) Exit EndIf cout ( "Creating collection of updates to download:" & @CRLF & @CRLF ) $updatesToDownload = ObjCreate("Microsoft.Update.UpdateColl") For $i = 0 to Int ( $searchResult.Updates.Count ) - 1 Step 1 $update = $searchResult.Updates.Item($i) $addThisUpdate = false If $update.InstallationBehavior.CanRequestUserInput = true Then cout ( $i + 1 & ". skipping: " & $update.Title & " because it requires user input" & @CRLF ) Else If $update.EulaAccepted = false Then $update.AcceptEula() $addThisUpdate = true Else $addThisUpdate = True EndIf EndIf If $addThisUpdate = true Then cout ( ( $i + 1 ) & ". adding: " & $update.Title & @CRLF ) $updatesToDownload.Add($update) EndIf Next If $updatesToDownload.Count = 0 Then cout ( "All updates were skipped" & @CRLF ) Exit EndIf Cout ( "Would you like to download available updates? (Y/N)" & @CRLF ) $input2 = Getch () If $input2 <> "y" And $input2 <> "Y" Then Cout ( "Either invalid input was entered or you chose not to install. Exiting.." & @CRLF ) Exit Else cout ( "Downloading updates..." & @CRLF ) $downloader = $updateSession.CreateUpdateDownloader() $downloader.Updates = $updatesToDownload $downloader.Download() $updatesToInstall = ObjCreate ("Microsoft.Update.UpdateColl") $rebootMayBeRequired = false cout ( "Successfully downloaded updates:" & @CRLF & @CRLF ) For $i = 0 to Int ( $searchResult.Updates.Count ) - 1 Step 1 $update = $searchResult.Updates.Item($i) If $update.IsDownloaded = true Then cout ( ( $i + 1 ) & ". " & $update.Title & @CRLF ) $updatesToInstall.Add($update) If Int ( $update.InstallationBehavior.RebootBehavior ) > 0 Then $rebootMayBeRequired = true EndIf EndIf Next If $updatesToInstall.Count = 0 Then cout ( "No updates were successfully downloaded." & @CRLF ) Exit EndIf If $rebootMayBeRequired = true Then cout ( "These updates may require a reboot." & @CRLF ) EndIf Cout ( "Would you like to install updates now? (Y/N)" & @CRLF ) $input = Getch ( ) If $input <> "y" And $input <> "Y" Then Cout ( "Either invalid input was entered or you chose not to install. Exiting.." & @CRLF ) Exit Else Cout ( "Installing updates..." & @CRLF ) $installer = $updateSession.CreateUpdateInstaller() $installer.Updates = $updatesToInstall $installationResult = $installer.Install() cout ( "Installation Result: " & $installationResult.ResultCode & @CRLF ) Cout ( "Reboot Required: " & $installationResult.RebootRequired & @CRLF ) Cout ( "Listing of updates installed and individual installation results:" & @CRLF & @CRLF ) For $i = 0 to Int ( $updatesToInstall.Count ) - 1 step 1 Cout ( ( $i + 1 ) & ". " & $updatesToInstall.Item($i).Title & ": " & $installationResult.GetUpdateResult($i).ResultCode & @CRLF ) Next EndIf EndIf Console.au3
    1 point
  8. Hello. I have not time to see too much. But base in RTFC's first post This could be a start... Local $hHandle = DllCallbackRegister("_PFMIFSCALLBACK", "long", "long;dword;ptr") Local $pCallBack = DllCallbackGetPtr($hHandle) DllCall("yourdll.ll", "none", "FormatEx", "dword", $MediaFlag, "wstr", $Format, "wstr", $Label, "bool", $QuickFormat, "dword", $ClusterSize, "ptr", $pCallBack) DllCallbackFree($hHandle) Func _PFMIFSCALLBACK($Command, $SubAction, $ActionInfo) EndFunc ;==>_PFMIFSCALLBACK Saludos
    1 point
  9. You have to set up a dll CallBack for this to work. If you're familiar with PowerBasic, here's a source code example you might be able to adapt. AFAIK, there's no existing AutoIt source code for this particular function on the forums. But someone else may have something lying around, if you're lucky.
    1 point
  10. Did you try my previous code ? a little adaptation gives this (based precisely on the provided requirements) : $txt = FileRead("1.txt") $out = "items4" $new = StringRegExpReplace($txt, '(?m)^.*\Q' & $out & '\E.*$', "") FileWrite("new.txt", $new)
    1 point
  11. Skysnake, As I said to another poster just above, if you want to ask questions which do not specifically involve this UDF then please post in the open forum and leave this thread uncluttered. As neither of your posts above fall into this category I will be removing them shortly, as well as this rejoinder. M23 Edit: But here is how you can use the UDF to have a column (2) which uses a combo to limit user edit options and a right-click menu to select the colour of another column (1) of the selected row. Not terribly difficult after all: #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <AutoItConstants.au3> #include <StaticConstants.au3> #include <UpDownConstants.au3> #include <EditConstants.au3> #include <File.au3> #include <Misc.au3> #include <String.au3> #include <Array.au3> #include "GUIListViewEx.au3" Global $iYellow = "0xFFFF00", _ $iLtBlue = "0xCCCCFF", _ $iGreen = "0x00FF00", _ $iBlack = "0x000000", _ $iRed = "0xFF0000", _ $iBlue = "0x0000FF", _ $iWhite = "0xFFFFFF" Global $sRet $hGUI = GUICreate("Coloured ListView Example", 500, 300) ; Create ListView $cLV = GUICtrlCreateListView("Column 0|Colourable|Editable|Column 3", 10, 10, 480, 260, BitOR($LVS_SINGLESEL, $LVS_SHOWSELALWAYS)) For $i = 0 To 3 _GUICtrlListView_SetColumnWidth($cLV, $i, 100) Next ; Initiate ListView = user colours $iLVIndex = _GUIListViewEx_Init($cLV, "", 0, 0, True, 32) ; Set deafult colours to use Global $aDefCols[4] = ["0x000000", "0xFEFEFE", "0xFFFFFF", "0x0000FF"] _GUIListViewEx_SetDefColours($iLVIndex, $aDefCols) ; Set column edit status _GUIListViewEx_SetEditStatus($iLVIndex, 2, 2, "1|2|3", True) ; 2 = Read-only combo ; If colours used then this function must be run BEFORE GUISetState _GUIListViewEx_MsgRegister() GUISetState() ; Create array and fill listview Global $aLVArray[6][4] For $i = 0 To 5 $sData = "Item " & $i & "-0" $aLVArray[$i][0] = $sData For $j = 1 To 3 $sData &= "|SubItem " & $i & "-" & $j $aLVArray[$i][$j] = "SubItem " & $i & "-" & $j Next _GUIListViewEx_InsertSpec($iLVIndex, 0, $sData) Next ; Create context menu for native ListView $mContextmenu = GUICtrlCreateContextMenu($cLV) $mWhtTxt = GUICtrlCreateMenuItem("White text", $mContextmenu) $mYelTxt = GUICtrlCreateMenuItem("Yellow text", $mContextmenu) $mBluTxt = GUICtrlCreateMenuItem("Cyan text", $mContextmenu) $mGrnTxt = GUICtrlCreateMenuItem("Green text", $mContextmenu) $mBlkTxt = GUICtrlCreateMenuItem("Black text", $mContextmenu) GUICtrlCreateMenuItem("", $mContextmenu) $mWhtFld = GUICtrlCreateMenuItem("White field", $mContextmenu) $mRedFld = GUICtrlCreateMenuItem("Red field", $mContextmenu) $mBluFld = GUICtrlCreateMenuItem("Blue field", $mContextmenu) $mGrnFld = GUICtrlCreateMenuItem("Green field", $mContextmenu) $mBlkFld = GUICtrlCreateMenuItem("Black field", $mContextmenu) GUICtrlCreateMenuItem("", $mContextmenu) $mDefTxt = GUICtrlCreateMenuItem("Default txt", $mContextmenu) $mDefFld = GUICtrlCreateMenuItem("Default field", $mContextmenu) $mDefBoth = GUICtrlCreateMenuItem("Default both", $mContextmenu) While 1 $iMsg = GUIGetMsg() Switch $iMsg Case $GUI_EVENT_CLOSE Exit Case $mWhtTxt To $mDefBoth ; Check context menu items _SetColour($iMsg) EndSwitch $vRet = _GUIListViewEx_EventMonitor() WEnd Func _SetColour($iCID) ; Get information on where last right click occurred within ListView Local $aContext = _GUIListViewEx_ContextPos() ; Set new colour required Local $sColSet = "", $aColArray, $aSplit, $fDef = False Switch $iCID Case $mWhtTxt $sColSet = $iWhite & ";" ; Text colour followed by ";" Case $mYelTxt $sColSet = $iYellow & ";" Case $mBluTxt $sColSet = $iLtBlue & ";" Case $mGrnTxt $sColSet = $iGreen & ";" Case $mBlkTxt $sColSet = $iBlack & ";" Case $mWhtFld $sColSet = ";" & $iWhite ; Field colour preceded by ";" Case $mRedFld $sColSet = ";" & $iRed Case $mBluFld $sColSet = ";" & $iBlue Case $mGrnFld $sColSet = ";" & $iGreen Case $mBlkFld $sColSet = ";" & $iBlack Case $mDefTxt ; Get current colours $aColArray = _GUIListViewEx_ReturnArray($aContext[0], 2) ; Extract current colours $aSplit = StringSplit($aColArray[$aContext[1]][$aContext[2]], ";") ; Create required setting $sColSet = ";" & $aSplit[2] ; Set default flag $fDef = True Case $mDefFld $aColArray = _GUIListViewEx_ReturnArray($aContext[0], 2) $aSplit = StringSplit($aColArray[$aContext[1]][$aContext[2]], ";") $sColSet = $aSplit[1] & ";" $fDef = True Case $mDefBoth $sColSet = ";" EndSwitch If $sColSet Then ; Reset to default if needed If $fDef Then _GUIListViewEx_SetColour($aContext[0], ";", $aContext[1], 1) EndIf ; Set required item colour _GUIListViewEx_SetColour($aContext[0], $sColSet, $aContext[1], 1) EndIf EndFunc
    1 point
  12. Melba23

    Logic Error

    tbohon, GUICtrlGetState can return a mixture of states - in this case you also get a $GUI_VISIBLE state as well as the $GUI_ENABLE/DISABLE state. So you need to use BitAND to check if the correct bits are set: #include <GUIConstantsEx.au3> $Form1 = GUICreate("My First AutoIT Project (in a long time)", 623, 449, -1, -1) $Label1 = GUICtrlCreateLabel("Click the button ---> ", 135, 88, 218, 33) $Label2 = GUICtrlCreateLabel("You clicked me!!!!!", 202, 208, 218, 44) GUICtrlSetState(-1, $GUI_DISABLE) $Button1 = GUICtrlCreateButton("Click me!", 383, 80, 105, 49) $Button2 = GUICtrlCreateButton("Exit", 544, 400, 57, 33) GUISetState(@SW_SHOW) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $Button1 If BitAND(GUICtrlGetState($Label2), $GUI_ENABLE) Then GUICtrlSetState($Label2, $GUI_DISABLE) Else GUICtrlSetState($Label2, $GUI_ENABLE) EndIf Case $Button2 Exit EndSwitch WEnd Please ask if you have any questions. M23
    1 point
  13. wakillon

    Fifteen Game Autoit

    Good work Thanks
    1 point
  14. Fabio_iGames

    Fifteen Game Autoit

    You're here ... teacher Very good. You are amazing.
    1 point
  15. I know I disappointed some of you guys with this version as you were waiting for the requested features like Sliders, InputBox, Support for tabbing through controls and other stuff. I spent a lot of time for other improvements and got tired of trying to find ways to get stuff to work I tried adding many other things like fully transparent controls, but ended up building in so many workarounds and it still didn't fully work as I wanted to.. I know there are examples for sliders etc. but it gets too complicated and too time consuming when trying to build it into the UDF for easy usage. These are the things on my ToDo List at the moment but I can't tell if or when I will built them in. Windows 10 Style Sliders (Like the volume slider) Some sort of modern looking tab/menu. Simple Inputbox (low prio) Support for tabbing through controls Maybe someone is interested in helping out
    1 point
×
×
  • Create New...