Add rounding to this script

Hi everyone,
I need to add rounding to this script. I need two versions, one for 1 decimal place and one for 0 decimal places. Can anyone help out?
#target illustrator
addMeasurements();
function addMeasurements() {
    var i, doc, imp, met, txtItems, txt, nub;
    doc = app.activeDocument;
    imp = doc.layers.getByName( 'Text' );
    met = doc.layers.add();  met.name = 'New';
    txtItems = imp.textFrames;
    for ( i = 0; i < txtItems.length; i++ ) {
        txtItems[i].duplicate( met, ElementPlacement.PLACEATEND )
    txtItems = met.textFrames;
    for ( i = 0; i < txtItems.length; i++ ) {
        var nub = parseInt( txt = txtItems[i].contents ); // For Numbers only!!!!
        txtItems[i].contents = String( txt * 1.1 )
Thanks in advance.

The example is just a basic function… Just place it after the main function body in your script… Call it where you need it… here is an example… I changed your parseInt() to parseFloat() to deal with your decmial values… While this should wolk it still may NOT be what you want… i.e. it does nothing about keeping the alpha characters in your text frames the new numbers replace all content…
#target illustrator
addMeasurements();
function addMeasurements() {
    var i, doc, imp, met, txtItems, txt, nub;
    doc = app.activeDocument;
    imp = doc.layers.getByName( 'Numbers' );
    met = doc.layers.add();  met.name = 'New';
    txtItems = imp.textFrames;
    for ( i = 0; i < txtItems.length; i++ ) {
        txtItems[i].duplicate( met, ElementPlacement.PLACEATEND )
    txtItems = met.textFrames;
    for ( i = 0; i < txtItems.length; i++ ) {
        var nub = parseFloat( txtItems[i].contents ); // now parseFloat()
                              nub = nub * 1.123456; // just to check the function rounds…
                              var rnub = roundToDP( nub, 2 );
        txtItems[i].contents = String( rnub ); // replaces all content…?
function roundToDP( n, dP ) {
          return Math.round( n * Math.pow( 10, dP ) ) / Math.pow( 10, dP );

Similar Messages

  • Please assist with modifying this script to read in a list of servers and output results to excel

    Hello,
    I have an excellent script written by Brian Wilhite to gather the last logged in user using Powershell.
    http://gallery.technet.microsoft.com/scriptcenter/Get-LastLogon-Determining-283f98ae/view/Discussions#content
    My Powershell Fu is stumbling to modify this script to the following requirements:
    Currently the script must be loaded first into Powershell, then it can be executed.  I would rather edit the script in my Powershell ISE, add the .txt file to the script itself that gives a list of the servers I need to scan.  Then when I
    press Run Script in my ISE it executes.
    I would also like to output the results of the file to excel (.xls or .csv will do).  Currently the results look as follows:
    Computer : SVR01
    User : WILHITE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    I would prefer it shows up like so:
    Computer User SID Time Currently LoggedOn
    SVR01 WILHITE\BRIAN S-1xxx 9/20/2012 1:07:58 PM FalseSRV02 WILHITE\BRIAN S-2xxx 9/26/2014 10:00:00 AM True
    Any help you can provide would be greatly appreciated.  I'll add the full script to the end of this post.
    Thank you.
    Function Get-LastLogon
    <#
    .SYNOPSIS
    This function will list the last user logged on or logged in.
    .DESCRIPTION
    This function will list the last user logged on or logged in. It will detect if the user is currently logged on
    via WMI or the Registry, depending on what version of Windows is running on the target. There is some "guess" work
    to determine what Domain the user truly belongs to if run against Vista NON SP1 and below, since the function
    is using the profile name initially to detect the user name. It then compares the profile name and the Security
    Entries (ACE-SDDL) to see if they are equal to determine Domain and if the profile is loaded via the Registry.
    .PARAMETER ComputerName
    A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).
    .PARAMETER FilterSID
    Filters a single SID from the results. For use if there is a service account commonly used.
    .PARAMETER WQLFilter
    Default WQLFilter defined for the Win32_UserProfile query, it is best to leave this alone, unless you know what
    you are doing.
    Default Value = "NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'"
    .EXAMPLE
    $Servers = Get-Content "C:\ServerList.txt"
    Get-LastLogon -ComputerName $Servers
    This example will return the last logon information from all the servers in the C:\ServerList.txt file.
    Computer : SVR01
    User : WILHITE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    Computer : SVR02
    User : WILIHTE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 12:46:48 PM
    CurrentlyLoggedOn : True
    .EXAMPLE
    Get-LastLogon -ComputerName svr01, svr02 -FilterSID S-1-5-21-012345678-0123456789-012345678-012345
    This example will return the last logon information from all the servers in the C:\ServerList.txt file.
    Computer : SVR01
    User : WILHITE\ADMIN
    SID : S-1-5-21-012345678-0123456789-012345678-543210
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    Computer : SVR02
    User : WILIHTE\ADMIN
    SID : S-1-5-21-012345678-0123456789-012345678-543210
    Time : 9/20/2012 12:46:48 PM
    CurrentlyLoggedOn : True
    .LINK
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee886409(v=vs.85).aspx
    http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx
    .NOTES
    Author: Brian C. Wilhite
    Email: [email protected]
    Date: "09/20/2012"
    Updates: Added FilterSID Parameter
    Cleaned Up Code, defined fewer variables when creating PSObjects
    ToDo: Clean up the UserSID Translation, to continue even if the SID is local
    #>
    [CmdletBinding()]
    param(
    [Parameter(Position=0,ValueFromPipeline=$true)]
    [Alias("CN","Computer")]
    [String[]]$ComputerName="$env:COMPUTERNAME",
    [String]$FilterSID,
    [String]$WQLFilter="NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'"
    Begin
    #Adjusting ErrorActionPreference to stop on all errors
    $TempErrAct = $ErrorActionPreference
    $ErrorActionPreference = "Stop"
    #Exclude Local System, Local Service & Network Service
    }#End Begin Script Block
    Process
    Foreach ($Computer in $ComputerName)
    $Computer = $Computer.ToUpper().Trim()
    Try
    #Querying Windows version to determine how to proceed.
    $Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
    $Build = $Win32OS.BuildNumber
    #Win32_UserProfile exist on Windows Vista and above
    If ($Build -ge 6001)
    If ($FilterSID)
    $WQLFilter = $WQLFilter + " AND NOT SID = `'$FilterSID`'"
    }#End If ($FilterSID)
    $Win32User = Get-WmiObject -Class Win32_UserProfile -Filter $WQLFilter -ComputerName $Computer
    $LastUser = $Win32User | Sort-Object -Property LastUseTime -Descending | Select-Object -First 1
    $Loaded = $LastUser.Loaded
    $Script:Time = ([WMI]'').ConvertToDateTime($LastUser.LastUseTime)
    #Convert SID to Account for friendly display
    $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($LastUser.SID)
    $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
    }#End If ($Build -ge 6001)
    If ($Build -le 6000)
    If ($Build -eq 2195)
    $SysDrv = $Win32OS.SystemDirectory.ToCharArray()[0] + ":"
    }#End If ($Build -eq 2195)
    Else
    $SysDrv = $Win32OS.SystemDrive
    }#End Else
    $SysDrv = $SysDrv.Replace(":","$")
    $Script:ProfLoc = "\\$Computer\$SysDrv\Documents and Settings"
    $Profiles = Get-ChildItem -Path $Script:ProfLoc
    $Script:NTUserDatLog = $Profiles | ForEach-Object -Process {$_.GetFiles("ntuser.dat.LOG")}
    #Function to grab last profile data, used for allowing -FilterSID to function properly.
    function GetLastProfData ($InstanceNumber)
    $Script:LastProf = ($Script:NTUserDatLog | Sort-Object -Property LastWriteTime -Descending)[$InstanceNumber]
    $Script:UserName = $Script:LastProf.DirectoryName.Replace("$Script:ProfLoc","").Trim("\").ToUpper()
    $Script:Time = $Script:LastProf.LastAccessTime
    #Getting the SID of the user from the file ACE to compare
    $Script:Sddl = $Script:LastProf.GetAccessControl().Sddl
    $Script:Sddl = $Script:Sddl.split("(") | Select-String -Pattern "[0-9]\)$" | Select-Object -First 1
    #Formatting SID, assuming the 6th entry will be the users SID.
    $Script:Sddl = $Script:Sddl.ToString().Split(";")[5].Trim(")")
    #Convert Account to SID to detect if profile is loaded via the remote registry
    $Script:TranSID = New-Object System.Security.Principal.NTAccount($Script:UserName)
    $Script:UserSID = $Script:TranSID.Translate([System.Security.Principal.SecurityIdentifier])
    }#End function GetLastProfData
    GetLastProfData -InstanceNumber 0
    #If the FilterSID equals the UserSID, rerun GetLastProfData and select the next instance
    If ($Script:UserSID -eq $FilterSID)
    GetLastProfData -InstanceNumber 1
    }#End If ($Script:UserSID -eq $FilterSID)
    #If the detected SID via Sddl matches the UserSID, then connect to the registry to detect currently loggedon.
    If ($Script:Sddl -eq $Script:UserSID)
    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"Users",$Computer)
    $Loaded = $Reg.GetSubKeyNames() -contains $Script:UserSID.Value
    #Convert SID to Account for friendly display
    $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($Script:UserSID)
    $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
    }#End If ($Script:Sddl -eq $Script:UserSID)
    Else
    $User = $Script:UserName
    $Loaded = "Unknown"
    }#End Else
    }#End If ($Build -le 6000)
    #Creating Custom PSObject For Output
    New-Object -TypeName PSObject -Property @{
    Computer=$Computer
    User=$User
    SID=$Script:UserSID
    Time=$Script:Time
    CurrentlyLoggedOn=$Loaded
    } | Select-Object Computer, User, SID, Time, CurrentlyLoggedOn
    }#End Try
    Catch
    If ($_.Exception.Message -Like "*Some or all identity references could not be translated*")
    Write-Warning "Unable to Translate $Script:UserSID, try filtering the SID `nby using the -FilterSID parameter."
    Write-Warning "It may be that $Script:UserSID is local to $Computer, Unable to translate remote SID"
    Else
    Write-Warning $_
    }#End Catch
    }#End Foreach ($Computer in $ComputerName)
    }#End Process
    End
    #Resetting ErrorActionPref
    $ErrorActionPreference = $TempErrAct
    }#End End
    }# End Function Get-LastLogon

     This should work:
    Get-LastLogon -Computername (Get-content .\Servers.txt) | Export-CSV .\Output.csv -NoTypeInformation
    I just tested it on my test domain and it did the trick.

  • How can I modify this script to return only certain rows of my mySQL table?

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

  • How do I edit this script (newbie)

    Editing a script
    I found a script that creates a reminder event based upon the birthdays of my contacts in Address Book. It looks forward one week at a time.
    I'm not familiar with creating scripts. How would I edit this to do the following (if possible)
    1- I set up a contact list in Address Book for only those people whose birthdays I want to be reminded of. Is it possible to have this script only look through this contact list, not every contact.
    2- Can it also be set up to delete the previously set events (so that the only events that appear are the ones for the ensuing week)
    3- Can it be set up to remind me of anniversaries also? How would I edit it? (I tried to find and replace the term birthday with anniversary, but all it did was notify me of forthcoming week's birthdays but called them anniversaries)
    Thanks!
    ===============
    birthdayAlert.scpt
    User set variables
    set numberDaysNotice to 1 -- how many days before the birthday to alert you, 0 is that day
    set timeOfNotification to 5 -- the hour you want the notification
    set selectedCalender to "Birthday Reminders" -- the calender in iCal you want to add the events to
    Setup
    set birthdayPeople to {}
    set birthdayDates to {}
    Get the current date & next week
    set today to current date
    set nextWeek to today + (60 * 60 * 24 * 7)
    Loop through everyone in the Address Book
    tell application "Address Book"
    set peopleArray to the name of every person
    repeat with i from 1 to count of peopleArray
    set thisPerson to person i
    set thisBirthday to birth date of thisPerson
    Check if they've got a birthday entered on their card
    if thisBirthday is not equal to (missing value) then
    set year of thisBirthday to year of (current date) -- otherwise it uses their birth year
    See if it's in the next week
    if (thisBirthday is greater than today) and (thisBirthday is less than nextWeek) then
    set thisBirthday_day to day of thisBirthday
    set thisBirthday_month to month of thisBirthday
    Add them to our list
    set birthdayPeople to birthdayPeople & name of thisPerson
    set birthdayDates to birthdayDates & birth date of thisPerson
    end if
    end if
    end repeat
    end tell
    If we have birthday's go into iCal and add the alerts
    if (count of birthdayPeople) is greater than 0 and ((count of birthdayPeople) is equal to (count of birthdayDates)) then
    tell application "iCal"
    tell calendar selectedCalender
    repeat with i from 1 to count of birthdayPeople
    set thisDate to item i of birthdayDates
    set year of thisDate to year of today
    set time of thisDate to (60 * 60) * timeOfNotification
    set day of thisDate to (day of thisDate) - numberDaysNotice
    set thisEvent to make new event at end with properties {description:"", summary:(item i of birthdayPeople) & "'s Birthday", location:"", start date:thisDate, end date:thisDate + 15 * minutes}
    tell thisEvent
    make new display alarm at end with properties {trigger interval:0}
    end tell
    end repeat
    end tell
    end tell
    end if

    1- I set up a contact list in Address Book for only those people whose birthdays I want to be reminded of. Is it possible to have this script only look through this contact list, not every contact.
    Sure - if you created a specific group of the people you want to track then just change the line:
    set peopleArray to the name of every person
    to:
    set peopleArray to the name of every person of group "Birthdays"
    (or whatever group name you used). You see, as written your script just grabs everyone's name as opposed to just the names of people in the specific group.
    2- Can it also be set up to delete the previously set events (so that the only events that appear are the ones for the ensuing week)
    Yes, but that's a little trickier since you need some way to denote which events are birthday events vs. other events from last week. If you're using a specific calendar for this then you could just delete existing events in that calendar, or you could implement a minor change to the way you create events - use the description to identify this is one of your auto-created birthday alarms:
    set thisEvent to make new event at end with properties {description:"birthday", summary:(item i of birthdayPeople) & "'s Birthday", location:"", start date:thisDate, end date:thisDate + 15 * minutes}
    So now the events will have a specific description, so it's easy to start your new script off with a line that deletes existing 'birthday" events, via:
    tell application "iCal"
      delete every event of calendar selectedCalendar whose description = "birthday"
    end tell
    (you can nix the '... whose description = "birthday"' element if you just want to delete all existing events in the calendar).
    3- Can it be set up to remind me of anniversaries also? How would I edit it? (I tried to find and replace the term birthday with anniversary, but all it did was notify me of forthcoming week's birthdays but called them anniversaries)
    Sure, that's because you specifically ask Address Book for birthdays:
    set thisBirthday to birth date of thisPerson
    To track anniversaries you need to ask Address Book for different data. This one's a little tricker since anniversaries are tracked via the custom date element, so you'd need something like:
    set anniversaryList to {}
    tell application "Address Book"
      repeat with eachPerson in (get every person) -- add 'of group "anniversaries' if you use a specific group
        repeat with eachDate in eachPerson's custom dates
          if label of eachDate = "anniversary" then
            -- this person has an Anniversary set, so add your code here to check if eachDate is in the next week if it is:
            copy eachPerson to end of anniversaryList
          end if
        end repeat
      end repeat
    end tell
    At the end of this you'll have a list of people whose anniversary is upcoming and you can duplicate your iCal code to add anniversary events in addition to birthdays.

  • Can i use this script in illustrator?

    can i use this script in illustrator?
    Newsgroup_User

    // This script exports extended layer.bounds information to [psd_file_name].xml
    // by pattesdours
    function docCheck() {
        // ensure that there is at least one document open
        if (!documents.length) {
            alert('There are no documents open.');
            return; // quit
    docCheck();
    var originalRulerUnits = preferences.rulerUnits;
    preferences.rulerUnits = Units.PIXELS;
    var docRef = activeDocument;
    var docWidth = docRef.width.value;
    var docHeight = docRef.height.value;
    var mySourceFilePath = activeDocument.fullName.path + "/";
    //  Code to get layer index / descriptor
    cTID = function(s) { return app.charIDToTypeID(s); };
    sTID = function(s) { return app.stringIDToTypeID(s); };
    function getLayerDescriptor (doc, layer) {
        var ref = new ActionReference();
        ref.putEnumerated(cTID("Lyr "), cTID("Ordn"), cTID("Trgt"));
        return executeActionGet(ref)
    function getLayerID(doc, layer) {
      var d = getLayerDescriptor(doc, layer);
      return d.getInteger(cTID('LyrI'));
    var stackorder = 0;
    // function from Xbytor to traverse all layers
    traverseLayers = function(doc, ftn, reverse) {
      function _traverse(doc, layers, ftn, reverse) {
        var ok = true;
        for (var i = 1; i <= layers.length && ok != false; i++) {
          var index = (reverse == true) ? layers.length-i : i - 1;
          var layer = layers[index];
          //  alert("layer.typename  >>> "+layer.typename ); 
          if (layer.typename == "LayerSet") {
            ok = _traverse(doc, layer.layers, ftn, reverse);
          } else {
      stackorder = stackorder + 1;
            ok = ftn(doc, layer, stackorder);
        return ok;
      return _traverse(doc, doc.layers, ftn, reverse);
    // create a string to hold the data
    var str ="";
    // class using a contructor
    function cLayer(doc, layer) {
    //this.layerID = Stdlib.getLayerID(doc, layer);
      this.layerID = getLayerID(doc, layer);
      //alert("layer ID: " + this.layerID);
      this.layerWidth = layer.bounds[2].value - layer.bounds[0].value;
          this.layerHeight = layer.bounds[3].value - layer.bounds[1].value;
      // these return object coordinates relative to canvas
          this.upperLeftX = layer.bounds[0].value;
          this.upperLeftY = layer.bounds[1].value;
          this.upperCenterX = this.layerWidth / 2 + layer.bounds[0].value;
          this.upperCenterY = layer.bounds[1].value;
          this.upperRightX = layer.bounds[2].value;
          this.upperRightY = layer.bounds[1].value;
          this.middleLeftX = layer.bounds[0].value;
          this.middleLeftY = this.layerHeight / 2 + layer.bounds[1].value;
          this.middleCenterX = this.layerWidth / 2 + layer.bounds[0].value;
          this.middleCenterY = this.layerHeight / 2 + layer.bounds[1].value;
          this.middleRightX = layer.bounds[2].value;
          this.middleRightY = this.layerHeight / 2 + layer.bounds[1].value;
          this.lowerLeftX = layer.bounds[0].value;
          this.lowerLeftY = layer.bounds[3].value;
          this.lowerCenterX = this.layerWidth / 2 + layer.bounds[0].value;
          this.lowerCenterY = layer.bounds[3].value;
          this.lowerRightX = layer.bounds[2].value;
          this.lowerRightY = layer.bounds[3].value;
       // I'm adding these for easier editing of flash symbol transformation point (outputs a 'x, y' format)
       // because I like to assign shortcut keys that use the numeric pad keyboard, like such:
       // 7 8 9
       // 4 5 6
       // 1 2 3
          var windowW=2048;
          var windowH=1536;
       this.leftBottom = this.lowerLeftX + ", " + (windowH-this.lowerLeftY);
       this.bottomCenter = this.lowerCenterX + ", " +  (windowH-this.lowerCenterY);
       this.rightBottom = this.lowerRightX + ", " + this.lowerRightY;
       this.leftCenter = this.middleLeftX + ", " + this.middleLeftY;
       this.center = this.middleCenterX + ", " + this.middleCenterY;
       this.rightCenter = this.middleRightX + ", " + this.middleRightY;
       this.leftTop = this.upperLeftX + ", " + this.upperLeftY;
       this.topCenter = this.upperCenterX + ", " + this.upperCenterY;
       this.rightTop = this.upperRightX + ", " + this.upperRightY;
      // these return object coordinates relative to layer bounds
          this.relUpperLeftX = layer.bounds[1].value - layer.bounds[1].value;
          this.relUpperLeftY =  layer.bounds[0].value - layer.bounds[0].value;
          this.relUpperCenterX = this.layerWidth / 2;
          this.relUpperCenterY = layer.bounds[0].value - layer.bounds[0].value;
          this.relUpperRightX = this.layerWidth;
          this.relUpperRightY = layer.bounds[0].value - layer.bounds[0].value;
          this.relMiddleLeftX = layer.bounds[1].value - layer.bounds[1].value;
          this.relMiddleLeftY = this.layerHeight / 2;
          this.relMiddleCenterX = this.layerWidth / 2;
          this.relMiddleCenterY = this.layerHeight / 2;
          this.relMiddleRightX = this.layerWidth;
      this.relMiddleRightY = this.layerHeight / 2;
          this.relLowerLeftX = layer.bounds[1].value - layer.bounds[1].value;
          this.relLowerLeftY = this.layerHeight;
          this.relLowerCenterX = this.layerWidth / 2;
      this.relLowerCenterY = this.layerHeight / 2;
          this.relLowerRightY = this.layerHeight;
          this.relLowerRightX = this.layerWidth;
          this.relLowerRightY = this.layerHeight;
      return this;
    // add header line
    str = "<psd filename=\"" + docRef.name + "\" path=\"" + mySourceFilePath + "\" width=\"" + docWidth + "\" height=\"" + docHeight + "\">\n";
    // now a function to collect the data
    var isParentAvailable=false;
    var prevLayerSetName="";
    function exportBounds(doc, layer, i) {
        var isVisible = layer.visible;
        var layerData = cLayer(doc, layer);
    //alert("layer.name  >>> "+layer.name );
    //alert("typename >>> "+layer.typename);
    /*if(layer.parent.name == "ParentTest"){
    for(var i in layer.parent){
        alert(" III >>> "+i+"<<<layer.parent>>"+layer.parent[i]);
      if(isVisible){
    // Layer object main coordinates relative to its active pixels
    var startStr="";
        if(layer.parent.typename=="LayerSet"){
            if(prevLayerSetName!="LayerSet")    {
                startStr="\t<parentlayer id='"+layer.parent.name+"'>\n\t";
            }else{
                   startStr="\t";
            // endStr="\t</parentlayer>\n";
             prevLayerSetName=layer.parent.typename;
          }else{
               if(prevLayerSetName=="LayerSet"){
                    startStr="\t</parentlayer>\n";
                prevLayerSetName="";
      var positionStr=layer.name.split(".")[0].substr(layer.name.split(".")[0].length-3,layer.name. split(".")[0].length);
      var assetPosition=leftTop;
      if(positionStr=="L_B"){
      assetPosition=leftBottom;
      }else if(positionStr=="B_C"){
      assetPosition=bottomCenter;
      }else if(positionStr=="R_B"){
      assetPosition=rightBottom;
      }else if(positionStr=="L_C"){
      assetPosition=leftCenter;
      }else if(positionStr=="C"){
      assetPosition=center;
      }else if(positionStr=="R_C"){
      assetPosition=rightCenter;
      }else if(positionStr=="L_T"){
      assetPosition=leftTop;
      }else if(positionStr=="T_C"){
      assetPosition=topCenter;
      }else if(positionStr=="R_T"){
      assetPosition=rightTop;
      var str2 =startStr+ "\t<layer name=\"" + layer.name
      + "\" stack=\"" + (i - 1) // order in which layers are stacked, starting with zero for the bottom-most layer
      + "\" position=\"" + assetPosition // this is the
      + "\" layerwidth=\"" + layerData.layerWidth
      + "\" layerheight=\"" + layerData.layerHeight
      + "\" transformpoint=\"" + "center" + "\">" // hard-coding 'center' as the default transformation point
      + layer.name + ".png" + "</layer>\n" // I have to put some content here otherwise sometimes tags are ignored
    str += str2.toString();
    // call X's function using the one above
    traverseLayers(app.activeDocument, exportBounds, true);
    // Use this to export XML file to same directory where PSD file is located
        var mySourceFilePath = activeDocument.fullName.path + "/";
    // create a reference to a file for output
        var csvFile = new File(mySourceFilePath.toString().match(/([^\.]+)/)[1] + app.activeDocument.name.match(/([^\.]+)/)[1] + ".xml");
    // open the file, write the data, then close the file
    csvFile.open('w');
    csvFile.writeln(str + "</psd>");
    csvFile.close();
    preferences.rulerUnits = originalRulerUnits;
    // Confirm that operation has completed
    alert("Operation Complete!" + "\n" + "Layer coordinates were successfully exported to:" + "\n" + "\n" + mySourceFilePath.toString().match(/([^\.]+)/)[1] + app.activeDocument.name.match(/([^\.]+)/)[1] + ".xml");

  • Getting the name of the Action that runs this script

    If I create a action in photoshop to run a script called "test script", How can I determine within the "test script" what action name started running this script?  I'm trying to write a script to scale my images.  The scaling will be determined by what Action ran this script.
    Example
    Action Names are 5x7, 4x6, 8x10
    Eash action above will run the same script called "scale me"
    Within "scale me", the java code will determine that 4x6 started running "scale me"
    "scale me" will go to the section within the java code to scale the image loaded in Photoshop to a 4x6 size.
    The reason for writing the "scale me" code this way is that I can maintain only one script to scale my images.
    Any suggestions or help would be appreciated.
    Raymond

    Thanks for all your comments.  Micheal, I took your code for the "ActionReference()" object and it works great!  I completed my code and it is working okay (some more testing needed).
    *  My Scaling Impage Script  */
    var docRef = app.activeDocument;  //Pointer to current opened document
    finish:
    if (documents.length == 0)      // Check to see if image opened if not, error message
                alert('There are no opened images\r\r' +"Exiting Script");
                break finish;
    var savedState = docRef.activeHistoryState      // Save the history state
    var originalUnit = preferences.rulerUnits   // Save the existing ruler perferences - units
    var ref = new ActionReference();  //Pointer to current selected Action
    ref.putEnumerated( charIDToTypeID("Actn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );  // Point to selected Action
    var desc = executeActionGet(ref);
    var actionName = desc.getString( charIDToTypeID("Nm  ") );  // Get Name of seclected Action
    var actionSetName = desc.getString( charIDToTypeID("PrNm") ); // Get Group the selected Action belongs to
    var actionnumber = 100;    //actionname =  100  (No Action Defined as default)
    var portraitorienation = 0;  // Orientation default to portrait
    var resolutions = 300;  // resolution default to 300
    var sizeh = 999999;  // default size
    var sizew = 999999;  // default size
    var resolution = 300;
    var scaleup1 = 0;  //enlargement
    var scaleup2 = 0;  //enlargement
    var scaleflag = 0;
    var scaleflagg = 0
    //  Assumption is the long side is always defined in sizeh
    if (actionName=="4 x 5") { actionnumber =0;  sizeh = 1535; sizew = 1228;}
    if (actionName=="4 x 6") { actionnumber =1;  sizeh = 1842; sizew = 1228;}
    if (actionName=="5 x 7") { actionnumber =2;  sizeh = 2149; sizew = 1535;}
    if (actionName=="6 x 9") { actionnumber =3;  sizeh = 2127; sizew = 1842;}
    if (actionName=="8 x 10") { actionnumber =4;  sizeh = 3020; sizew = 2416;}
    if (actionName=="8 x 12") { actionnumber =5;  sizeh = 3624; sizew = 2416;}
    if (actionName=="11 x 14") { actionnumber =6;  sizeh = 4228; sizew = 3322;}
    if (actionName=="12 x 18") { actionnumber =7;  sizeh = 5436; sizew = 3624;}
    if (actionName=="12 x 24") { actionnumber =8;  sizeh = 7248; sizew = 3624;}
    if (actionName=="12 x 36") { actionnumber =9;  sizeh = 10872; sizew = 3624;}
    preferences.rulerUnits = Units.PIXELS
    var doch = parseInt (docRef.height);
    var docw = parseInt (docRef.width);
    scaleflag = doch-docw;
    if ( doch > docw ) { scaleflagg =1}
    if  (scaleflagg == 0)
                    portraitorienation = 1;  // Landscape Orientation
                    //alert("Seclected Landscape")
                    //alert(doch+" Height" +docw +" Width")
    var scale1 = docw - sizeh
    var scale2 = doch - sizeh
    if (docw > sizeh) {scaleup1=1}
    if (doch > sizeh) {scaleup2=1}
    // We know know what action was started (What size to scale to and the orientation - Landscape or Portrait)
          //      alert ( "Current selected action is: "+actionName+"\r\rin the action set: "+actionSetName +"\r\rAction Number is " +actionnumber +"\r\rDeminsions are (HxW):  "  +sizeh +", "+sizew );
            if (portraitorienation == 1)   //landscape if true
                            if (scaleup1 == 1)
                                            alert ( "This Photo is landscape\r\r"+ "The doc H x W are:  " +doch +" x " + docw +"\r\r" +"Resizing to (H X W:  " +sizew +", "+ sizeh + "\r\r"  + "Reduction");                               
                                            docRef.resizeImage (sizeh, undefined, resolution, ResampleMethod.BICUBICSHARPER)  // Reduction in size
                            else
                                            alert ( "This Photo is landscape\r\r"+ "The doc H x W are:  " +doch +" x " + docw +"\r\r" +"Resizing to (H X W:  " +sizew +", "+ sizeh + "\r\r"   + "Enlargement");                                       
                                            docRef.resizeImage (sizeh, undefined, resolution, ResampleMethod.BICUBICSMOOTHER)  //Enlargement in size
            else  // portrait
                        if (scaleup2 ==1)
                                            alert ( "This Photo is Portrait\r\r"+ "The doc H x W are:  " +doch +" x " + docw +"\r\r" +"Resizing to (H X W:  " +sizeh +", "+ sizew + "\r\r"  + "Reduction");                                                 
                                           docRef.resizeImage (undefined, sizeh, resolution, ResampleMethod.BICUBICSHARPER)
                            else
                                            alert ( "This Photo is Portrait\r\r"+ "The doc H x W are:  " +doch +" x " + docw +"\r\r" +"Resizing to (H X W:  " +sizeh +", "+ sizew + "\r\r"   + "Enlargement");
                                            docRef.resizeImage (undefined, sizeh, resolution, ResampleMethod.BICUBICSMOOTHER)
    preferences.rulerUnits = originalUnit  // Restore ruler perferences - units
    My script is a single file that is run by the Actions, I've created for each size and each action runs the same script.  When the script runs, it determines via "ActionReference();" what the current selected Action name is and then applies the scaling.  This script has logic for landscape and portrait and will scale using the different algorithms (bicubic xxxx) depending if it is reducing the image or enlarging.   The parametersfor the scaling is long side and constraint proportions.
    So if I have to add another size to the code, all I need to do is to add one line of code to the script, copy any of the existing Actions and rename the copied Action to the size and I am done.
    I'm not a experience programmer so pls don't laugh at my coding but have done some C, C++, Fortran (Yes I'm an electrical engineer) in my days.  A number of things has stumped me abit and one of them was the use of arrays which didn't work for me too well.  I was to use the array for storing my parameters of each size.  Another one that really got me puzzled was the use of the docRef = activeDocument object.  The docRef.height and docRef.width will tell you the dimensions of the document based on the units set for rules.  I set mine for pixels.  The problem I had was the statement if(docRef.height > docRef.width) { do some stufff}.  If I change the  > to < for the same document it alway gives me a "true" logical.  After some thoughts today, I suspect that true is anything not 0 and false is only 0.  I will try this out tonight.  This theory does not fit well with my understanding on how the if statement works in other languages.  Any comments on this would be appreciated.
    Oh and I noticed some extra code var declarations that is not needed such as the activeHistoryState - was determining if I need to use this or the perferences.rulerunits to restore my ruler perferences and apparently the activeHistoryState does not and forgot to remove from the code.

  • Rounding up in script logic

    Dear all,
      I am using BPC 7.0 MS
      I tried to perform rounding up in script logic using Round and a negative number, but it didn't work.
      Any other suggestions?
    Cheers,
    Lip Chean

    So in this case you might need to use division instead of multiplication, for example:
    (int(28/100)+1)*100
    In my previous example I was assuming that you might need to get rid of two decimals and round to the full currncy unit.
    cheers,
    Madis
    Edited by: Madis Udam on Mar 17, 2010 9:30 PM
    Edited by: Madis Udam on Mar 17, 2010 9:31 PM

  • Add/change datatype column (scripting)

    Hello,
    I am writing a script to add default columns and their values to tables. So far for me it's possible to add columns to an existing table in the model.
    Next I want to add the value for datatype. I found out there's a method called getDataType(). Until now, I didn't find the 'setter; for this property.
    Like other scripts, I started with create a table with columns and then using the API to read the values.
    A simplified version of my code:
    // get columns array
    var myTab = model.getTableSet().getByName("T_POSITIONS");
    colArray = myTab.getElementsCollection().toArray();
    // loop over columns
    for(i = 0; i < colArray.length; i++){
      var dataType = colArray[i].getDataType();
      model.getAppView().log(colArray[i] + " has datatype " + dataType );
      colArray[i].setDataType("VARCHAR2 (1)");
    An error occurs when I want to run this script: Cannot find function setDataType in object ID.
    I cannot find the right method to add/modify the datatype property.
    Any tip would be appreciated.

    Hi Bart,
    here is what is in XML file for column:
    <Column name="FIRST_NAME" id="5E8F1EEC-287E-6496-C568-DFBF6321BD91">
    <sourceConnName>FDB11R21</sourceConnName>
    <sourceObjSchema>EMPLOYEES</sourceObjSchema>
    <sourceObjName>FIRST_NAME</sourceObjName>
    <createdBy></createdBy>
    <createdTime>2015-01-13 12:45:08 UTC</createdTime>
    <commentInRDBMS>First name of the employee. A not null column.</commentInRDBMS>
    <ownerDesignName>HR_870</ownerDesignName>
    <nullsAllowed>true</nullsAllowed>
    <useDomainConstraints>false</useDomainConstraints>
    <use>1</use>
    <logicalDatatype>LOGDT024</logicalDatatype>
    <dataTypeSize>20 BYTE</dataTypeSize>
    <autoIncrementCycle>false</autoIncrementCycle>
    </Column>
    <dataTypeSize>20 BYTE</dataTypeSize>
    So you need to set size to "20 BYTE" or "20 CHAR"
    Philip

  • Update required to this script

    Hi,
    This is a script to relink images by changing the names of the files in a folder etc.
    I am using Indesign CS4 and I would appreciate a update of this script to CS4 (previously worked in CS3) it still works in CS4 but not 100%.
    Could you also incorparate one little thing?
    I have a page with multiple link on it. Everytime it updates the links, it asks me to approve every single link updated. I would like the script to have a feature "update all" without having to click "yes" (for approve) a million time when I know the links are all good.
    Here is a copy of the script. ( I notice some is in what seems to be Russian, mainly the top half of the script is in Russian)
    Change Links
    version 3.5
    Relink the images of the document to files with identical names in choosen folder.
    An InDesign CS2-CS3 JavaScript
    OS: Mac OS X, Windows XP
    You use this script at your own fear and risk.
    © 2009 Dmitriy Lapayev ([email protected])
    The script is intended to replace the images of the document on files with identical names
    from selected folder.
    Main tasks:
    1) Replace the missing files of the non-standard "Package Publication",
    including interconnection transfers projects like: "Windows" to "MAC OS X" or from "MAC OS X" to "Windows";
    2) The substitution of the preliminary document images on the processed files
    with unchanged proportions of the height and width
    (without the “Crop Image” and changes “Canvas Size”).
    In parentheses elements of the dialog indicates the number of found objects of this type.
    When launched, need select a folder, which contains the files that are intended to replace in the document.
    Realized:
    • choice of language when you first start: Russian or English
    (full support of the Russian language is available only for OS Windows)
    • extraction of embedded image files of the document;
    • check the attribute «nonprinting»;
    • search for types of document images;
    • search for files extensions in the selected folder;
    • Unlock Position for groups and objects to the replacement of files;
    • save the settings and selected folder path in the ini-file
    (created when you first run the script).
    Relink images:
    1) stored the geometric coordinates of images (Geometric Bounds), if not choosed
    settings: Center Content, Scale 100% or Angles 0 °;
    preservation of Geometric Bounds (top left and bottom right points) of the original image
    is intended to replace the links to images with unchanged proportions of the height and width
    (without «crop» - Crop Image and resizing - Canvas Size);
    2) ignored:
    • files with duplicate names (with the extension) -
    when you change the type of files «identical», without an extension -
    with the replacement for the selected type, complete with different full file names;
    • outside pages images (PB);
    • images posted from the clipboard (without link).
    Скрипт предназначен для замещения связанных файлов документа
    на файлы с аналогичными именами в выбранной папке.
    Базовые задачи:
    1) восстановление потерянных связей с файлами
    нестандартных «сборок проектов» (Package Publication) при переносе, включая межсистемный;
    2) замещение предварительных изображений в документе на обработанные.
    В круглых скобках элементов диалога настроек скрипта указывается количество найденных
    объектов данного типа.
    При запуске скрипта выбирается папка, которая содержит файлы, предназначенные
    для замещения в документе.
    Настройки скрипта:
    1) выбор изображений документа по состоянию связи с файлом;
    2) диапазон страниц замещения изображений, задается именами страниц и секциями документа
    (выбор секции обладает большим приоритетом);
    3) «Режим пошаговой замены» - Step Mode:
    • установка Center Content - размещать изображение по центру фрейма (контейнера);
    • установка Scale 100% - вертикальному и горизонтальному масштабированию изображения
    присваивается значение 100%;
    • установка Angles 0° – углам вращения и горизонтального сдвига присваивается значение 0°;
    • установка Check Rotate 90° - проверка вращение изображения (±90°),
    при обнаружении несоответствия отношения вертикального и горизонтального масштабов
    исходного и обработанного изображений;
    • установка Clipping Path to None – отключать «обтравочный» путь;
    • установка Check Transparency - проверка параметров прозрачности изображений и фреймов
    (Blending Settings: Opacity < 100%, Blending Mode - не «Normal»);
    4) Including Non-printing Objects - включая объекты с атрибутом «не печатать»
    при замещении связей с файлами;
    5) «Choice of File Extensions:» - выбор типов связанных файлов документа
    для замены в заданном диапазоне страниц;
    6) «File Names:» - установки для сопоставления имен исходных и найденных в выбранной папке файлов,
    если имена файлов не совпадают («неидентичные» - «Non-identical»):
    • «The End of File Name:» - выбор окончания имени файла, содержащего более одного символа «точка»;
    • «Choice of File Extensions:» - выбор расширения файлов в указанной папке;
    7) «Show Relink Report» - формирование и отображение отчета замещения связей с файлами.
    Реализовано:
    • выбор языка интерфейса скрипта при первом запуске: русский или английский
    (полная поддержка русского языка доступна только на ОС «Windows»)
    • извлечение внедренных файлов изображений документа;
    • проверка атрибута «не печатать»;
    • поиск типов связанных файлов документа;
    • поиск расширений файлов в выбранной папке;
    • Unlock Position для групп и объектов при замещении файлов;
    • сохранение настроек и пути к выбранной папке в файле инициализации
    (создается при первом запуске скрипта).
    При замещении изображений:
    1) сохраняются геометрические координаты изображений – Geometric Bounds, если не установлено
    в настройках: Center Content, Scale 100% или Angles 0°;
    сохранение Geometric Bounds (верхняя левая и нижняя правая точки) исходного изображения
    предназначено для замещения на связи с файлами при неизменных пропорциях высоты
    и ширины изображений, т.е. без «кадрирования» - Crop Image и изменения размера - Canvas Size;
    2) игнорируются:
    • файлы с дублирующимися именами с расширением - при замене на тип файлов «идентичный»,
    без расширения - при замене на выбранный тип, при отличающихся полных именах файлов;
    • изображения, находящиеся вне страниц документа (PB);
    • изображения, помещенные из буфера обмена (отсутствует связь с файлом).
    © 2009 Дмитрий Лапаев ([email protected])
    with (app) {
    const myScrVer = "3.5";
    const myScrName = "Change Links";
    // максимальная величина допуска отношений горизонтального и вертикального масштабов изображений
    const myVGScDop = 0.01;
    // copyright
    var mn = "\u00A9\ \u0044\u006D\u0069\u0074\u0072\u0069\u0079\ \u004C\u0061\u0070\u0061\u0079\u0065\u0076";
    // User Interaction Level
    scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
    // создание файла инициализации
    const IniFName = "ChLinks_ini.txt";
    var MyStrIniF = "";
    var lgclIniF = new File (activeScript.path + "/" + IniFName);
    if (!lgclIniF.exists) {
      // Выбор языка интерфейса
      var s_Locale = "";
      var myLanguageSelectDialog = dialogs.add({name: "Select Language (" + $.locale + ")", canCancel: false})
      with (myLanguageSelectDialog.dialogColumns.add().borderPanels.add()) {
       var languagesNames = new Array ("Русский", "English");
       var languagesSelect = dropdowns.add({stringList:languagesNames, selectedIndex: 0, minWidth: 160});
      myLanguageSelectDialog.show();
      switch (languagesSelect.selectedIndex) {
       case 0: s_Locale = "ru"; break;
       case 1: s_Locale = "ua"; break;
       case 2: s_Locale = "en"; break;
      myLanguageSelectDialog.destroy();
      MyStrIniF += "var inScriptName = \"" + myScrName + " " + myScrVer + "\";\n";
      MyStrIniF += "var inpVLinkStM = 0;\n";
      MyStrIniF += "var inpDefPath = \"\";\n";
      MyStrIniF += "var inStepMode = true;\n";
      MyStrIniF += "var inShowReport = true;\n";
      MyStrIniF += "var inClippPathNone = false;\n";
      MyStrIniF += "var inCenterCont = false;\n";
      MyStrIniF += "var inScale100 = false;\n";
      MyStrIniF += "var inAngles0 = false;\n";
      MyStrIniF += "var inCheckRotImage = false;\n";
      MyStrIniF += "var inpOrdDotN = true;\n";
      MyStrIniF += "var inpNotIdcl = true;\n";
      MyStrIniF += "var inpInSec = false;\n";
      MyStrIniF += "var inCheckTransp = false;\n";
      MyStrIniF += "var inNonprintIm = true;\n";
      MyStrIniF += "var sel_Language = \"" + s_Locale + "\";\n";
      MyStrIniF += "const mn = \"" + mn + "\";";
      lgclIniF.open("w");
      if (lgclIniF.write(MyStrIniF)) {
       alert (IniFName + " successfully created!\n(Default Script Options)", myScrName + " " + myScrVer, false);
       lgclIniF.close();
       eval ("//@include \'" + IniFName + "\';");
      else {alert("Unable to write the ini-file!"); exit();}
    else {eval ("//@include \'" + IniFName + "\';"); cr();}
    // тип файловой системы (ОС)
    var WonFS = File.fs;
    if (WonFS == "Macintosh") {WonFS = "Mac OS X";}
    // язык интерфейса
    $.localize = true;
    $.locale = sel_Language;
    const copyRight = localize ({ru: "\u00A9\ Дмитрий Лапаев", en: mn});
    const local_Folder = localize ({ru: "Папка: ", en: "Folder: "});
    const local_inFolder = localize ({ru: "папке: ", en: "a Folder: "});
    const local_In = localize ({ru: " в ", en: " in "});
    const local_To = localize ({ru: " на ", en: " to "});
    const local_FNames = localize ({ru: "имена файлов", en: "names"});
    const local_Report = localize ({ru: "Отчет замещения файлов", en: "Relink Report"});
    const local_Relink = localize ({ru: "Заменить", en: "Relink"});
    const local_Found= localize ({ru: "Найдено", en: "Found"});
    const local_inSections = localize ({ru: "cекциях", en: "sections"});
    const local_Total = localize ({ru: "Всего: ", en: "Total: "});
    const local_Links= localize ({ru: "связей с файлами", en: "Links"});
    const local_Files = localize ({ru: "-файлы", en: "-files"});
    const local_LinkStatus = localize ({ru: "состояние связей -", en: "link status -"});
    const local_OfSectionsN = localize ({ru: " cекции №", en: " of section #"});
    const local_OfDocument = localize ({ru: " документа", en: " of document"});
    const local_Conditions = localize ({ru: "Условия замещения:", en: "Conditions:"});
    const local_ApplyChanges = localize ({ru: "Сохранить изменения?", en: "Apply Changes?"});
    const local_ContinueRelink = localize ({ru: "Продолжить замещение файлов?", en: "Continue Relink Files?"});
    const local_RepInf_1 = localize ({ru: "успешно заменено", en: "Successfully relink"});
    const local_RepInf_2 = localize ({ru: "отсутствуют в папке", en: "Links to not existing files"});
    const local_RepInf_3 = localize ({ru: "игнорировано из-за дубликата имени", en: "Ignored links with duplicates of names"});
    const local_RepInf_4 = localize ({ru: "отменено пользователем", en: "Canceled by user"});
    const local_RepInf_5 = localize ({ru: "объекты \"не для печати\"", en: "Оbjects with attribute \"Nonprinting\""});
    // надписи диалогов
    const RotateLabel = localize ({ru: "Вращать", en: "Rotate"});
    const ChoiceFileFormatsLabel = localize ({ru: "Выбор форматов файлов:", en: "Choice of File Formats:"});
    const FileNameLabel = localize ({ru: "Имена файлов:", en: "File Names:"});
    const PageRangeLabel = localize ({ru: "Диапазон страниц:", en: "Range of Pages:"});
    const EndPageNameLabel = localize ({ru: "Окончание имени:", en: "The End of File Name:"});
    const ChoiceExtLabel = localize ({ru: "Выбор типа файлов:", en: "Choice of File Extensions:"});
    var nameNCE =  "identical";
    if (WonFS == "Windows") {nameNCE =  localize ({ru: "идентичные", en: nameNCE});}
    var nameNon =  "Non-";
    if (WonFS == "Windows") {nameNon =  localize ({ru: "не", en: nameNon});}
    var selShowPeport = "Show Relink Report";
    if (WonFS == "Windows") {selShowPeport = localize ({ru: "Отобразить отчет", en: selShowPeport});}
    var selSections = "Sections:";
    if (WonFS == "Windows") {selSections = localize ({ru: "Cекции документа:", en: selSections});}
    var selFDot = "First Dot";
    if (WonFS == "Windows") {selFDot = localize ({ru: "первая точка", en: selFDot});}
    var selLastDot = "Last Dot";
    if (WonFS == "Windows") {selLastDot = localize ({ru: "последняя точка", en: selLastDot});}
    var selStepMode = "Step Mode";
    if (WonFS == "Windows") {selStepMode = localize ({ru: "Режим пошаговой замены", en: selStepMode});}
    var selFitCenter = "Center Content";
    if (WonFS == "Windows") {selFitCenter = localize ({ru: "по центру фрейма", en: selFitCenter});}
    var selVHScale100 = "Scale 100%";
    if (WonFS == "Windows") {selVHScale100 = localize ({ru: "масштаб 100%", en: selVHScale100});}
    var selAngles0 = "Angles 0°";
    if (WonFS == "Windows") {selAngles0 = localize ({ru: "углы 0°", en: selAngles0});}
    var selСhRotate90 = "Check Rotate 90°";
    if (WonFS == "Windows") {selСhRotate90 = localize ({ru: "проверять вращение на 90°", en: selСhRotate90});}
    var selClippingPathNone = "Clipping Path to None";
    if (WonFS == "Windows") {selClippingPathNone = localize ({ru: "отключать обтравочный путь", en: selClippingPathNone});}
    var selChTransparency = "Check Transparency";
    if (WonFS == "Windows") {selChTransparency = localize ({ru: "проверять прозрачность", en: selChTransparency});}
    var selNonprintingImages = "Including Non-printing Objects";
    if (WonFS == "Windows") {selNonprintingImages = localize ({ru: "Включая объекты не для печати", en: selNonprintingImages});}
    var selRotate90CW = "90° CW";
    if (WonFS == "Windows") {selRotate90CW = localize ({ru: "90° по часовой стрелке", en: selRotate90CW});}
    var selRotate90CCW = "90° CCW";
    if (WonFS == "Windows") {selRotate90CCW = localize ({ru: "90° против", en: selRotate90CCW});}
    // массив выбора состояний связей
    var inpVLinkStArr = new Array();
    if (WonFS == "Windows") {
      inpVLinkStArr = [[localize ({ru: "отсутствующие", en: "Missing"}), false], [localize ({ru: "нормальные", en: "Normal"}), false], [localize ({ru: "модифицированные", en: "Modified"}), false], [localize ({ru: "все связи", en: "All Links"}), false]];
    else {
      inpVLinkStArr = [["Missing", false], ["Normal", false], ["Modified", false], ["All Links", false]];
    inpVLinkStArr[inpVLinkStM][1] = true;
    // сообщения скрипта
    var alertWithoutLink = localize ({ru: "Объект без связи с файлом!\n(импортирован из буфера обмена)\nПродолжить работу?", en: "Object without link!\n(imported from clipboard)\nContinue?"});
    var alertAfterRotateSAngle = localize ({ru: "Угол горизонтального сдвига изображения равен", en: "The skewing angle applied to the Image is"});
    var alertAfterRotateSA0 = localize ({ru: "После поворота изображения это значение будет некорректным!\nУстановить 0°?", en: "After rotate this value is incorrect!\nSet Shear Angle to 0°?"});
    var alertNonprinting = localize ({ru: "Найден объект:", en: "Non-printing Object:"});
    var alertNonprintToOff = localize ({ru: "Отключить атрибут \"не для печати\"?", en: "Set attribute \"Nonprinting\" to Off?"});
    var alertEmbedded = localize ({ru: "внедренных изображений", en: "embedded files"});
    var alertUnembed = localize ({ru: "Сохранить внедренные изображения?", en: "Unembed this files?"});
    var alertAlreadyExist = localize ({ru: "уже существует в указанной папке.\nПерезаписать этот файл?", en: "already exist in the folder.\nDo you want to overwrite the file with the embedded data?"});
    var alertСreateNewFolder = localize ({ru: "Выберите папку для сохранения файлов", en: "Select the Folder where files will be created"});
    var alertNotMatchLinks = localize ({ru: "Не найдено соответствующих связей с файлами!", en: "No matching Links!"});
    var alertlEmptyFolder = localize ({ru: "пустая\nили содержит недопустимые символы в имени!\n(только для Mac OS X)", en: "is empty\nor contains illegal characters in its name!\n(Mac OS X)"});
    var alertNotFoundImages = localize ({ru: "Не найдено файлов в папке:", en: "Сannot Find Files in a Folder:"});
    var selFolderWithImages = localize ({ru: "Выберите папку с файлами для замещения в документе", en: "Select a Folder with files for Relink"});
    var andTryAgain =  localize ({ru: "и выполните скрипт повторно.", en: "and try again."});
    var noSaveDocumentAlert =  localize ({ru: "Пожалуйста сохраните документ ", en: "Please Save "});
    var noLinks = localize ({ru: "В открытом документе нет связанных файлов!", en: "No Links in Document!"});
    var noOpenDocsAlert = localize ({ru: "Отсутствуют открытые документы!\nПожалуйста откройте документ", en: "No Documents are Open!\nPlease Open a Document"}) + " " + andTryAgain;
    $.locale = null;
    // проверка открытых документов
    if (documents.length == 0) {alert (noOpenDocsAlert, inScriptName, false); exit();}
    var myDoc = activeDocument;
    try {activeDocument.filePath}
    catch (error) {alert (noSaveDocumentAlert + myDoc.name + " " + andTryAgain, inScriptName, false); exit();}
    if (myDoc.links.length == 0) {alert (noLinks, inScriptName, false); exit();}
    // версия InDesign
    try {const InDver = version.substr (0, 5);}
    catch (error) {alert (inScriptName + "\nis not compatible with this version of InDesign!", "", true); exit();}
    // количество страниц в документе
    var myDocPgsLength = myDoc.pages.length;
    // выбор папки с изображениями
    var myNIdir = Folder.selectDialog (selFolderWithImages, inpDefPath);
    if (myNIdir != null) {var MyNewDir = myNIdir; }
    else {exit();}
    // определяем расширения файлов выбранной папки, исключаем системные
    var MyFiles = MyNewDir.getFiles("*");
    if (MyFiles.length == 0) {
      alert(local_Folder + "\'" + Folder.decode(MyNewDir.name) + "\' " + alertlEmptyFolder, inScriptName, false);
      exit();
    // типы расширений файлов в выбранной папки
    var NewImagesExtType = new Array();
    NewImagesExtType =  ExtenSysCheck (MyFiles);
    if (NewImagesExtType.length == 0) {
      alert (alertNotFoundImages + " \'" + Folder.decode(MyNewDir.name) + "\'!", inScriptName, false);
      exit();
    // заполняем массив типов изображений документа
    var DocSelType = new Array();
    var TypeFileMyDoc = GetFileTypeInDoc (myDoc);
    for (var objCounter = 0; objCounter < TypeFileMyDoc.length; objCounter++) {
      DocSelType.push ([true, TypeFileMyDoc[objCounter][0]]);
    // считаем связи с файлами по состояниям
    var myLinksCounters = myDocLinksCounters(myDoc);
    var ArrStatusL = new Array();
    for (objCounter = 0; objCounter < 4; objCounter++) {
      ArrStatusL.push("(" + myLinksCounters[objCounter] + ") ");
    // имена первой и последней страниц документа
    var DocNumberPageStart = myDoc.pages[0].name;
    var DocNumberPageEnd = myDoc.pages[myDocPgsLength-1].name;
    // массив параметров секций
    var ASecPar = SecRangeOfPages (myDoc);
    // Диалог
    var myDialog = dialogs.add({name: inScriptName + " (InDesign " + InDver + " on " + WonFS + ")  " + copyRight});
    var myCheckArray = new Array();
    with (myDialog.dialogColumns.add().dialogRows.add()) { 
      with (borderPanels.add().dialogColumns.add()) {
       // панель выбора изображений документа по типу состояния связи с файлом
       with (dialogRows.add()) {
        staticTexts.add({staticLabel: local_Relink + ":"});
        var myDocLinksSatus = radiobuttonGroups.add();
        for (var StC = 0; StC < inpVLinkStArr.length; StC++) {
         myDocLinksSatus.radiobuttonControls.add({staticLabel: ArrStatusL[StC] + inpVLinkStArr[StC][0], checkedState: inpVLinkStArr[StC][1]});
       // панель выбора диапазона страниц
       with (borderPanels.add().dialogColumns.add()) {
        dialogRows.add().staticTexts.add({staticLabel: PageRangeLabel});
        // задаем имена первой и последней страниц документа
        with(dialogRows.add()) {
         var PageRangeStart = dialogColumns.add().textEditboxes.add({editContents:DocNumberPageStart, minWidth: 90});
         var PageRangeEnd = dialogColumns.add().textEditboxes.add({editContents:DocNumberPageEnd, minWidth: 90});
        var myReportTotalPages  = local_Total + myDocPgsLength;
        if (ASecPar.length > 1) {myReportTotalPages += local_In + ASecPar.length + " " + local_inSections;}
        dialogRows.add().staticTexts.add({staticLabel: myReportTotalPages});
        // секции документа
        var SecNSelect = 0;
        if (ASecPar.length > 1) {
         var MySelNumbSection = dialogRows.add().enablingGroups.add({staticLabel: selSections, checkedState: inpInSec});
         var SecNList = new Array();
         var nSecPx = "";
         var mySecRange;
         with (MySelNumbSection) {
          for (objCounter = 0; objCounter < ASecPar.length ; objCounter++) {
           if (ASecPar[objCounter][1]  == true) {nSecPx = ASecPar[objCounter][2];}
           else {nSecPx = "";}
           mySecRange = nSecPx + ASecPar[objCounter][3] + "-" + nSecPx + (ASecPar[objCounter][3]+ASecPar[objCounter][4]-1);
           SecNList.push((objCounter+1) + "\| " + mySecRange);
          SecNSelect = dropdowns.add({stringList: SecNList, selectedIndex: 0, minWidth: 165});
       // пошаговый режим
       var MyStepByStepMode = dialogRows.add().enablingGroups.add({staticLabel: selStepMode, checkedState: inStepMode});
       with (MyStepByStepMode.dialogColumns.add()) {
        var myCenterContent = checkboxControls.add({staticLabel: selFitCenter, checkedState: inCenterCont, minWidth: 191});
        with (dialogRows.add()) {
         var myScale100 = checkboxControls.add({staticLabel: selVHScale100, checkedState: inScale100});
         var myAngles0 = checkboxControls.add({staticLabel: selAngles0, checkedState: inAngles0});
        var myPossRotateIm = checkboxControls.add({staticLabel: selСhRotate90, checkedState: inCheckRotImage});
        var myClippPathNone = checkboxControls.add({staticLabel: selClippingPathNone, checkedState: inClippPathNone});
        var myChTransparency = checkboxControls.add({staticLabel: selChTransparency, checkedState: inCheckTransp});
       var myNonprintImagesRelink = checkboxControls.add({staticLabel: selNonprintingImages, checkedState: inNonprintIm});
      // панель выбора типов файлов документа для замены
      with (borderPanels.add().dialogColumns.add()) {
       with(borderPanels.add().dialogColumns.add()) {
        dialogRows.add().staticTexts.add({staticLabel: ChoiceFileFormatsLabel});
        for (objCounter = 0; objCounter < TypeFileMyDoc.length; objCounter++)
        myCheckArray[objCounter] = checkboxControls.add ({staticLabel: Str_inskbk(TypeFileMyDoc[objCounter][0]) + " (" + TypeFileMyDoc[objCounter][1] + ")", checkedState: true, minWidth: 180});
       dialogRows.add().staticTexts.add({staticLabel: FileNameLabel});
       var MyTypeNFname = dialogRows.add().enablingGroups.add({staticLabel: nameNon + nameNCE, checkedState: inpNotIdcl});
       with (MyTypeNFname.dialogColumns.add()) {
        // панель выбора окончания имени файла (для имен связанных файлов с несколькими точками в имени)
        with(borderPanels.add().dialogColumns.add()) {
         dialogRows.add().staticTexts.add({staticLabel: EndPageNameLabel});
         var myDotFLord = dialogRows.add().radiobuttonGroups.add();
         myDotFLord.radiobuttonControls.add({staticLabel: selFDot, checkedState: inpOrdDotN, minWidth: 155});
         myDotFLord.radiobuttonControls.add({staticLabel: selLastDot, checkedState: !inpOrdDotN});
        // панель выбора расширений файлов, найденных в папке
        with(borderPanels.add().dialogColumns.add()) {
         dialogRows.add().staticTexts.add({staticLabel: ChoiceExtLabel});
         var MyTypesForChange = new Array();
         for (objCounter = 0; objCounter < NewImagesExtType.length; objCounter++)
         MyTypesForChange.push("." + NewImagesExtType[objCounter]);
         var myNewImagesExtSelect = dropdowns.add({stringList:MyTypesForChange, selectedIndex: 0, minWidth: 155});
         dialogRows.add().staticTexts.add({staticLabel: local_Found + local_In + local_inFolder + NewImagesExtType.length}); 
       var myShowReportRelink = checkboxControls.add({staticLabel: selShowPeport, checkedState: inShowReport});
    // отображаем диалог
    var myResult = myDialog.show();
    if (!myResult) {myDialog.destroy(); exit();}
    // переменные выбранных установок
    var myIndexButLinksSt = myDocLinksSatus.selectedButton;
    var myButFirstDotName = false;
    if (myDotFLord.selectedButton == 0) {myButFirstDotName = true;}
    var selSectPR = inpInSec;
    try {selSectPR = MySelNumbSection.checkedState;}
    catch (e){}
    var selChTransp = myChTransparency.checkedState;
    var selScale_100 = myScale100.checkedState;
    var selAngles_0 = myAngles0.checkedState;
    var selCenterCont = myCenterContent.checkedState;
    var selChRotate = myPossRotateIm.checkedState;
    var selClipPathNone = myClippPathNone.checkedState;
    var selStepMode = MyStepByStepMode.checkedState;
    var MyNDirAbsURI = MyNewDir.absoluteURI;
    // записываем выбранные установки в файл инициализации
    MyStrIniF = "var inScriptName = \"" + myScrName + " " + myScrVer + "\";\n";
    MyStrIniF += "var inpVLinkStM = " + myIndexButLinksSt + ";\n";
    // MyStrIniF += "var inpDefPath = \"" + MyNDirAbsURI.substr(0, MyNDirAbsURI.lastIndexOf("/")) + "\";\n";
    MyStrIniF += "var inpDefPath = \"" + MyNDirAbsURI + "\";\n";
    MyStrIniF += "var inStepMode = " + selStepMode + ";\n";
    MyStrIniF += "var inShowReport = " + myShowReportRelink.checkedState + ";\n";
    MyStrIniF += "var inClippPathNone = " + selClipPathNone + ";\n";
    MyStrIniF += "var inCenterCont = " + selCenterCont + ";\n";
    MyStrIniF += "var inScale100 = " + selScale_100 + ";\n";
    MyStrIniF += "var inAngles0 = " + selAngles_0 + ";\n";
    MyStrIniF += "var inCheckRotImage = " + selChRotate + ";\n";
    MyStrIniF += "var inpOrdDotN = " + myButFirstDotName + ";\n";
    MyStrIniF += "var inpNotIdcl = " + MyTypeNFname.checkedState + ";\n";
    MyStrIniF += "var inpInSec = " + selSectPR + ";\n";
    MyStrIniF += "var inCheckTransp = " + selChTransp + ";\n";
    MyStrIniF += "var inNonprintIm = " + myNonprintImagesRelink.checkedState + ";\n";
    MyStrIniF += "var sel_Language = \"" + sel_Language + "\";\n";
    MyStrIniF += "const mn = \"" + mn + "\";";
    lgclIniF.open("w");
    if (lgclIniF.write(MyStrIniF)) {lgclIniF.close();}
    else {alert ("Error writing to the ini-file!", inScriptName, true);}
    // переменные диапазона страниц для поиска изображений
    var PRSedcont = PageRangeStart.editContents;
    var PREedcont = PageRangeEnd.editContents;
    var mySelSecStartAbs = 0;
    var mySelSecEndsAbs = myDocPgsLength;
    if (ASecPar.length > 1 && selSectPR == true) {
      SecNSelect = SecNSelect.selectedIndex;
      mySelSecStartAbs = ASecPar[SecNSelect][0];
      mySelSecEndsAbs = mySelSecStartAbs + ASecPar[SecNSelect][4];
    // присваиваем выбранный тип для замещения
    var mySelectedExt ;
    var ResIndexSelectExt = myNewImagesExtSelect.selectedIndex ;
    if (MyTypeNFname.checkedState == false) {mySelectedExt = nameNCE;}
    else {mySelectedExt = NewImagesExtType[ResIndexSelectExt];}
    var mySTdocStr = new Array();
    // выбранные для замещения типы документа
    for (objCounter = 0; objCounter < DocSelType.length; objCounter++) {
      DocSelType[objCounter][0] = myCheckArray[objCounter].checkedState;
      if (DocSelType[objCounter][0] == true) mySTdocStr.push(Str_inskbk(DocSelType[objCounter][1]));
    // формируем массив изображений документа по установленным условиям
    var MyGraphicsPages = new Array();
    // выборка всех изображений из заданного диапазона страниц
    MyGraphicsPages = RangePagesGraphics (myDoc, PRSedcont, PREedcont, selSectPR, mySelSecStartAbs, mySelSecEndsAbs);
    PRSedcont = MyGraphicsPages[1]
    PREedcont = MyGraphicsPages[2];
    // массив имен файлов изображений с атрибутом "не печатать"
    var myImagesWithANonpr = new Array();
    // удаляем (при выборе в диалоге) изображения с атрибутом "не печатать"
    MyGraphicsPages = myPrint_ObjArray (MyGraphicsPages[0], MyStepByStepMode.checkedState, myNonprintImagesRelink.checkedState, myImagesWithANonpr)
    // выбираем по статусу состояния связи с файлом изображения
    MyGraphicsPages = selMissNormModAll_Links (MyGraphicsPages, myIndexButLinksSt);
    // выборка по обозначенным типам изображений
    MyGraphicsPages = getTypeRastrImages (MyGraphicsPages, DocSelType);
    // удаляем файлы с дублирующимися именами при разных путях
    MyGraphicsPages =  FindDuplicatesNames (MyGraphicsPages, mySelectedExt, myButFirstDotName);
    if (MyGraphicsPages.length == 0) {
      alert (alertNotMatchLinks, inScriptName, false);
      myDialog.destroy();
      exit();
    // переподстановка выбранных файлов:
    var beRotate = false;
    var ResRelinkErr = SelectedFiles_Relink (MyGraphicsPages, MyNDirAbsURI, mySelectedExt);
    // отчет
    ResRelinkErr.push(myImagesWithANonpr);
    if (myShowReportRelink.checkedState) {ReportErrorsRelink (ResRelinkErr, inpVLinkStArr[myIndexButLinksSt][0], PRSedcont, PREedcont, SecNSelect, selSectPR, mySTdocStr);}
    myDialog.destroy();
    exit();
    /* ФУНКЦИИ•••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• •••••••••••••••••••••••••••••••••••••••••••••••*/
    /* Функция возвращает массив счетчиков изображений документа по состоянию связи с файлом.
    Внедренные файлы предлагается извлечь в выбранную папку. */
    function myDocLinksCounters (inDDoc) {
    var aDocLinksL = inDDoc.links.length;
    var ArrLinksCount = new Array(0, 0, 0, aDocLinksL);
    var myEmbeddedLinks = new Array();
    for (var linkCounter = 0; linkCounter < aDocLinksL; linkCounter++) {
      if (inDDoc.links[linkCounter].status == LinkStatus.linkMissing) ArrLinksCount[0]++;
      if (inDDoc.links[linkCounter].status == LinkStatus.normal) ArrLinksCount[1]++;
      if (inDDoc.links[linkCounter].status == LinkStatus.linkOutOfDate) ArrLinksCount[2]++;
      if (inDDoc.links[linkCounter].status == LinkStatus.linkEmbedded) myEmbeddedLinks.push(inDDoc.links[linkCounter]);
    // для внедренных изображений
    if (myEmbeddedLinks.length > 0) {
      if (confirm (local_Found + " " + alertEmbedded + ": " + myEmbeddedLinks.length + "\n" + alertUnembed, "", inScriptName)) {
       // выбор папки
       var myUnmDir = Folder.selectDialog (alertСreateNewFolder, inDDoc.filePath);
       if (myUnmDir != null) {
        var MyNewUnembedDir = myUnmDir.absoluteURI; 
        for (linkCounter = 0; linkCounter < myEmbeddedLinks.length; linkCounter++){
         // если файл с таким же именем существует
         if (File(MyNewUnembedDir + "/" + myEmbeddedLinks[linkCounter].name).exists) {
          if (confirm (myEmbeddedLinks[linkCounter].name + " " + alertAlreadyExist, "", inScriptName)) {
           myEmbeddedLinks[linkCounter].unembed(Folder(MyNewUnembedDir));
           ArrLinksCount[1]++;
         else {
          myEmbeddedLinks[linkCounter].unembed(Folder(MyNewUnembedDir));
          ArrLinksCount[1]++;
    return ArrLinksCount;
    /* Функция удаляет из массива myObjArray изображения с атрибутом "не печатать"
    при myNonPrImSeld = false. При пошаговом режиме предлагается снять атрибут "не печатать"
    с изображений массива myObjArray.
    Формируется массив изображений с атрибутом "не печатать" myArrayNonprintingIm для отчета. */
    function myPrint_ObjArray(myObjArray, myStepModeTrue, myNonPrImSeld, myArrayNonprintingIm) {
    var myPrintObjArray= new Array();
    var myObjPr;
    for (var myCobj = 0; myCobj < myObjArray.length; myCobj++) {
      myObjPr = myObjArray[myCobj];
      if (myNonprint_ParentRe(myObjPr)) { 
       if(myStepModeTrue) {
        myObjPr.itemLink.show();
        if (confirm(alertNonprinting + " " + myObjPr.itemLink.name + "\n" + alertNonprintToOff)) {
         myNonpFalse_ParentRe (myObjPr);
         myPrintObjArray.push(myObjPr);
        else {
         myArrayNonprintingIm.push(myObjPr.itemLink.name);
       else {myArrayNonprintingIm.push(myObjPr.itemLink.name);}
       if (myNonPrImSeld == true) {myPrintObjArray.push(myObjPr);}
    else myPrintObjArray.push(myObjPr);
    return myPrintObjArray;
    /* Функция возвращает массив изображений, выбранных
    по состоянию связи c файлом из массива myImagesArray, */
    function selMissNormModAll_Links(myImagesArray, LinksStatusIndex, atrNonPrint) {
    if (LinksStatusIndex == 3) {return myImagesArray;}
    var myStatusImages = new Array();
    var myStatusLink;
    for (var myCounter = 0; myCounter < myImagesArray.length; myCounter++) {
      myStatusLink = myImagesArray[myCounter].itemLink.status;
      // отсутствующие
      if (myStatusLink == LinkStatus.linkMissing && LinksStatusIndex == 0)
       {myStatusImages.push(myImagesArray[myCounter]);}
      // нормальные
      if (myStatusLink == LinkStatus.normal && LinksStatusIndex == 1)
       {myStatusImages.push(myImagesArray[myCounter]);}
      // модифицированные
      if (myStatusLink == LinkStatus.linkOutOfDate && LinksStatusIndex == 2)
       {myStatusImages.push(myImagesArray[myCounter]);}
    return myStatusImages;
    /* Функция замещения связей с файлами. Возвращает массив с результатами замещения. */
    function SelectedFiles_Relink (MySeldGraphics, MyRFolder, myExten) {
    var myLink;
    var myNewLinkName = "";
    var myFileName = "";
    var myFileNameNoExt = "";
    var myRelinkFileName = "";
    var RelinkToFilesName = "";
    var myBlendingSettings = "";
    var myUpdLink;
    var RelinkYes = true;
    var ReportAlerts = new Array();
    var mySeccessRelinks = new Array();
    var DuplicatsCancelObj = new Array();
    var NoFileExistErrorLinks = new Array();
    var CancelByURelink = new Array();
    var OldGeomBounds;
    var myCountUndo;
    var myImageRotAng;
    var myImageShAngl;
    var myPossAngleW;
    var myNewFImage;
    var myPrSc;
    var myNewPrSc;
    var myIsImagePar = new Array();
    // считать координаты для разворота
    app.activeDocument.viewPreferences.rulerOrigin = RulerOrigin.spreadOrigin;
    // установка центральной точки (для поворота изображения)
    app.activeWindow.transformReferencePoint = AnchorPoint.centerAnchor;
    for (var i = 0; i < MySeldGraphics.length; i++) {
      myLink = MySeldGraphics[i][0].itemLink;
      myFileName = myLink.name;
      myFileNameNoExt = FileNameWtExt(myFileName, myButFirstDotName); 
      if (MySeldGraphics[i][1] == true) {   
       if (myExten == nameNCE) {myRelinkFileName = myFileName;}
       else {myRelinkFileName = myFileNameNoExt + "." + myExten;}
       // полное имя файла
       myNewLinkName = MyRFolder + "/" + myRelinkFileName;
       // переменная, описывающая операцию замещения файлов
       RelinkToFilesName = myFileName + local_To + myRelinkFileName;
       // если файл найден
       if (File (myNewLinkName).exists) {
        // запоминаем геометрические координаты предварительного изображения
        OldGeomBounds = MySeldGraphics[i][0].geometricBounds;
        // для пошагового режима
        if (selStepMode) {
         myLink.show();
         // blending settings
         if (selChTransp) {myBlendingSettings = OBJ_Effects(MySeldGraphics[i][0], InDver.substr(0,1));}
         RelinkYes = confirm (local_Relink + " " + RelinkToFilesName + "?\n\n" + myBlendingSettings);
         if (RelinkYes) {
          // запоминаем параметры предварительного изображения
          myIsImagePar = [MySeldGraphics[i][0].horizontalScale, MySeldGraphics[i][0].verticalScale, MySeldGraphics[i][0].shearAngle, MySeldGraphics[i][0].rotationAngle, OldGeomBounds];
          // отношение горизонтального и вертикального масштабов
          myPrSc = ScaleProp_HV(MySeldGraphics[i][0]);
        if (RelinkYes) {
         myLink.relink (File(myNewLinkName));
         myUpdLink = myLink.update();
         myNewFImage = myUpdLink.parent;
         myNewFImage.geometricBounds = OldGeomBounds;
         myCountUndo = 3;
         // для пошагового режима
         if (selStepMode == true) {
          // отключаем путь
          if (selClipPathNone == true) {
           if (myUpdLink.parent.clippingPath.clippingType != ClippingPathType.none) {
            myUpdLink.parent.clippingPath.clippingType = ClippingPathType.none;
            myCountUndo++;
          myUpdLink.show();
          // проверка вращения изображения на 90°
          if (selChRotate == true) {
           beRotate = false;
           // анализ вероятности поворота изображения (±90°)
           myNewPrSc = ScaleProp_HV(myNewFImage);
           if (Math.abs (myNewPrSc - myPrSc ) > myVGScDop) {
            // поворот изображения
            if (InDver.substr(0, 1) < 5) {myCountUndo = myRotateDialogCS2 (myNewFImage, myIsImagePar, myCountUndo);}
            else {myCountUndo = myRotateUIDialog (myNewFImage, myIsImagePar, myCountUndo);}
          // изображение - по центру фрейма
          if (selCenterCont) {
           myNewFImage.fit (FitOptions.centerContent);
           myCountUndo++;
          // углы - 0 градусов
          if (selAngles_0) {
           myCountUndo = image_ZeroAngle (myNewFImage, myCountUndo, beRotate);
          else {myCountUndo = anglesRounding (myNewFImage, myCountUndo);}
          // масштаб - 100 %
          if (selScale_100) {
           myCountUndo = image_VH_Scale_100 (myNewFImage, myCountUndo);
          else {myCountUndo = Scale_VH (myNewFImage, myPrSc, myCountUndo);}
          // применить изменения изображения
          if (confirm (local_ApplyChanges, "", inScriptName) == false) {
           myResUndo (myCountUndo);
           CancelByURelink.push(RelinkToFilesName);
           if (confirm (local_ContinueRelink, "", inScriptName) == false) break;
         else mySeccessRelinks.push(RelinkToFilesName);
        else mySeccessRelinks.push(RelinkToFilesName);
       else CancelByURelink.push(RelinkToFilesName);
      else NoFileExistErrorLinks.push(myRelinkFileName);
    else {if (myExten != nameNCE) {DuplicatsCancelObj.push(myFileNameNoExt);} else {DuplicatsCancelObj.push(myFileName);}}
    } // завершение цикла
    ReportAlerts.push(mySeccessRelinks);
    ReportAlerts.push(NoFileExistErrorLinks);
    ReportAlerts.push(DuplicatsCancelObj);
    ReportAlerts.push(CancelByURelink);
    ReportAlerts.push(MySeldGraphics.length);
    ReportAlerts.push(myExten);
    ReportAlerts.push(MyRFolder);
    return ReportAlerts;
    /* Функция формирует отчет по замещению фйлов изображений документа. */
    function ReportErrorsRelink (ArrErrorsLinks, myFoundSt, DnStPage, DnEndPage, DnNSec, SelSecY, TypeDocSel) {
    // массив сообщений отчета замены связей
    var StLabelsArr = new Array(local_RepInf_1, local_RepInf_2, local_RepInf_3, local_RepInf_4, local_RepInf_5);
    var myReportRelnk = app.dialogs.add({name: local_Report, canCancel: false});
    var myFragmD = myReportRelnk.dialogColumns.add().borderPanels.add().dialogColumns.add();
    with (myFragmD) {
      var myEndRT;
      var myBegRT;
      if (ArrErrorsLinks[5]  == nameNCE) {myEndRT = local_To + ArrErrorsLinks[5] + " " + local_FNames;}
      else {myEndRT = local_To + ArrErrorsLinks[5] + local_Files;} 
      if (myFoundSt != inpVLinkStArr[3][0]) {myBegRT = "1) " + local_LinkStatus + " \"" + myFoundSt + "\"";}
      else {myBegRT = "1) " + myFoundSt;}
      // формируем отчет
      with (dialogRows.add()) {
       dialogColumns.add().staticTexts.add({staticLabel: local_Conditions});
       with (dialogColumns.add()) {
        dialogRows.add().staticTexts.add({staticLabel: myBegRT});
        dialogRows.add().staticTexts.add({staticLabel: "2) " + myStrSymbolsReplace(TypeDocSel, ",", ", ") + myEndRT});
      dialogRows.add().staticTexts.add({staticLabel: local_Found + " " + local_Links + ": " + ArrErrorsLinks[4]});
      for (var myBordersCount = 0; myBordersCount <  StLabelsArr.length; myBordersCount++)
      if (myBordersCount < 4) {
       BorderTextsDropdowns (myFragmD, StLabelsArr[myBordersCount], ArrErrorsLinks[myBordersCount], 230);
      else {
       var mySecSelInfo;
       if (SelSecY) {mySecSelInfo =  local_OfSectionsN + (DnNSec+1);}
       else {mySecSelInfo = local_OfDocument;}
       dialogRows.add().staticTexts.add({staticLabel: PageRangeLabel + " " + DnStPage + " - " + DnEndPage + mySecSelInfo});
       BorderTextsDropdowns (myFragmD, StLabelsArr[myBordersCount], ArrErrorsLinks[7], 230);
      dialogRows.add().staticTexts.add({staticLabel: local_Folder + Folder.decode (Folder(ArrErrorsLinks[6]).name)});
    myReportRelnk.show();
    myReportRelnk.destroy();
    /* Функция формирует панель диалога с текстовой информацией
    и "выпадающим списком" неповторяющихся объектов массива myArray. */
    function BorderTextsDropdowns (myDialogArh, StrTextLabel, myArray, DdownsMinimW) {
    if (myArray.length > 0) {
    with (myDialogArh.borderPanels.add()) {
      staticTexts.add({staticLabel: StrTextLabel + ": " + myArray.length, minWidth: DdownsMinimW});
      try {dropdowns.add({stringList: myArray, selectedIndex: 0, minWidth: 320});}
      catch (e) {alert (e);}
    /* Функция возвращает массив графических объектов заданного диапазона страниц  документа.*/
    function RangePagesGraphics (mySegDoc, StartEC, EndgEC, SNSel, SecStart, SecEnd) {
    var NPageStart = -1;
    var CurrtPage;
    var myGaphicsCounter;
    var MyGraphicsP = new Array();
    var MyGraphicsPFinal = new Array();
    var myLinkType;
    // для диапазона страниц документа
    for (var myPageCounter = SecStart; myPageCounter <  SecEnd; myPageCounter++) {
      CurrtPage = mySegDoc.pages[myPageCounter];
      if (StartEC == CurrtPage.name) {NPageStart = CurrtPage.name;}
      if (NPageStart != -1) {
       // дополняем массив графическими объектами страницы
       for (myGaphicsCounter = 0; myGaphicsCounter <  CurrtPage.allGraphics.length; myGaphicsCounter++) {
        if (CurrtPage.allGraphics[myGaphicsCounter].itemLink != null) {MyGraphicsP.push(CurrtPage.allGraphics[myGaphicsCounter]);}
      // если имя текущей и финальной в диапазоне совпадают, то выходим из цикла
      if (EndgEC == CurrtPage.name)  break;
    EndgEC = CurrtPage.name;
    /* если не найдена первая страница в диапазоне,
    то считаем, что диапазон внутри секции задан неправильно,
    заполняем массив графическими объектами выбранной секции */
    if(SNSel == true & NPageStart == -1) {
      NPageStart = mySegDoc.pages[SecStart].name;
      for(myPageCounter = SecStart; myPageCounter <  SecEnd; myPageCounter++) {
       CurrtPage = mySegDoc.pages[myPageCounter];
       // дополняем массив графическими объектами страницы
       for(myGaphicsCounter = 0; myGaphicsCounter <  CurrtPage.allGraphics.length; myGaphicsCounter++) {
        if (CurrtPage.allGraphics[myGaphicsCounter].itemLink != null) {MyGraphicsP.push(CurrtPage.allGraphics[myGaphicsCounter]);}
      EndgEC = CurrtPage.name;
    MyGraphicsPFinal.push(MyGraphicsP);
    MyGraphicsPFinal.push(NPageStart);
    MyGraphicsPFinal.push(EndgEC);
    return MyGraphicsPFinal;
    /* Функция возвращает массив параметров секций документа.
    ArrFSecPageNumbers [section number][0] - порядковый номер первой страницы секции,
    ArrFSecPageNumbers [section number][1] - "true" - включать префикс секции при нумерации,
    ArrFSecPageNumbers [section number][2] - префикс секции,
    ArrFSecPageNumbers [section number][3] - номер первой страницы секции,
    ArrFSecPageNumbers [section number][4] - количество страниц в секции.*/
    function SecRangeOfPages (myDocument) {
    var mySecEnd = 0;
    var ArrFSecPageNumbers = new Array();
    var SectionOfPage = myDocument.pages[0].appliedSection;
    var SecPrefixName = SectionOfPage.sectionPrefix;
    var SecPnumStart =  SectionOfPage.pageNumberStart;
    var SecIncludePrfx = SectionOfPage.includeSectionPrefix;
    ArrFSecPageNumbers.push([0, SecIncludePrfx, SecPrefixName, SecPnumStart, 0]);
    for (var myPageCounter = 0; myPageCounter <  myDocument.pages.length; myPageCounter++) {
      CurrentSection = myDocument.pages[myPageCounter].appliedSection;
      if (SectionOfPage != CurrentSection) {
       SecPrefixName = CurrentSection.sectionPrefix;
       SecPnumStart =  CurrentSection.pageNumberStart;
       SecIncludePrfx = CurrentSection.includeSectionPrefix;
       ArrFSecPageNumbers[ArrFSecPageNumbers.length-1][4] = mySecEnd;
       mySecEnd = 0;
       ArrFSecPageNumbers.push([myPageCounter, SecIncludePrfx, SecPrefixName, SecPnumStart, mySecEnd]);
       SectionOfPage = CurrentSection;
      mySecEnd++;
    ArrFSecPageNumbers[ArrFSecPageNumbers.length-1][4] = mySecEnd;
    return ArrFSecPageNumbers;
    /* Функция удаления папок и системных файлов из массива объектов выбранной папки.
    Возвращает массив типов файлов (расширений). */
    function ExtenSysCheck (ArrayFilesExt) {
    var GrFilesExtArr = new Array();
    var CurrFile;
    for (var myCr = 0; myCr < ArrayFilesExt.length; myCr++) {
      CurrFile = ArrayFilesExt[myCr];
      // не папка, не системный файл
      if (typeof CurrFile.open != "undefined" && !MacOsXSysFile(CurrFile))
      GrFilesExtArr.push(FileNExt(CurrFile));
    GrFilesExtArr = getUniqObjArray(GrFilesExtArr);
    return GrFilesExtArr;
    /* Функция определения "системного файла" по расширению,
    если имя файла начинается с точки, то определяем его как системный файл (для Mac OS X). */
    function MacOsXSysFile(FileNamePath) {
    var myFileNamePath = String(FileNamePath);
    var EndFullPath = myFileNamePath.lastIndexOf("/");
    var myFileFirstT = myFileNamePath.substr(EndFullPath+1, 1);
    if (myFileFirstT == ".") {return true;}
    var ExtCurrFile = FileNExt (myFileNamePath);
    if(ExtCurrFile.length > 2 && ExtCurrFile.length < 5) {
      var SysExtArr = new Array ("DAT","VOL","APP","INI","SYS","COM","BAT","BAK", "ATM","TMP","DLL","REG","OLD","LOG","CFG","JSX","OTF","PFB","PFM","TTF","FON","LNK","EXE" );
      for (var extCr = 0; extCr < SysExtArr.length; extCr++) {
       if (ExtCurrFile == SysExtArr[extCr] || ExtCurrFile == SysExtArr[extCr].toLowerCase()) return true;}
    else return true;
    return false;
    /* Функция проверки дубликатов имен файлов
    (с расширением - при замене на идентичный тип или без расширения).
    Возвращает массив графических объектов с "разрешением замены" - ArrayGraphObjReLinksSt.
    Игнорируются файлы с дублирующимися именами:
    с расширением - при замене на тип файлов "идентичный",
    без расширения - при замене на выбранный тип, при отличающихся полных именах файлов. */
    function FindDuplicatesNames (ArrayGraphObj, myextSel, DotFirst) {
    var NameNoExt = "";
    var NameNoExtArr = new Array();
    var ArrayGraphObjReLinksSt = new Array();
    var IndFD = new Array();
    // заполняем массив имен файлов
    for (var myCr = 0; myCr < ArrayGraphObj.length; myCr++) {
      if (myextSel != nameNCE) {NameNoExt = FileNameWtExt (ArrayGraphObj[myCr].itemLink.name, DotFirst);}
      else {NameNoExt = ArrayGraphObj[myCr].itemLink.name;}
      NameNoExtArr.push (NameNoExt);
    for (myCr = 0; myCr < ArrayGraphObj.length; myCr++) {
      var PathExtArr = new Array();
      IndFD = checkDoubled (NameNoExtArr, NameNoExtArr[myCr]);
      if (IndFD.length > 1){
        for (var myDuplidx = 0; myDuplidx < IndFD.length; myDuplidx++) {PathExtArr.push(ArrayGraphObj[IndFD[myDuplidx]].itemLink.filePath);}   
        if (getUniqObjArray(PathExtArr).length == 1) {ArrayGraphObjReLinksSt.push([ArrayGraphObj[myCr], true]);}
        else {ArrayGraphObjReLinksSt.push([ArrayGraphObj[myCr], false]);}
      else {ArrayGraphObjReLinksSt.push([ArrayGraphObj[myCr], true]);}
    return ArrayGraphObjReLinksSt;
    /* Функция определения расширения файла, возвращает часть строки от крайней правой точки. */
    function FileNExt (FileNamePath) {
    var myFileNamePath = String (FileNamePath);
    var myFileNEnd = myFileNamePath.lastIndexOf (".");
    if (myFileNEnd != -1) {myFileNamePath = myFileNamePath.substr(myFileNEnd+1);}
    return myFileNamePath;
    /* Функция удаляет расширение файла,
    возвращает строку от начала myFileName до первого (при myDotOrd = true)
    или последнего символа точки (myDotOrd = false). */
    function FileNameWtExt (myFileName, myDotOrd) {
    var myFileNamePath = String (myFileName);
    var myFileNEnd = myFileNamePath.lastIndexOf (".");
    if (myFileNEnd != -1) {
      myFileNamePath = myFileName.substr (0, myFileNEnd);
      if (myDotOrd) {
       // рекурсивный вызов функции
       myFileNamePath = FileNameWtExt (myFileNamePath, true);
    return myFileNamePath;
    /* Функция получения массива типов графических файлов, которые используются в документе (ActDoc).
    Выполняется Unlock Position для всех объектов и групп с графическими изображениями документа.
    Определяется количество изображений, которые были вставлены в документ из буфера обмена (Null Link). */
    function GetFileTypeInDoc (ActDoc) {
    var myObject;
    var myImageType;
    var myDocTypeArr = new Array();
    var myDocUniqTypeArr;
    var myResultDocTypeAndCounters = new Array();
    for (var myCr = 0; myCr < ActDoc.allGraphics.length; myCr++) {
      myObject = ActDoc.allGraphics[myCr];
      myUnlock_ParentRe (myObject);
      try {
       myImageType = myObject.itemLink.linkType;
       myDocTypeArr.push(myImageType);
      catch (e) {
       mySelection_ParentRe(myObject, myObject);
       if (!confirm(alertWithoutLink, "", inScriptName)) {exit();}
    myDocUniqTypeArr = getUniqObjArray(myDocTypeArr);
    for (myCr = 0; myCr < myDocUniqTypeArr.length; myCr++) {
      myResultDocTypeAndCounters.push([myDocUniqTypeArr[myCr], checkDoubled(myDocTypeArr, myDocUniqTypeArr[myCr]).length]);
    return myResultDocTypeAndCounters;
    /* Функция осуществляет переход в активном окне на разворот
    с объектом myGraphObj и выделяет mySelectObj, если обект не является содержимым текстового блока. */
    function mySelection_ParentRe (myGraphObj, mySelectObj) {
    app.activeDocument.select (mySelectObj);
    app.activeWindow.zoom (2053206906);
    if (myGraphObj.parent.constructor.name != "Story") {
      try {app.activeWindow.activeSpread = myGraphObj.parent;}
      // рекурсивный вызов при ошибке
      catch (e) {mySelection_ParentRe(myGraphObj.parent, mySelectObj);}
    // Функция выполняет UnLock Positon изображения myGraphObj
    function myUnlock_ParentRe (myGraphObj) {
    try {myGraphObj.parent.locked = false;}
    // рекурсивный вызов при ошибке
    catch (e) {myUnlock_ParentRe(myGraphObj.parent);}
    /* Функция выполняет поиск "истинности" атрибута Nonprinting для изображения и групп, включающих текущий объект. */
    function myNonprint_ParentRe (myGraphNObj) {
    try {
      var mNonPrRes = myGraphNObj.nonprinting;
      // условие рекурсивного вызова функции
      if (mNonPrRes == false) {
       mNonPrRes = myNonprint_ParentRe (myGraphNObj.parent);
       if (mNonPrRes) {return true;}
      else {return true;}
    catch (e) {return false;}
    /* Функция отменяет "истинность" атрибута Nonprinting
    для изображения, его контейнера и групп, включающих текущий объект. */
    function myNonpFalse_ParentRe (myGraphFObj) {
    try {
      myGraphFObj.nonprinting = false;
      myNonpFalse_ParentRe(myGraphFObj.parent);
    catch (e) {}
    /* Функция поиска дубликата myObject в массиве myArray. Возвращает массив индексов найденных дубликатов в массиве. */
    function checkDoubled(myArray, myObject) {
    var IndxDupls = new Array();
    for (var objCnr = 0; objCnr < myArray.length; objCnr++) {
      if (myObject == myArray[objCnr]) {IndxDupls.push(objCnr);}
    return IndxDupls;
    /* Функция возвращает массив myResultArr из неповторяющихся объектов массива myArray. */
    function getUniqObjArray (myArray) {
    var myResultArr = new Array();
    var myObject;
    for (var myCounter = 0; myCounter < myArray.length; myCounter++) {
      myObject = myArray[myCounter];
      if (checkDoubled(myResultArr, myObject).length == 0) {myResultArr.push(myObject);}
    return myResultArr;
    function cr() {if (mn != "\u00A9\ \u0044\u006D\u0069\u0074\u0072\u0069\u0079\ \u004C\u0061\u0070\u0061\u0079\u0065\u0076") exit();}
    /* Функция получения графических объектов выбранных типов (ArrTypeFind) из массива (myRastrImageArray). */
    function getTypeRastrImages (myRastrImageArray, ArrTypeFind) {
    var myTypeResult = new Array();
    var myObject;
    var myTypeImage;
    for (var myCounter = 0; myCounter < myRastrImageArray.length; myCounter++) {
      myObject = myRastrImageArray[myCounter];
      myTypeImage = myObject.itemLink.linkType;
      for (var TypeCr = 0; TypeCr < ArrTypeFind.length; TypeCr++) {
       if (myTypeImage == ArrTypeFind[TypeCr][1] && ArrTypeFind[TypeCr][0] == true) {
        myTypeResult.push(myObject);
    return myTypeResult;
    /* Функция поворота изображения myRImage на 90° по часовой стрелке или против,
    в диалоге выбирается направление вращения. После вращения:
    изображению присваиваются значения geometricBounds исходного,
    возвращается счетчик действий над изображением - myCountNone.
    myImageArrPars  (horizontalScale, verticalScale, shearAngle, rotationAngle, geometricBounds). */
    function myRotateUIDialog (myRImage, myImageArrPars, myCountNone) {
    // Прогнозирование возможного поворота изо

    Check out my Update path names in links script: http://www.kasyan.ho.com.ua/relink.html
    Kasyan

  • How to run add-opt-in.py script in swf

    I am using flash professional for my project , now i like to use adobe scout for profiling. I have read that for flashpro we have dowload python scripts and run the add-opt-in.py script on your SWF etc.
    how to run the python script in a swf. can u explain.. and also i like to know about remote profiling
    Thanks in advance

    You need to install python, and then you can run the script.
    I use a command line like this:
    c:\Python33\python.exe c:\tools\flexProfiling\add-opt-in.py "E:\my.swf"
    There are more details about it at this website:  http://www.adobe.com/devnet/scout/articles/adobe-scout-getting-started.html
    You can read about remote profiling at the same site:  http://www.adobe.com/devnet/scout/articles/adobe-scout-getting-started.html

  • Please correct this script

    Hello
    In this script i cant change resulution it will change default size 72 dpi when i chnage 300 dpi it cant work
    also it was not work in cs5 bridge app
    please help me
    #target bridge  
    if( BridgeTalk.appName == "bridge" ) { 
    var menu = MenuElement.find ('myBridgeMenu');
    if (menu == null){
    var newMenu = MenuElement.create( "menu", "Bridge", "before tools/ps", "myBridgeMenu" );
    WebPics = MenuElement.create( "command", "Bridge Processor", "at the end of myBridgeMenu",  "BridgeProcessor" );
    WebPics.onSelect = function () {
       WebPictures();
    function WebPictures(){
    if(app.version.match(/^\d+/) < 2){
        alert("You need CS3 or better to use this script!");
        return;
    if($.os.match(/windows/gi)){
    var TemplateFolder = new Folder(Folder.userData.absoluteURI + "/Adobe/XMP/Metadata Templates");
    var Templates = TemplateFolder.getFiles("*.xmp");
    var TemplateNames =[];
    for(var d in Templates){TemplateNames.push(decodeURI(Templates[d].name.toString().replace(/\.xmp$/i,'' )));}
    var PrefsFile = File(Folder.userData +"/BridgePrefs.dat");
    var Prefs = {};
    if(!PrefsFile.exists){
        Prefs.folder = decodeURI(app.document.presentationPath);
        Prefs.Width = 900;
        Prefs.Height = 800; 
        Prefs.quality = 79;
        Prefs.type = 0;
        if($.os.match(/windows/gi)){
        Prefs.template = 0;
        }else{
    PrefsFile.open('r');
    Prefs = eval(PrefsFile.read());
    PrefsFile.close();
    if($.os.match(/windows/gi)){
    if(Prefs.template == null) Prefs.template = 0;
    if(Prefs.template == undefined) Prefs.template = 0;
    var win = new Window('dialog','Bridge Processor');
    g = win.graphics;
    var myBrush = g.newBrush(g.BrushType.SOLID_COLOR, [0.99, 0.99, 0.99, 1]);
    g.backgroundColor = myBrush;
    win.alignChildren="row";
    win.g10 = win.add('group');
    win.g10.orientation = "row";
    win.title = win.g10.add('statictext',undefined,"Bridge Processor");
    win.title.helpTip="Written by Paul Riggott";
    win.title.alignment="bottom";
    var g = win.title.graphics;
    g.font = ScriptUI.newFont("Georgia","BOLDITALIC",26);
    win.p1= win.add("panel", undefined, undefined, {borderStyle:"black"});
    win.p1.alignChildren="fill";
    win.p2= win.p1.add("panel", undefined, undefined, {borderStyle:"black"});
    win.g3 =win.p2.add('group');
    win.g3.orientation = "row";
    win.g3.alignment="left";
    win.g3.rb1 = win.g3.add('radiobutton',undefined,'Use selected Files');
    win.g3.rb2 = win.g3.add('radiobutton',undefined,'Use files of Type');
    var FileExtensions = "DNG,PSD,PDD,JPEG,JPG,JPE,GIF,BMP,RLE,DIB,TIF,CRW,NEF,RAF,ORF,CIN,DPX,EPS,PS,FLM,PSB,EXR, PCX,PDP," +
    "PCD,RAW,PICT,PCT,PIC,PXR,PNG,TGA,VDA,ICB,VST,TIF,TIFF,WBM,DNG,SCT,PBM,CRW,CR2,DC2,DCR,NEF ,MOS,MRW,X3F,MOV";
    FileExtensions= FileExtensions.toUpperCase();
    FileExtensions = FileExtensions.split(",");
    FileExtensions= ReturnUniqueSortedList(FileExtensions);
    win.g3.dd1 = win.g3.add('dropdownlist',undefined,FileExtensions);
    try{
    win.g3.dd1.selection= Number(Prefs.type);
    }catch(e){win.g3.dd1.selection=0;};
    win.g3.rb1.value=true;
    win.g3.cb1 = win.g3.add('checkbox',undefined,'Use Subfolders');
    win.g3.dd1.enabled=false;
    win.g3.cb1.value=false;
    win.g3.cb1.enabled=false;
    win.g3.rb2.onClick = function(){
    win.g3.dd1.enabled=true;
    win.g3.cb1.value=false;
    win.g3.cb1.enabled=true;
    win.g3.rb1.onClick = function(){
    win.g3.dd1.enabled=false;
    win.g3.cb1.value=false;
    win.g3.cb1.enabled=false;
    win.p3= win.p1.add("panel", undefined, undefined, {borderStyle:"black"});
    win.g10a =win.p3.add('group');
    win.g10a.alignment="left";
    win.g10a.cb1 = win.g10a.add('checkbox',undefined,'Save to Same Location');
    win.g11 =win.p3.add('group');
    win.g11.spacing=10;
    win.g11.orientation = 'row';
    win.g11.alignment="left";
    win.g11.st1 = win.g11.add('statictext',undefined,'Output Folder :-');
    win.g11.st1.preferredSize=[200,20];
    win.g11.bu1 = win.g11.add('button',undefined,'Browse');
    win.g11.st1.alignment="left";
    win.g11a =win.p3.add('group');
    win.g11a.et1 = win.g11a.add('edittext');
    win.g11a.et1.preferredSize=[400,20];
    win.g11a.et1.enabled=false;
    if(Folder(Prefs.folder.exists)){
        win.g11a.et1.text =  decodeURI(Folder(Prefs.folder).fsName);
    if(Folder(Prefs.folder.exists)) outputFolder = Folder(Prefs.folder);
    win.g11.bu1.onClick=function(){  
         outputFolder = Folder.selectDialog("Please select the output folder",Prefs.folder);   
         if(outputFolder !=null) win.g11a.et1.text =  decodeURI(outputFolder.fsName);
    win.p4= win.p1.add("panel", undefined, undefined, {borderStyle:"black"});
    win.g12 =win.p4.add('group');
    win.g12.cb1 = win.g12.add('checkbox',undefined,'Use Fullsize JPEG');
    win.g12.cb1.helpTip="This can take a lot more time!";
    if($.os.match(/windows/gi)){
    win.g12.cb2 = win.g12.add('checkbox',undefined,'Set Resolution');
    win.g12.et1 = win.g12.add('edittext',undefined,'72');
    win.g12.et1.preferredSize=[100,20];
    win.g12.et1.onChanging = function() {
      if (this.text.match(/[^\d]/)) {
        this.text = this.text.replace(/[^\d]/g, '');
    win.g12.orientation = 'row';
    win.g12.alignment="left";
    win.g12.spacing=20;
    win.g12.cb2.onClick=function(){
        if(win.g12.cb2.value){
            win.g12.et1.enabled=true;
            }else{
                win.g12.et1.enabled=false;
    win.g12.cb2.onClick();
    win.g14 =win.p4.add('group');
    win.g14.spacing=0;
    win.g14.orientation = 'row';
    win.g14.alignment="left";
    win.g14.cb1 = win.g14.add('checkbox',undefined,"Fit Image");
    win.g14.cb1.preferredSize=[80,20];
    win.g14.st0 = win.g14.add('statictext',undefined,"W: ");
    win.g14.et1 = win.g14.add('edittext',undefined,'900');
    win.g14.et1.preferredSize=[50,20];
    win.g14.et1.enabled=false;
    win.g14.et1.text = Number(Prefs.Width);
    win.g14.st1 = win.g14.add('statictext',undefined,"px");
    win.g14.st1.preferredSize=[30,20]
    win.g14.st0a = win.g14.add('statictext',undefined,"H: ");
    win.g14.et1a = win.g14.add('edittext',undefined,'900');
    win.g14.et1a.preferredSize=[50,20];
    win.g14.et1a.enabled=false;
    win.g14.et1a.text = Number(Prefs.Height);
    win.g14.st1a = win.g14.add('statictext',undefined,"px");
    win.g14.st1a.preferredSize=[30,20]
    win.g14.st3 = win.g14.add('statictext',undefined,"Quality");
    win.g14.st3.preferredSize=[60,20];
    win.g14.dd1 = win.g14.add('dropdownlist');
    for(var a =1;a<101;a++){
        win.g14.dd1.add("item", a);
    win.g14.dd1.selection=Number(Prefs.quality);
    win.g14.et1.onChanging = function() {
      if (this.text.match(/[^\d]/)) {
        this.text = this.text.replace(/[^\d]/g, '');
    win.g14.et1a.onChanging = function() {
      if (this.text.match(/[^\d]/)) {
        this.text = this.text.replace(/[^\d]/g, '');
    if($.os.match(/windows/gi)){
    win.g18 =win.p4.add('group');
    win.g18.spacing=25;
    win.g18.orientation = 'row';
    win.g18.alignment="left";
    win.g18.cb1 = win.g18.add('checkbox',undefined,'Use Template');
    win.g18.dd1 = win.g18.add('dropdownlist',undefined,TemplateNames);
    if(Templates.length < 1) {
    win.g18.cb1.enabled=false;
    }else{
    win.g18.dd1.selection=Number(Prefs.template);
    win.g18.dd1.enabled=false;
    win.g18.cb1.onClick=function(){
        if(win.g18.cb1.value){
            win.g18.dd1.enabled=true;
            }else{
                win.g18.dd1.enabled=false;
    win.g14.cb1.onClick=function(){
       if( win.g14.cb1.value){
           win.g14.et1.enabled=true;
           win.g14.et1a.enabled=true;
           }else{
               win.g14.et1.enabled=false;
               win.g14.et1a.enabled=false;
    win.g50 =win.p4.add('group');
    win.g50.spacing=10;
    win.g50.orientation = 'row';
    win.g50.alignment="left";
    win.g50.st1 = win.g50.add('statictext',undefined,"FileName Options");
    var options = ["Document Name","Document Name with Prefix","Document Name with Suffix","Document Name with Sequence Number","New Name with Sequence Number"];
    win.g50.dd1 = win.g50.add('dropdownlist',undefined,options);
    win.g50.dd1.selection=0;
    win.g55 =win.p4.add('group');
    win.g55.spacing=10;
    win.g55.orientation = 'stack';
    win.g55.alignment="left";
    win.g55a =win.g55.add('group');
    win.g55a.spacing=10;
    win.g55a.alignment="left";
    win.g55a.st1 = win.g55a.add('statictext',undefined,"Prefix");
    win.g55a.et1 = win.g55a.add('edittext',undefined,"");
    win.g55a.et1.preferredSize=[250,20];
    win.g55a.visible=false;
    win.g55b =win.g55.add('group');
    win.g55b.spacing=10;
    win.g55b.alignment="left";
    win.g55b.st1 = win.g55b.add('statictext',undefined,"Suffix");
    win.g55b.et1 = win.g55b.add('edittext',undefined,"");
    win.g55b.et1.preferredSize=[250,20];
    win.g55b.visible=false;
    var numbers =[2,3,4,5,6,7,8,9,10];
    win.g55c =win.g55.add('group');
    win.g55c.spacing=10;
    win.g55c.alignment="left";
    win.g55c.st1 = win.g55c.add('statictext',undefined,"Sequence Number");
    win.g55c.et1 = win.g55c.add('edittext',undefined,"");
    win.g55c.et1.preferredSize=[50,20];
    win.g55c.st2 =win.g55c.add('statictext',undefined,'Length');
    win.g55c.dd1 =win.g55c.add('dropdownlist',undefined,numbers);
    win.g55c.dd1.selection=2;
    win.g55c.visible=false;
    win.g55c.et1.onChanging = function() {
      if (this.text.match(/[^\-\.\d]/)) {
        this.text = this.text.replace(/[^\-\.\d]/g, '');
    win.g55d =win.g55.add('group');
    win.g55d.spacing=10;
    win.g55d.st1 = win.g55d.add('statictext',undefined,"FileName");
    win.g55d.et1 = win.g55d.add('edittext',undefined,"");
    win.g55d.et1.preferredSize=[195,20];
    win.g55d.et2 = win.g55d.add('edittext',undefined,"");
    win.g55d.et2.preferredSize=[50,20];
    win.g55d.st2 =win.g55d.add('statictext',undefined,'length');
    win.g55d.dd1 =win.g55d.add('dropdownlist',undefined,numbers);
    win.g55d.dd1.selection=2;
    win.g55d.visible=false;
    win.g55d.et2.onChanging = function() {
      if (this.text.match(/[^\-\.\d]/)) {
        this.text = this.text.replace(/[^\-\.\d]/g, '');
    win.g50.dd1.onChange = function(){
        switch(this.selection.index){
            case 0 : hideFields();checkSave();break;
            case 1 : hideFields();
            win.g55a.visible=true;
            break;
            case 2 : hideFields();
            win.g55b.visible=true;
            break;
            case 3 : hideFields();
            win.g55c.visible=true;
            break;
            case 4 : hideFields();
            win.g55d.visible=true;
            break;
            default : break;
    function hideFields(){
    win.g55a.visible=false;
    win.g55a.et1.text='';
    win.g55b.et1.text='';
    win.g55b.visible=false;
    win.g55c.visible=false;
    win.g55c.et1.text='1';
    win.g55d.visible=false;
    win.g55d.et1.text='';
    win.g55d.et2.text='1';
    win.g150 =win.p1.add('group');
    win.g150.spacing=10;
    win.g150.orientation = 'row';
    win.g150.alignment="top";
    win.g150.bu1 = win.g150.add('button',undefined,"Process");
    win.g150.bu1.preferredSize=[200,30];
    win.g150.bu2 = win.g150.add('button',undefined,"Cancel");
    win.g150.bu2.preferredSize=[200,30];
    win.g10a.cb1.onClick=function(){
        if(win.g10a.cb1.value){
            win.g11.bu1.enabled=false;
            win.g50.dd1.selection=4;
            }else{
                win.g11.bu1.enabled=true;
    function checkSave(){
        if(win.g10a.cb1.value){
            alert("Sorry this is not allowed as it could overwrite the document!\nPlease use another option");
            win.g50.dd1.selection=4;
            return;
    win.g150.bu1.onClick=function(){
        if(win.g11a.et1.text == ''){
            alert("No output folder has been selected!");
            return;
        if(Number(win.g14.et1.text) <10) {
            alert("Please enter a realistic Resize number!");
            return;
        if(Number(win.g14.et1a.text) <10) {
            alert("Please enter a realistic Resize number!");
            return;
        if(win.g50.dd1.selection.index == 1 && win.g55a.et1.text == ''){
            alert("No Prefix Has Been Entered!");
            win.g55a.et1.active=true;
            return;
        if(win.g50.dd1.selection.index == 2 && win.g55b.et1.text == ''){
            alert("No Suffix Has Been Entered!");
            win.g55b.et1.active=true;
            return;
        if(win.g50.dd1.selection.index == 3 && win.g55c.et1.text == ''){
            alert("No Sequence Number Has Been Entered!");
            win.g55c.et1.active=true;
            return;
        if(win.g50.dd1.selection.index == 4 && win.g55d.et1.text == ''){
            alert("No File Name Has Been Entered!");
            win.g55d.et1.active=true;
            return;
        if(win.g50.dd1.selection.index == 4 && win.g55d.et2.text == ''){
            alert("No Sequence Number Has Been Entered!");
            win.g55d.et2.active=true;
            return;
    Prefs.folder = decodeURI(outputFolder);
    Prefs.Width = Number(win.g14.et1.text);
    Prefs.Height = Number(win.g14.et1a.text);
    Prefs.quality = parseInt(win.g14.dd1.selection.index);
    Prefs.type= parseInt(win.g3.dd1.selection.index);
    if($.os.match(/windows/gi)){
    if(Templates.length > 0) {
    Prefs.template = parseInt(win.g18.dd1.selection.index);
    PrefsFile.open('w');
    PrefsFile.write(Prefs.toSource());
    PrefsFile.close();
        win.close(1);
        process();
    win.center();
    result = win.show();
    function process(){
    var folders =[];
    if(win.g3.cb1.value){
    var topLevel = Folder(app.document.presentationPath);   
    folders = FindAllFolders(topLevel, folders);
    folders.unshift(topLevel);
    var Quality = parseInt(win.g14.dd1.selection.index);
    var ResizeW = Number(win.g14.et1.text);
    var ResizeH = Number(win.g14.et1a.text);
    var sels =[];
    Count = 0;
    mask = win.g3.dd1.selection.text.toLowerCase();
    if(win.g3.rb1.value) {
        sels = app.document.selections;
       processSels();
    if(!win.g3.rb1.value &&  !win.g3.cb1.value){
    app.document.deselectAll();  
    sels = app.document.getSelection(mask);
    processSels();
    if(!win.g3.rb1.value &&  win.g3.cb1.value){//use subfolders
    mask = "*."+ win.g3.dd1.selection.text.toLowerCase();
    for(var k in folders){
    sels = folders[k].getFiles(mask);
    processSels();
    function processSels(){
    for(var z  in sels){
    var Thumb1 = new Thumbnail(sels[z]);
    Name = decodeURI(Thumb1.spec.name).replace(/\.[^\.]+$/, '');
    var Seq1 = zeroPad((Number(Count)+Number(win.g55c.et1.text)), (parseInt(win.g55c.dd1.selection.index)+2));
    var Seq2 = zeroPad((Number(Count)+Number(win.g55d.et2.text)), (parseInt(win.g55d.dd1.selection.index)+2));
    var Prefix = win.g55a.et1.text;
    var Suffix = win.g55b.et1.text;
    var NewName = win.g55d.et1.text;
    app.synchronousMode = true;
    if(win.g12.cb1.value){
    Thumb1.core.fullsize.fullsize;
    }else{
        Thumb1.core.preview.preview;
    app.synchronousMode = false;
    var md = Thumb1.synchronousMetadata;
    md.namespace = "http://ns.adobe.com/tiff/1.0/";
    var orientation = md.Orientation.replace(/(\w+)(\s+)(.)(\d+)(.)/,"$3$4");
    orientation = orientation.replace(/°/,'');
    orientation = orientation.replace(/Rotate/,'');
    if(orientation == 'Normal') orientation =0;
    var bm = undefined;
    if(win.g12.cb1.value){
    bm = Thumb1.core.fullsize.fullsize;
    }else{
        bm = Thumb1.core.preview.preview;
    if(bm.width != undefined) bm = bm.rotate(orientation);
    if(win.g14.cb1.value){
    if(bm.width > bm.height){
    var maxSize = Math.max(bm.height,bm.width);
    var minSize =Math.min(ResizeW,maxSize);
    if(minSize < maxSize) bm = bm.resize(minSize,BitmapData.bicubicSharper);
    }else{
        var maxSize = Math.max(bm.height,bm.width);
        var minSize =Math.min(ResizeH,maxSize);
    if(minSize < maxSize) bm = bm.resize(minSize,BitmapData.bicubicSharper);
    var parts = Thumb1.name.match(/(.*)\.([^\.]+)/); 
    switch(Number(win.g50.dd1.selection.index)){
        case 0 : saveFile =  Name; break;
        case 1 : saveFile =  Prefix + Name; break;
        case 2 : saveFile =  Name + Suffix; break;
        case 3 : saveFile =  Name + Seq1; break;
        case 4 : saveFile =  NewName + Seq2; break;
        default : break;
    if(win.g10a.cb1.value) outputFolder =app.document.presentationPath;
    bm.exportTo(new File(outputFolder +"/"+ saveFile +".jpg"),(Quality+1));
    Count++;
    if($.os.match(/windows/gi)){
    if(win.g12.cb2.value){//set resolution
    var res = Number(win.g12.et1.text);
    var t = new Thumbnail(new File(outputFolder +"/"+ saveFile +".jpg"));
    var mdata = t.synchronousMetadata;
    mdata.namespace = "http://ns.adobe.com/tiff/1.0/";
    mdata.XResolution =res*1000 +"/1000";
    mdata.YResolution =res*1000 +"/1000";
    mdata.ResolutionUnit =1;
    if(win.g18.cb1.value){
    var t = new Thumbnail(new File(outputFolder +"/"+ saveFile +".jpg"));
    var mdata = t.synchronousMetadata;
    mdata.applyMetadataTemplate(win.g18.dd1.selection.text, "replace");
        if(result == 1) alert("All done!");
    function ReturnUniqueSortedList(ArrayName){
    var unduped = new Object;
    for (var i = 0; i < ArrayName.length; i++) {  
    unduped[ArrayName[i]] = ArrayName[i];
    var uniques = new Array;
    for (var ki in unduped) {
       uniques.push(unduped[ki]);
    uniques.sort();
    return uniques;
    function FindAllFolders( srcFolderStr, destArray) {
        var fileFolderArray = Folder( srcFolderStr ).getFiles();
        for ( var i = 0; i < fileFolderArray.length; i++ ) {
            var fileFoldObj = fileFolderArray[i];
            if ( fileFoldObj instanceof File ) {           
            } else {
             destArray.push( Folder(fileFoldObj) );
            FindAllFolders( fileFoldObj.toString(), destArray );
        return destArray;
    function zeroPad(n, s) {
    n = n.toString();
    while (n.length < s) n = '0' + n;
    return n;

    The latest version is here:-
    http://www.scriptsrus.talktalk.net/BridgeProcessor.htm
    This is WINDOWS ONLY, this script will NOT work on a Mac!

  • Why does this script behavior change with the phase of the moon ?

    Can anyone from adobe corp or non-adobe volunteers tell me where to look in their docs to find out why this script change its behavior or how to use the debugger to figure out the same. I read the guide and the whole section on debugger and break points etc well.
    try{
    this.getField('Button4').strokeColor = color.red   ;
    app.setTimeOut( "this.getField('Button4').strokeColor = color.green ;" , 500 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.blue  ;" , 1000 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.red   ;" , 1500 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.green ;" , 2000 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.blue  ;" , 2500 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.red   ;" , 3000 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.green ;" , 3500 );
    app.setTimeOut( "this.getField('Button4').strokeColor = color.blue  ;" , 4000 );
    catch(e){}
    Sometimes the above script cycle thru all the colors in proper order and other time it get stuck.
    I have linked it to a button so its part of the button javascript.
    Is there a way to craft setTimeOut calls that it becomes a reliable delay ?
    How to craft it such that the file does not change and does not have to be saved ? This is wanted in addition but not the essential issue at the moment.
    Thanks,
    Rainbow

    MAXcount=20
    // Create a simple color animation on a field called “Color” that changes every second.
    function DoIt() {
      var f = this.getField("Button4");
      var nColor = (timeout.count++ % 10 / 10);
      // Various shades of red.
      var aColor = new Array("RGB", nColor, 0, 0);
      f.fillColor = aColor;
      console.println( 'change' + ' ' + nColor + '; count=' + timeout.count );
      if (timeout.count >= MAXcount)
        app.clearInterval ( timeout );
    console.show();
    console.clear();
    console.println('Start');
    // save return value as a variable
    timeout = app.setInterval("DoIt()", 1000);
    // Add a property to our timeout object so that DoIt() can keep a count going.
    timeout.count = 0;
    console.println('End of code');
    // And observe the results. I expect your new timer events are conflicting with each other. Note that in the above code the change is performed within the called function and not as new line of code.
    I ran it but did not follow your last comment and acrobat disk icon prompts for saving the file. Can anyone remove this "latter problem" ? Can it be solved by any means ?

  • Firefox has crashed numerous times on me tonight, and I keep getting an unresponsive script error (Script: chrome://devany/content/main.js:254) regardless of what website I'm on. NoScript will not block this script, and it's popping up with an increasing

    Firefox has crashed numerous times on me tonight, and I keep getting an unresponsive script error (Script: chrome://devany/content/main.js:254) regardless of what website I'm on. NoScript will not block this script, and it's popping up with an increasing and alarming frequency. It's completely crippled my Firefox, and getting the a large enough window between unresponsive script warnings to get the Troubleshooting Information from Firefox took me a good 20 minutes. It's a very persistent script. I've already re-installed Firefox and restarted my computer, and scanned for viruses/malware. I'm on a Mac, if it makes a difference.
    == This happened ==
    Every time Firefox opened
    == Tonight. I can't say what site I was on, though I first noticed it on DeviantArt and thought it was their new layout producing problems. ==
    == User Agent ==
    Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7

    yay, I had this same issue, and I too browsed deviantArt and also have got Deviantanywhere add-on installed. : D
    I'm so glad that You've found a solution and shared it with us.
    I was really getting worried that I'd done something to get malware installed on my 'puter. *Phew* !!
    I'm going to disable DeviantAnywhere after I post this and hopefully this will be fixed for me too!
    I actually hadn't kept my firefox up to date. but.. *shh...*
    I updated it and after I did, it told me that there was a script running that was not responding. : )
    yay for FireFox~
    ~QuinsY.

  • Add search area in script

    Hi,
    In the Navigator, I would like to add or remove search areas with script. This script will be launched at the DIAdem start to automatically configure the datafinder and update the search area. I don't find the way to do it. Could anyone help me ?
    Thanks in advance.

    Hi bull balls,
    Unfortunately, there is no command available in the DIAdem 11.0 time frame with which you can programmatically configure the DataFinder.  We have received requests of this sort in the past and are considering options on this front moving forward.
    Brad Turpin
    DIAdem Product Support Engineer
    National Instruments

  • A login webpage gives the message "This script requires that jquery.js be loaded first." then will not show the user ID and password login boxes. How can this be corrected?

    A login webpage gives the message "This script requires that jquery.js be loaded first." then will not show the user ID and password login boxes. How can this be corrected?

    That message is listed in two scripts on the bank's site. One function that can display the message is named PhotoRotator and the other is named PromoRotator. However, I can't seem to trigger the error myself.
    If you have any add-ons that alter the page, such as ad blockers, try creating an exception for these sites and see whether that helps:
    www.northrim.com<br>
    www.northrimbankonline.com
    You also could try this logon page: https://www.northrimbankonline.com/onlineserv/HB/Signon.cgi
    (''Obviously you should be cautious about links offered on public forums to ensure you are not being phished! Check them out carefully before entering your username and password.'')

Maybe you are looking for