Page 1 of 1

Scripting: new function "random(low, high)"

Posted: 12 Mar 2010 00:32
by Stefan
I want to request random() as new script function.

Code:
http://www.vbexplorer.com/VBExplorer/ra ... bers_1.asp
Public Function Rand(ByVal Low As Long, ByVal High As Long) As Long
   Randomize
   Rand = Int((High - Low + 1) * Rnd) + Low
End Function


http://www.vb-seminar.de/vb_17.htm
Function Zufallszahl(ByVal min, ByVal max)
  Randomize 'Zufallsgenerator initialisieren
  z = Rnd 'Zufallszahl (liegt zwischen 0 und 1)
  Zufallszahl = Int(min + (max - min + 1) * z)
End Function



I want to rename (or create) files with random name:
$len = rand(1, "<ss>");
while ($len>0){
  $rand = rand(1,26);
  $char = substr("abcdefghijklmnopqrstuvwxyz", $rand, 1);
  $name = $name . $char;
incr $len, -1;
}
or create an GUID.


I want to create files with random size:
$base = "<hhss>";
$size = rand($base , $base * $base);
While($len<$size){
  $content = $content . "a";
  IF ($width>71){$content = $content . "<crlf>", $width= }
incr $width;
incr $len;
}


An use would be too to pick an random file:
$rand = rand(1, $filecount);
  $copyfile = gettoken($filelist, $rand);

or pick an random amount of files. rand(20, 25);

Re: Scripting: new function "random(low, high)"

Posted: 12 Mar 2010 01:28
by TheQwerty
For that use I think I'd prefer to see a function that calls GetTempFileName.
GetTempFileName Function

Creates a name for a temporary file. If a unique file name is generated, an empty file is created and the handle to it is released; otherwise, only a file name is generated.

Re: Scripting: new function "random(low, high)"

Posted: 14 Mar 2010 20:41
by Stefan

Code: Select all

v8.90.0003 - 2010-03-14 18:35
 [...]
    + Scripting got a new function.
      Name:   rand
      Action: Generates an integer random number.
      Syntax: rand([low=0], [high=1])
        low:    the lowest value to return (default: 0)
        high:   the highest value to return (default: 1)
                should be same or higher than low
        return: random number
      Examples:
        echo rand(); //returns 0 or 1
        echo rand(2, 4); //returns 2 or 3 or 4
        echo rand(-1, 1); //returns -1 or 0 or 1
 [...]
Many thanks Don.

I have added the rand() function into one of my currently 'work in process' scripts.
Works fine for me with first test, but please note that i am not an coder, so use this script on test files only.

ROT13.xys

Code: Select all

//http://en.wikipedia.org/wiki/ROT13

"Encode string with ROT5 (digits)"
   global $func_ROT5, $string;
   $string = input("ROT5","String to encode:", "<curname>");
   sub "_func_ROT5";
   text $func_ROT5;
 
"Encode string with ROT13 (chars)"
   global $func_ROT13, $string;
   $string = input("ROT13","String to encode:", "<curname>");
   sub "_func_ROT13";
   text $func_ROT13;
   
"Encode string with ROT18 (digits + chars)"
   global $func_ROT5, $func_ROT13, $string;
   $string = input("ROT18","String to encode:", "<curname>");
   sub "_func_ROT5";
   $string = $func_ROT5;
   sub "_func_ROT13";
   text $func_ROT13;
 
"TODO: Encode string with ROT47 (all signs)"
    
-
    
"TEST: Rename curbase with ROT18 (chars & digits)"
   global $func_ROT5, $func_ROT13, $string;

   $seletedFiles = getinfo("SelectedItemsPathNames", "|");
   $count = 1;
   while(1)
   {
     $curname = gettoken($seletedFiles, $count, "|");
     end ($curname=="");
 
     //$path  = regexreplace($curname, "^(.*\\)(.*)$", "$1");
     $string  = regexreplace($curname, "^(.*\\)(.*)$", "$2");
 
     sub "_func_ROT5"; 
     $string = $func_ROT5;
     sub "_func_ROT13";
     rename , "$func_ROT13 /e", , $curname;
   incr $count;
   }
-
"TEST: Rand test (randomize string)"
   $string = input("RAND Test","String to scrample:", "<curname>");
   $len = strlen($string);
   $out = "";

   while ($len>2){
     $rand = rand(1,26);
     $char = substr("abcdefghijklmnopqrstuvwxyz", $rand, 1);
     $out = $out . $char;
   incr $len, , -1;
   }
   //step;
   $out = regexreplace($out, "(.*)(...)", "$1.$2");
   $rand = rand(1,21);
   $char = substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", $rand, 1); 
   $out = $char$out;
   text $string<crlf>$out;
 

"TEST: Rand test (rename files randomize)"
   $seletedFiles = getinfo("SelectedItemsPathNames", "|");
   $count = 1;
   while(1)
   {
     $curname = gettoken($seletedFiles, $count, "|");
     end ($curname=="");
 
     //$path  = regexreplace($curname, "^(.*\\)(.*)$", "$1");
     $string  = regexreplace($curname, "^(.*\\)(.*)$", "$2");
  
     $len = strlen($string);
     $out = "";

     while ($len>2){
       $rand = rand(1,26);
       $char = substr("abcdefghijklmnopqrstuvwxyz", $rand, 1);
       $out = $out . $char;
     incr $len, , -1;
     }
     //step;
     $out = regexreplace($out, "(.*)(...)", "$1.$2");
     $rand = rand(1,21);
     $char = substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", $rand, 1); 
     $out = $char$out;
     //text $string<crlf>$out;
     rename , "$out /e", , $curname;
   incr $count;
   }


//====================================
"_func_ROT13"
   global $func_ROT13, $string;
   $count = 0;
   $func_ROT13 = "";
   while(1)
   {
     $char = substr($string, $count, 1);
     If ($char=="")
     {
       break;
     }else{
       $asc = asc("$char");

       $check = 0;
       //chars:
       IF ($check==0){IF ($asc > 64  && $asc < 78 ){$asc = $asc + 13; $check=1;}}
       IF ($check==0){IF ($asc > 77  && $asc < 91 ){$asc = $asc - 13; $check=1;}}
       IF ($check==0){IF ($asc > 96  && $asc < 110){$asc = $asc + 13; $check=1;}}
       IF ($check==0){IF ($asc > 109 && $asc < 123){$asc = $asc - 13; $check=1;}}
       $char = chr($asc);
   
       $func_ROT13 = $func_ROT13$char;
     incr $count;
     }
   }
   //text $func_ROT13;
 

"_func_ROT5"
   global $func_ROT5, $string;
   $count = 0;
   $func_ROT5 = "";
   while(1)
   {
      $char = substr($string, $count, 1);
      If ($char=="")
      {
        break;
      }else{
        $asc = asc("$char");

        $check = 0;
        //digits:
        IF ($check==0){IF ($asc > 47  && $asc < 53 ){$asc = $asc + 5; $check=1;}}
        IF ($check==0){IF ($asc > 52  && $asc < 58 ){$asc = $asc - 5; $check=1;}}
        $char = chr($asc);
   
        $func_ROT5 = $func_ROT5$char;
      incr $count;
      }
   }
   //text $func_ROT5;
 
 
//==================================== 
-
"Edit this &script : edit"
   self $ScriptFile, file;
   OpenWith "<xypath>\Tools\NotePad2\Notepad2.exe", ,$ScriptFile;

Re: Scripting: new function "random(low, high)"

Posted: 14 Mar 2010 21:17
by Stefan
Create GUIDs

Code: Select all

"_Pseudo-GUID"
 /*
 http://de.wikipedia.org/wiki/Globally_Unique_Identifier
 
 GUIDs haben das Format {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}, 
 wobei jedes 'X' für ein Zeichen aus dem Hexadezimalsystem steht 
 und damit eine Ziffer 0-9 oder ein Buchstaben A-F sein kann - 
 Beispiel {936DA01F-9ABD-4D9D-80C7-02AF85C822A8}.
 */

 /*
 http://en.wikipedia.org/wiki/Globally_unique_identifier

 A globally unique identifier or GUID is a unique reference number used as an identifier in computer software. 
 The term GUID also is used for Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

 The value of a GUID is represented as a 32-character hexadecimal string, 
 such as {21EC2020-3AEA-1069-A2DD-08002B30309D},
 The total number of unique keys is 2128 or 3.4×1038 — roughly 2 trillion per cubic millimeter of the entire volume of the Earth. 
 This number is so large that the probability of the same number being generated twice is extremely small.

 V4 GUIDs use a pseudo-random number and can be identified by the digit "4" in the first position of the third group of digits,

         8   -  4   -   4  -  4   -   12
 3F2504E0-4F89-41D3-9A0C-0305E82C3301
 21EC2020-3AEA-4069-A2DD-08002B30309D

 Please note that my algorithm used here is not the best to create really unique GUIDs (as far as i understand this)
 */


$stock = "8BC3F01D542A67E9"; //"ABCDEF0123456789";
   $out = "";
   $len = 0;
   while ($len<8){$rand = rand(0,15);$sign = substr($stock, $rand, 1);$out=$out$sign; incr $len;}
   $out = $out . "-";
   
   $len = 0;
   while ($len<4){$rand = rand(0,15);$sign = substr($stock, $rand, 1);$out=$out$sign; incr $len;}
   $out = $out . "-";
   
   $len = 0; 
   $out = $out . "4";  // V4 GUIDs
   while ($len<3){$rand = rand(0,15);$sign = substr($stock, $rand, 1);$out=$out$sign; incr $len;}
   $out = $out . "-";
   
   $len = 0; 
   while ($len<4){$rand = rand(0,15);$sign = substr($stock, $rand, 1);$out=$out$sign; incr $len;}
   $out = $out . "-";
   
   $len = 0;
   while ($len<12){$rand = rand(0,15);$sign = substr($stock, $rand, 1);$out=$out$sign; incr $len;}
   
   msg "{" . $out . "}";


/*

Output looks like:

{CA0731C8-11B1-4206-D9D0-CE3E80CAB752}
{315C77D3-C0EE-4B99-07AD-D12DA2469953}
{1EED2D20-CA29-4921-4112-D914A627C3B4}
{B2ECBC53-E9BC-4B2B-9217-F14DA90E5340}
{EC53D406-B59F-4D33-AD11-7243F27ABEFA}


*/

Much more better then my last trials tests:
//Random GUID
$random = (<date yyyymmddhhmmss> * <date ss>) + (<date yyyymmdd> * <date mmss>);
  $GUID = substr($random, <date ss>, 2);
  $RndC = substr("abcdefghklnrstuvwxzabcdefghklnrstuvwxzabcdefghklnrstuvwxzabcd", "<date ss>", 1);
  $GUID = $GUID . $RndC;


Whereas this works good:
//Random numbers
$random = (<date yyyymmddhhmmss> * <date ss>) + (<date yyyymmdd> * <date mmss>);
  substr $random, $random, 0, 16; //length of output
  msg $random;

Re: Scripting: new function "random(low, high)"

Posted: 14 Mar 2010 21:38
by Stefan
GetTempFileName Function
Random file name or string, (version 0.1)

RandomFileName.xys

Code: Select all

"_RandomFileName"
$stock = "aAbB8cCd6DeE7fFg9GhH3iIj5JkKl4LmMn1NoOpPq2QrRs0StTuUvVwWxXyYzZ";
   $out = "";
   while ($len<9){
       $rand = rand(1,62);
           $sign = substr($stock, $rand, 1);
               $out=$out$sign; incr $len;
   }


  //output:  $out looks like "lJ2l1gZHU"

  //compose an file name:
  //$IniFile = "%tmp%\XY_" . $out . "_" . <datem yyyymmddhhmmss> . ".ini"; 
  //or just
  $IniFile = "%tmp%\XY_" . $out . ".ini"; 

  //test this:
  msg  $IniFile ;

  //real use would be e.g.:
  //writefile($IniFile, data, [on_exist], [mode])
  
/*

Our test output msg looks like:

    ---------------------------
            XYplorer
    ---------------------------
    C:\<your path to %temp%>\Temp\XY_lJ2l1gZHU.ini
    ---------------------------
              OK   
    ---------------------------

*/


GetTempFileName Function
Random file name or string, (version 0.2)

Random_Strings.xys

Code: Select all

   $out = "";

   while ($len<10)
   {
    $rand = rand(1,3);

    If ($rand==1)
      {
      $rand = rand(65,90); //A-Z
           $sign = chr($rand);
      }
    If ($rand==2)
      {
      $rand = rand(48,57); //0-9
           $sign = chr($rand);
      }
    If ($rand==3)
      {
      $rand = rand(97,122); //a-z
           $sign = chr($rand);
       }
    If (strpos($out, $sign, , 1) == -1) //unique signs only
      {    
       $out=$out$sign; 
       incr $len; 
      }
   }

  // $out is something like: "V9D2OQRw5d"

  //test this:
  msg "C:\temp\XY_$out.txt";



/*
 
  Our test output looks like:

    ---------------------------
          XYplorer
    ---------------------------
    C:\temp\XY_4gRJvQ143R.txt      //not unique signs
    ---------------------------
              OK   
    ---------------------------


    ---------------------------
          XYplorer
    ---------------------------
    C:\temp\XY_V9D2OQRw5d.txt       //unique signs only
    ---------------------------
              OK   
    ---------------------------

*/
GetTempFileName Function
Random file name or string, (version 0.3)
This script provides an output which looks exactly as the VBScript GetTempName does:

Code: Select all


   $GetTempName = "";
   while ($len<5)
   {$rand = rand(1,2);
    If ($rand==1)
       {$rand = rand(65,70); //A-F
        $sign = chr($rand);}
    If ($rand==2)
       {$rand = rand(48,57); //0-9
        $sign = chr($rand);}
    $GetTempName=$GetTempName$sign;
    $len++;}
    $GetTempName = "rad$GetTempName.tmp";

    text   $GetTempName;


/*
The output looks like one of this:

          radD7C8B.tmp
          rad58708.tmp
          radE9ECD.tmp
          radC82C6.tmp
          rad3BAFD.tmp
          radEDCEB.tmp

Whereas the output of the Visual Basic Script version looks like this:

  set FSO = CreateObject("scripting.filesystemobject")
  For i = 1 to 10
      a = a & FSO.GetTempName & vbcrlf
  next
  msgbox a

  'radBFAF3.tmp
  'rad7EB2F.tmp
  'rad41214.tmp
  'radEA4A1.tmp
  'rad4B340.tmp
  'rad32084.tmp
  'rad1D014.tmp
  'radC7606.tmp
  'radE4BA4.tmp
  'rad3C1FE.tmp
  'rad0B862.tmp

*/

///////////////////////////

//BTW we can create ten strings on the fly whit XYplorer too:

/*

 $a="";
   while($i < 10)
   {
   //--------------------------------

         $GetTempName = "";
         while ($len<5)
         {$rand = rand(1,2);
          If ($rand==1)
             {$rand = rand(65,70); //A-F
              $sign = chr($rand);}
          If ($rand==2)
             {$rand = rand(48,57); //0-9
              $sign = chr($rand);}
          $GetTempName=$GetTempName$sign;
          $len++;}
          $GetTempName = "rad$GetTempName.tmp";
         // text   $GetTempName; 



    $a = "$a$GetTempName<crlf>";
    $len=0;
    
    
   //--------------------------------
    $i++;
   }
   
   text $a;

/*
Gives us:
radB6D63.tmp
radFB621.tmp
rad9424C.tmp
radBC714.tmp
rad39BCE.tmp
radC320E.tmp
rad065D4.tmp
rad4A11A.tmp
radECFDB.tmp
radCB8DF.tmp
*/

*/



Random_WLAN.xys

Code: Select all

//PSK (Pre-Shared-Keys) WLAN WEP WPA WPA2 EAP key
/*
HEX Format:
a-f 97-102
A-F 65-70
0-9 48-57
64 Bit (10 signs) 165F765A7C
128 Bit (26 signs) 7469BC7668ADDA3472EE76486D
*/
   $WLANHEXkey = "";
   while ($len<26) 
   {
      $rand = rand(1,3);
      If ($rand==1)
      {
      $rand = rand(65,70); //A-F
           $sign = chr($rand);
       }
      If ($rand==2)
      {
      $rand = rand(48,57); //0-9
           $sign = chr($rand);
      }
      If ($rand==3)
      {
      $rand = rand(97,102); //a-f
           $sign = chr($rand);
       }

     $WLANHEXkey = $WLANHEXkey$sign; 
     incr $len; 

   }

  //test this:
  msg "My 126-bit WLAN HEX key: $WLANHEXkey";


/*

   Our test output looks like:

    ---------------------------
            XYplorer
    ---------------------------
    My 126-bit WLAN HEX key: f35Be78f3afC1fbc2cEa58a94e
    ---------------------------
                OK   
    ---------------------------
*/



////////////////////////////////////////////////////////////////


/*
ASCII Format:
a-z 97-122
A-Z 65-90
0-9 48-57
64 Bit (5 signs) A5d64
128 Bit (13 signs) 67a5G785hrsT7
*/


   $len=0;
   $WLAN_ASCIIkey = "";
   while ($len<13) 
   {
      $rand = rand(1,3);
      If ($rand==1)
      {
      $rand = rand(65,90); //A-Z
           $sign = chr($rand);
       }
      If ($rand==2)
      {
      $rand = rand(48,57); //0-9
           $sign = chr($rand);
      }
      If ($rand==3)
      {
      $rand = rand(97,122); //a-z
           $sign = chr($rand);
       }
    If (strpos($WLAN_ASCIIkey, $sign, , 1) == -1)  //unique
    {    
     $WLAN_ASCIIkey = $WLAN_ASCIIkey$sign; 
    incr $len; 
    }
   }
    
  //Test:
  msg "My 126-bit WLAN ASCII key: $WLAN_ASCIIkey";

/*

   Our test output looks like:

    ---------------------------
            XYplorer
    ---------------------------
    My 126-bit WLAN ASCII key: 0LO1Xl2IJs9ex
    ---------------------------
              OK   
    ---------------------------
*/



Random_Password.xys

Code: Select all

$c=1;
   $Password = "";
   $colPassword = "";
   while($c < 10)
   { 

     while ($len<8) 
     {
        $rand = rand(1,3);
        If ($rand==1)
        {
        $rand = rand(65,90); //A-Z
             $sign = chr($rand);
         }
        If ($rand==2)
        {
        $rand = rand(48,57); //0-9
             $sign = chr($rand);
        }
        If ($rand==3)
        {
        $rand = rand(97,122); //a-z
             $sign = chr($rand);
         }
      If (strpos($Password, $sign, , 1) == -1)  //unique
      {    
       $Password = $Password$sign; 
      incr $len; 
      }
     }

   $colPassword = $colPassword . "$c. $Password<crlf>";  //with leading number
   //$colPassword = $colPassword . "$Password<crlf>";    //without number in output
   $Password = "";
   $len = 0;
   $c++;
   }

  //an password would look like: n3K2vIaF

  //test this:
   text "Chose one password:<crlf 2>$colPassword";


/*

  Our test output looks like:

      =====================
      Chose one password:

      1. aF6tEr3V
      2. n3K2vIaF
      3. Ly0rA62T
      4. n28w9qyI
      5. k0UK7f96
      6. Q0ec54pr
      7. Ro1E4NWk
      8. K3RS5G7Z
      9. lLqC5gHy
      =====================
*/




Random Passwords english words.xys

Code: Select all


///////////////////////////////////////////////////////////////////////////////
/*

Create password from real english words so they can be better memorized.



First we need an list of word, 
this was the first result from Google:


Kevin's Word List Page
http://wordlist.sourceforge.net/

Ispell English Word Lists
This package contains the contents of the Ispell (ver 3.1.20) word list 
after being expand from there affix compressed form used by Ispell.
readme, tar.gz, zip (0.4 MB) 



Download and Unpack the "ispell-enwl-3.1.20.ZIP"
and edit the file "english.0"  (rename to english.txt if you want)


Then i have edit this file english.0  to remove unwanted names.
I want only words 5 chars long. You can do this better then i have done, i show just the basics.





To edit the file i use the freeware editor NotePad2 from
http://www.flos-freeware.ch/notepad2.html 


Download Notepad2 4.x Program Files (x86) [280 KB]
Unpack and run "NotePad2.exe"


Then i do several regex search&replace action.
(again: you may do something better then me)


Search     > Replace with      // description

^..$       > nothing           //remove two char words if any
^...$      > leave             //remove three char words
^....$     > replace with      //remove four char words
^.......*$ > empty             //remove six and more char words
.+'.+      >                   //remove ma'am, can't, don't,...


Then press
Alt+R                          //remove blank lines


Save the file into you XYplorer scripts folder.
Save one of the following scripts there too.
Be sure to have the latest beta of XYplorer (as state is today)
Run that script and see the test ouput.

*/
///////////////////////////////////////////////////////////////////////////////

//read whole file into var:
$file = readfile("<xyscripts>\english.0");

   //get amount of parts of file, delimitered by an newline, a.k.a Lines count:
   $lines = gettoken($file, "count", "<crlf>");


   //endless loop
   while(1)
   {
   
     //get two random numbers betwenn 1 and lines count:
     $line1 = rand(1, $lines);
     $line2 = rand(1, $lines);

     //get the lines indicated by the random line number:
     $part1 = gettoken($file, $line1, "<crlf>");
     $part2 = gettoken($file, $line2, "<crlf>");
     //get an random digit:
     $part3 = rand(1,9);
     
     //test output:
     //show result and ask to continue or break:
     //return: 1 on OK, 0 on Cancel 
     $conti =  confirm("$part1$part2$part3<crlf 3>Again?");
     if ($conti == 0){break;} //break the infinity loop
   }


/*
      Output looks like:

        ---------------------------
              XYplorer
        ---------------------------
              shutshaver9


              Again?
        ---------------------------
            OK   Abbrechen   
        ---------------------------
*/



//#############################


//create more then one password to chose one from list



$file = readfile("<xyscripts>\english.0");
 $lines = gettoken($file, "count", "<crlf>");

   $i=0;
   $collect = "";
   while($i < 11)
   {
       $line1 = rand(1, $lines);
       $line2 = rand(1, $lines);
         
       $part1 = gettoken($file, $line1, "<crlf>");
       $part2 = gettoken($file, $line2, "<crlf>");
       $part3 = rand(1,9);
          
        //multi password collection:
        $collect = "$collect$part1$part2$part3<crlf>";
   $i++;
   }

   //test output:
   text $collect;



/*
      Output looks like:

      spitsavert2
      currypokes8
      poresdummy9
      downssoled7
      skimpsores3
      pagesvivid3
      foodsbaron3
      daredpause8
      loathchore1
      tameroptic8
      womengreed5
      prierrebel4
      dirtygolfs8
      aromabonus6
*/


//#############################################


//recase an char and add an second digit


$file = readfile("<xyscripts>\english.0");
  $lines = gettoken($file, "count", "<crlf>");
    
   $i=0;
   $collect = "";
   while($i < 11)
   {
     $line1 = rand(1, $lines);
     $line2 = rand(1, $lines);
       
     $part1 = gettoken($file, $line1, "<crlf>");
     $part2 = gettoken($file, $line2, "<crlf>");
     $part3 = rand(1,9);
     $part4 = rand(2,8);
       
     $parts = "$part1$part2";
     //get an random pos from string:
     $r = rand(2,8);
     //get the cahr indented by the random pos:
     $X = substr($parts, $r, 1);
     //recase lower to upper and vice versa:
     $Y = recase($X, "invert");
     //replace just first char X in original case, but inverted in Y:
     // 1, 1, 1 >>> case sensitive, start at pos 1, stop after first replace
     $parts = replace($parts, $X, $Y, 1, 1, 1 ); 
     //multi password collection:
     $collect = "$collect$parts$part3$part4<crlf>";   
   $i++;
   }

   //test output:
   text $collect;

/*
        Output looks like:

        JApanpapal33
        parrYgenus44
        foggyfolDs26
        Spiessever82
        cavesboNes68
        echoswIder74
        bloAtlefts46
        enVoysmall23
        brokEasset37
        quashdepTh65

        awiNgtrail52
        curdsEgger56
        briGsfolks26
        meldswHich47
        scOrndines53
        opensHazel77
        cargoVials75
        Duskydoped18
        pluMprants14
        forumLocal66

        shovelAmes34
        cedaRupper44
        waxErblows95
        yesesquAck27
        treadgueSs83
        phOneroyal73
        raCesfades46
        swipegaTes54
        rawerprOne45
        pantyStyle45
        pailsruMps87
        basicspaNk12
*/


Re: Scripting: new function "random(low, high)"

Posted: 21 Mar 2010 11:51
by Stefan
Stefan wrote:I want to request random() as new script function.
Works fine, thank you Don.
An use would be too to pick an random file:
$rand = rand(1, $filecount);
  $copyfile = gettoken($filelist, $rand);

or pick an random amount of files. rand(20, 25);
RandomSelectFiles.xys

Code: Select all

//proof-of-concept script... selects sometimes one more or less. Use for testing only
//Purpose: select an given amount of file randomly from current file list.
//Example: chose a few songs randomly for portable MP3 player
//Example: chose randomly an script to work on next night
//Example: chose randomly your next ring sound
//Example: reply to this post with your use of it


focus;
  sel f;
  $FilesCount = getinfo("CountSelected");
  sel;
  $FilesToSelect = input("Choose", "How many files to select from total ". $FilesCount."?", 5);
 
  sel 1;
  $ListCount =;
  $FolderCount=;
  $files=" ";
  $filefilter="";


  //as long as count of already chosen files is less then wanted max:
  while($ListCount<$FilesToSelect)
  {
   
     //if item is an folder, count folders amount only:
     IF ( report("{Dir Yes|No|Drv}",1)==Yes)
     {
           incr $FolderCount;
           sel +1;
           continue;
     }else{
     
          //select an random file:
          $rand = rand(1,$FilesCount -1);
          $select = $FolderCount + $rand;
          sel $select;
          
          //step over if this file is already in file list:
          IF (strpos($files, quote("<curname>"))>0)
          {
               continue;
          }else{
          
               //else put randomly selected file to files list (here two examples):
               
               $files = $files . "<curname><crlf>";
               
               //i got problems with my test files, there are more or 
               //less chosen, so i had to quote the name
               $q = quote("<curname>"); 
               $filefilter = $filefilter . $q|;
               
               //increase count of already chosen files:
               incr $ListCount;
          }
     }
  }
  
  //output, do something with those randomly selected file:
  
  //Example 1
  //show text box with files:
  //text $files;
  
  //Example 2
  //just select chosen files:
  selfilter $filefilter;
  msg "Randomly chosen files are selected";
  
  //Example 3
  //show chosen files only (Read help about "Visual Filter", use CTRL+Shift+J to see all files again):
  sel;
  //text $filefilter;
  filter $filefilter;
  msg "Files are filtered for randomly chosen files.<crlf><crlf>Use CTRL+Shift+J to see all files again";

  // ---- (for continue testing) ----
  //restore full file list:
  wait 4000;
  #355; //toggling VisualFilter (use here to disable the filter)

Re: Scripting: new function "random(low, high)"

Posted: 20 Mar 2011 13:11
by Stefan
Based on this request >>> http://www.xyplorer.com/xyfc/viewtopic. ... 491#p57491

Thanks to Don for always improving scripting functionality.

Code: Select all

//XYplorer script to randomize an string
//found at http://www.xyplorer.com/xyfc/viewtopic.php?f=5&t=4780&p=57721
$b="";//dummy for nicer layout
         
  // === === === ===    user settings   === === === === 
     
  $IN = "This Should be RaNdoM";           //the input string to process on
  //d,e,R,s,h,i,T,M,u,S,N,o,l,o,d,b,a,h    //$out would be like this
                                            
  $RandomizeCaseToo = false;               //change the case of current char $sign?
  $delim = ",";                            //delim the single chars by $delim
  $DropSpaces = TRUE;                      //remove spaces from output?
            
           
           
            
  // === === === === === ===   === === === === === ===
  // === === ===  Don't modify code below  === === === 
               
  //user-settings: wants spaces or not?
  if ($DropSpaces){ $str = replace($IN, " ", ""); }else {$str = $IN;} 
               
  $count=0; $steps=strlen($str); $out="";    //inits
  while($count < $steps)                     //for each char in str
  {
      $len = strlen($str);
      if ($len > 1)                          //if there is more then one sign in str
      {
        $rand = rand(0,$len);                //get an random number to get random sign from str
        
        if ($rand == 0)                      //if random sign the first sign from str
        {
            $sign = substr($str, 0, 1);      //--get the random sign into an var
            $str = substr($str, 1);          //--set str to str without this random sign
         
        }elseif ($rand == $len)              //if random sign the last sign from str
        {
           $sign = substr($str, $len -1, 1); //--get sign
           $str = substr($str, 0, $len -1);  //--remove sign from str
          
        }else                                //if random sign is somewhere inside str
        {                                     
           $sign = substr($str, $rand, 1);   //--get sign
           $subA = substr($str, 0, $rand);   //--get part of str before sign
           $subB = substr($str, $rand +1);   //--get part of str after sign
           $str = $subA$subB;                //--set str to str without sign
        }
      }else
      {
          $sign = $str;                      //if only one sign left in str simply use this
      }
                                           
      if ($RandomizeCaseToo)                //User-settings: randomize case or not?
      { 
        $case = rand(0,1);                  //random: do an case change or not?
        if ($case==1){ $sign = recase($sign, "upper");} 
      }
       
      $out = "$out$sign$delim";             //collect output: OutArray+Sign+Delim
                
      $count++;                             //increase count
   }
           
   //trim surrounding spaces and comas:
   $out = regexreplace($out, "[ ,]*(\b.+\b)[ ,]*", "$1");
              
   // === create output ===
  //just use  $out  somewhere.
  //    would be   N,a,T,s,h,d,i,S,M,o,b,R,e,l,u,h,o,d
  //    or             oodaLiBR u D MSThSNeh
  //    depending on user-settings.
                   
  //-----------------------------------------------------------------
  //--------create an test output:
   $lenIn  = strlen($IN);
   $lenOut = strlen($out);
  
   text RandomizeCaseToo is: $RandomizeCaseToo<crlf>
        Delimiter is: "$delim"<crlf>
        DropSpaces is: $DropSpaces<crlf 2>
        Original string ($lenIn):<crlf>$IN<crlf 2>
        Output is ($lenOut):<crlf>$out;


/*

 Our test Output would look like:
 
      RandomizeCaseToo is: 0
      Delimiter is: ","
      DropSpaces is: 1

      Original string (21):
      This Should be RaNdoM

      Output is (35):
      N,a,T,s,h,d,i,S,M,o,b,R,e,l,u,h,o,d

      -------------

 Or:
      RandomizeCaseToo is: 1
      Delimiter is: ""
      DropSpaces is: 0

      Original string (21):
      This Should be RaNdoM

      Output is (21):
      oodaLiBR u D MSThSNeh
*/



########### EDIT:

Code: Select all

v9.90.0505 - 2011-03-20
  * SC replace enhanced. Added optional parameters start and count.
      Syntax: replace(string, search, replacement, [matchcase], _
                  [start=1], [count=-1]))
        start:  Position from left where the replacement starts.
        count:  Maximal number of replacements.

    * SC recase enhanced. New named argument for parameter mode:
        mode:
          invert: Invert the case of each letter.
      Example:
        text recase("the caMel can't.", "invert"); //THE CAmEL CAN'T.

The above rewrote Script:

Code: Select all

//XYplorer script to randomize an string
//found at http://www.xyplorer.com/xyfc/viewtopic.php?f=5&t=4780&p=57721
$b="";//dummy for nicer layout

  
  global $deb;   //set global var for pass info to the debugging function in sub routine
   
   
  // === === === ===    user settings   === === === ===
     
  $IN = "This Should be RaNdoM";           //the input string to process on
  //d,e,R,s,h,i,T,M,u,S,N,o,l,o,d,b,a,h    //$out would be like this
                                           
  $RandomizeCaseToo = TRUE;               //change the case of current char $sign?
  $delim = ",";                            //delim the single chars by $delim
  $DropSpaces = TRUE;                      //remove spaces from output?
           
  // === === === === === ===   === === === === === ===
  // === === ===  Don't modify code below  === === ===
               
  //user-settings: wants spaces or not?
  if ($DropSpaces){ $str = replace($IN, " ", ""); }else {$str = $IN;}
               
  $count=0; $steps=strlen($str); $out="";    //inits
  while($count < $steps)                     //for each char in str
  {
      $len = strlen($str);
      if ($len > 1)                          //if there is more then one sign in str
      {
        $rand = rand(0,$len);                //get an random number to get random sign from str
       
       
        $deb = "RAND $rand, str: $str, len: $len"; //set text for debugging output
        Sub "_DEBUG";                              //call debug sub routine with $deb as parameter
       
         
        if ($rand == 0)                      //if random sign the first sign from str
        {
            $sign = substr($str, 0, 1);      //--get the random sign into an var
            $str = replace($str, $sign, "", 1, 1, 1);          //--set str to str without this random sign
          
            $deb = "RAND case 0   , SIGN: $sign , new STR: $str<crlf>"; Sub "_DEBUG"; //Debugging
          
         
        }elseif ($rand == $len)              //if random sign the last sign from str
        {
           $sign = substr($str, $len -1, 1); //--get sign
           $str = replace($str, $sign, "", 1, 1, 1);  //--remove sign from str
        
           $deb = "RAND case len , SIGN: $sign , new STR: $str<crlf>"; Sub "_DEBUG";
         
         
        }else                                //if random sign is somewhere inside str
        {                                     
           $sign = substr($str, $rand, 1);   //--get sign
           $str = replace($str, $sign, "", 1, 1, 1);   //--remove sign from str
           $deb = "RAND case else, SIGN: $sign , new STR: $str<crlf>"; Sub "_DEBUG"; //Debugging
          
        }
      }else
      {
          $sign = $str;                      //if only one sign left in str simply use this
          $deb = "Last sign,      SIGN: $sign , new STR: $str<crlf>";  Sub "_DEBUG"; //Debugging
        
      }
                                           
      if ($RandomizeCaseToo)                //User-settings: randomize case or not?
      {
        $case = rand(0,1);                  //random: do an case change or not?
        if ($case==1){ $sign = recase($sign, "invert");}
      }
            
             
      $out = "$out$sign$delim";             //collect output: OutArray+Sign+Delim
               
      $count++;                             //increase count
   }
           
   //trim surrounding spaces and comas:
   $out = regexreplace($out, "[ ,]*(\b.+\b)[ ,]*", "$1");
             
   // === create output ===
  //just use  $out  somewhere.
  //    would be   N,a,T,s,h,d,i,S,M,o,b,R,e,l,u,h,o,d
  //    or             oodaLiBR u D MSThSNeh
  //    depending on user-settings.
                   
  //-----------------------------------------------------------------
  //--------create an test output:
   $lenIn  = strlen($IN);
   $lenOut = strlen($out);
       
   text RandomizeCaseToo is: $RandomizeCaseToo<crlf>
        Delimiter is: "$delim"<crlf>
        DropSpaces is: $DropSpaces<crlf 2>
        Original string ($lenIn):<crlf>$IN<crlf 2>
        Output is ($lenOut):<crlf>$out;
           
         
         
/////////////////////////////////////////////
//Debugging sub routine
//Usage:        $deb = "Position: xyz, Var: myVar";        Sub "_DEBUG";
 
"_DEBUG"
 global $deb;
   writefile("C:\Temp\deb.txt", "<date yyyy-mm-dd hh:nn:ss>  $deb<crlf>" ,a);
     
       
Debug output:

Code: Select all

2011-03-21 14:31:51  RAND 15, str: ThisShouldbeRaNdoM, len: 18
2011-03-21 14:31:51  RAND case else, SIGN: d , new STR: ThisShoulbeRaNdoM

2011-03-21 14:31:51  RAND 9, str: ThisShoulbeRaNdoM, len: 17
2011-03-21 14:31:51  RAND case else, SIGN: b , new STR: ThisShouleRaNdoM

2011-03-21 14:31:51  RAND 16, str: ThisShouleRaNdoM, len: 16
2011-03-21 14:31:51  RAND case len , SIGN: M , new STR: ThisShouleRaNdo

2011-03-21 14:31:51  RAND 5, str: ThisShouleRaNdo, len: 15
2011-03-21 14:31:51  RAND case else, SIGN: h , new STR: TisShouleRaNdo

2011-03-21 14:31:51  RAND 6, str: TisShouleRaNdo, len: 14
2011-03-21 14:31:51  RAND case else, SIGN: u , new STR: TisSholeRaNdo

2011-03-21 14:31:51  RAND 0, str: TisSholeRaNdo, len: 13
2011-03-21 14:31:51  RAND case 0   , SIGN: T , new STR: isSholeRaNdo

2011-03-21 14:31:51  RAND 11, str: isSholeRaNdo, len: 12
2011-03-21 14:31:51  RAND case else, SIGN: o , new STR: isShleRaNdo

2011-03-21 14:31:51  RAND 2, str: isShleRaNdo, len: 11
2011-03-21 14:31:51  RAND case else, SIGN: S , new STR: ishleRaNdo

2011-03-21 14:31:51  RAND 0, str: ishleRaNdo, len: 10
2011-03-21 14:31:51  RAND case 0   , SIGN: i , new STR: shleRaNdo

2011-03-21 14:31:52  RAND 8, str: shleRaNdo, len: 9
2011-03-21 14:31:52  RAND case else, SIGN: o , new STR: shleRaNd

2011-03-21 14:31:52  RAND 7, str: shleRaNd, len: 8
2011-03-21 14:31:52  RAND case else, SIGN: d , new STR: shleRaN

2011-03-21 14:31:52  RAND 3, str: shleRaN, len: 7
2011-03-21 14:31:52  RAND case else, SIGN: e , new STR: shlRaN

2011-03-21 14:31:52  RAND 3, str: shlRaN, len: 6
2011-03-21 14:31:52  RAND case else, SIGN: R , new STR: shlaN

2011-03-21 14:31:52  RAND 0, str: shlaN, len: 5
2011-03-21 14:31:52  RAND case 0   , SIGN: s , new STR: hlaN

2011-03-21 14:31:52  RAND 0, str: hlaN, len: 4
2011-03-21 14:31:52  RAND case 0   , SIGN: h , new STR: laN

2011-03-21 14:31:52  RAND 2, str: laN, len: 3
2011-03-21 14:31:52  RAND case else, SIGN: N , new STR: la

2011-03-21 14:31:52  RAND 0, str: la, len: 2
2011-03-21 14:31:53  RAND case 0   , SIGN: l , new STR: a

2011-03-21 14:31:53  Last sign,      SIGN: a , new STR: a


Test output:

Code: Select all

RandomizeCaseToo is: 1
Delimiter is: ","
DropSpaces is: 1

Original string (21):
This Should be RaNdoM

Output is (35):
d,B,m,h,u,T,o,s,I,O,d,E,r,s,h,N,L,a

Many thanks to Don!

.