text:
"""
SeleniumBase console scripts runner

Usage:
seleniumbase [COMMAND] [PARAMETERS]
  OR   sbase [COMMAND] [PARAMETERS]

Examples:
sbase get chromedriver
sbase methods
sbase options
sbase commander
sbase behave-gui
sbase mkdir ui_tests
sbase mkfile new_test.py
sbase mkrec new_test.py
sbase mkrec new_test.py --url=wikipedia.org
sbase codegen new_test.py --url=wikipedia.org
sbase recorder
sbase record new_test.py
sbase record
sbase mkpres new_presentation.py
sbase mkchart new_chart.py
sbase convert webdriver_unittest_file.py
sbase print my_first_test.py -n
sbase translate my_first_test.py --zh -p
sbase extract-objects my_first_test.py
sbase inject-objects my_first_test.py
sbase objectify my_first_test.py
sbase revert-objects my_first_test.py
sbase encrypt
sbase decrypt
sbase download server
sbase grid-hub start
sbase grid-node start --hub=127.0.0.1
"""

import colorama
import sys

colorama.init(autoreset=True)

def show_usage():
    show_basic_usage()
    sc = ""
    sc += '    Type "sbase help [COMMAND]" for specific command info.\n'
    sc += '    For info on all commands, type: "seleniumbase --help".\n'
    sc += '    Use "pytest" for running tests.\n'
    if "linux" not in sys.platform:
        c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
        c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
        c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
        c4 = colorama.Fore.MAGENTA + colorama.Back.LIGHTYELLOW_EX
        cr = colorama.Style.RESET_ALL
        sc = sc.replace("seleniumbase", c1 + "selenium" + c2 + "base" + cr)
        sc = sc.replace("sbase", c1 + "s" + c2 + "base" + cr)
        sc = sc.replace("pytest", c3 + "pytest" + cr)
        sc = sc.replace("--help", c4 + "--help" + cr)
        sc = sc.replace("help", c4 + "help" + cr)
    print(sc)

def show_basic_usage():
    import time
    from seleniumbase.console_scripts import logo_helper

    seleniumbase_logo = logo_helper.get_seleniumbase_logo()
    print(seleniumbase_logo)
    print("")
    time.sleep(0.25)  # Enough time to see the logo
    show_package_location()
    show_version_info()
    print("")
    sc = ""
    sc += ' * USAGE: "seleniumbase [COMMAND] [PARAMETERS]"\n'
    sc += ' *    OR:        "sbase [COMMAND] [PARAMETERS]"\n'
    sc += "\n"
    sc += "COMMANDS:\n"
    sc += "      get / install    [DRIVER] [OPTIONS]\n"
    sc += "      methods          (List common Python methods)\n"
    sc += "      options          (List common pytest options)\n"
    sc += "      behave-options   (List common Behave options)\n"
    sc += "      gui / commander  [OPTIONAL PATH or TEST FILE]\n"
    sc += "      behave-gui       (SBase Commander for Behave)\n"
    sc += "      mkdir            [DIRECTORY] [OPTIONS]\n"
    sc += "      mkfile           [FILE.py] [OPTIONS]\n"
    sc += "      mkrec / codegen  [FILE.py] [OPTIONS]\n"
    sc += "      recorder         (Open Recorder Desktop App.)\n"
    sc += "      record           (If args: mkrec. Else: App.)\n"
    sc += "      mkpres           [FILE.py] [LANG]\n"
    sc += "      mkchart          [FILE.py] [LANG]\n"
    sc += "      print            [FILE] [OPTIONS]\n"
    sc += "      translate        [SB_FILE.py] [LANG] [ACTION]\n"
    sc += "      convert          [WEBDRIVER_UNITTEST_FILE.py]\n"
    sc += "      extract-objects  [SB_FILE.py]\n"
    sc += "      inject-objects   [SB_FILE.py] [OPTIONS]\n"
    sc += "      objectify        [SB_FILE.py] [OPTIONS]\n"
    sc += "      revert-objects   [SB_FILE.py] [OPTIONS]\n"
    sc += "      encrypt / obfuscate\n"
    sc += "      decrypt / unobfuscate\n"
    sc += "      download server  (Get Selenium Grid JAR file)\n"
    sc += "      grid-hub         [start|stop] [OPTIONS]\n"
    sc += "      grid-node        [start|stop] --hub=[HOST/IP]\n"
    sc += ' * (EXAMPLE: "sbase get chromedriver latest") *\n'
    sc += ""
    if "linux" not in sys.platform:
        c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
        c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
        cr = colorama.Style.RESET_ALL
        sc = sc.replace("seleniumbase", c1 + "selenium" + c2 + "base" + cr)
        sc = sc.replace("sbase", c1 + "s" + c2 + "base" + cr)
    print(sc)

def show_install_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "get / install" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase install [DRIVER_NAME] [OPTIONS]")
    print("           OR: seleniumbase get [DRIVER_NAME] [OPTIONS]")
    print("           OR:    sbase install [DRIVER_NAME] [OPTIONS]")
    print("           OR:        sbase get [DRIVER_NAME] [OPTIONS]")
    print("                 (Drivers: chromedriver, geckodriver, edgedriver")
    print("                           iedriver, operadriver)")
    print("  Options:")
    print("           VERSION         Specify the version to download.")
    print("                            (Default chromedriver = 72.0.3626.69.")
    print('                             Use "latest" for the latest version.')
    print("                             For chromedriver, you can also use")
    print("                             the major version integer")
    print('                             or "latest-1" for 1 less than that.)')
    print("           -p OR --path    Also copy the driver to /usr/local/bin")
    print("  Examples:")
    print("           sbase get chromedriver")
    print("           sbase get geckodriver")
    print("           sbase get edgedriver")
    print("           sbase get chromedriver 101")
    print("           sbase get chromedriver 101.0.4951.41")
    print("           sbase get chromedriver latest")
    print("           sbase get chromedriver latest-1")
    print("           sbase get chromedriver -p")
    print("           sbase get chromedriver latest -p")
    print("           sbase get edgedriver 101.0.1210.32")
    print("  Output:")
    print("           Downloads the chosen webdriver to seleniumbase/drivers")
    print("           (chromedriver is required for Chrome automation)")
    print("           (geckodriver is required for Firefox automation)")
    print("           (edgedriver is required for Microsoft Edge automation)")
    print("           (iedriver is required for InternetExplorer automation)")
    print("           (operadriver is required for Opera Browser automation)")
    print("")

def show_commander_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "commander" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase commander [OPTIONAL PATH or TEST FILE]")
    print("           OR:    sbase commander [OPTIONAL PATH or TEST FILE]")
    print("           OR:   seleniumbase gui [OPTIONAL PATH or TEST FILE]")
    print("           OR:          sbase gui [OPTIONAL PATH or TEST FILE]")
    print("  Examples:")
    print("           sbase gui")
    print("           sbase gui -k agent")
    print("           sbase gui -m marker2")
    print("           sbase gui test_suite.py")
    print("           sbase gui offline_examples/")
    print("  Output:")
    print("           Launches SeleniumBase Commander | GUI for pytest.")
    print("")

def show_behave_gui_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "behave-gui" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase behave-gui [OPTIONAL PATH or TEST FILE]")
    print("           seleniumbase gui-behave [OPTIONAL PATH or TEST FILE]")
    print("           OR:    sbase behave-gui [OPTIONAL PATH or TEST FILE]")
    print("           OR:    sbase gui-behave [OPTIONAL PATH or TEST FILE]")
    print("  Examples:")
    print("           sbase behave-gui")
    print("           sbase behave-gui features/")
    print("           sbase behave-gui features/calculator.feature")
    print("  Output:")
    print("           Launches SeleniumBase Commander | GUI for Behave.")
    print("")

def show_mkdir_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "mkdir" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase mkdir [DIRECTORY] [OPTIONS]")
    print("           OR:    sbase mkdir [DIRECTORY] [OPTIONS]")
    print("  Example:")
    print("           sbase mkdir ui_tests")
    print("  Options:")
    print("           -b / --basic  (Only config files. No tests added.)")
    print("  Output:")
    print("           Creates a new folder for running SBase scripts.")
    print("           The new folder contains default config files,")
    print("           sample tests for helping new users get started,")
    print("           and Python boilerplates for setting up customized")
    print("           test frameworks.")
    print("")

def show_mkfile_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "mkfile" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase mkfile [FILE.py] [OPTIONS]")
    print("           OR:    sbase mkfile [FILE.py] [OPTIONS]")
    print("  Example:")
    print("           sbase mkfile new_test.py")
    print("  Options:")
    print("           -b / --basic  (Basic boilerplate / single-line test)")
    print("           -r / --rec  (adds ipdb breakpoint for Recorder Mode)")
    print("  Language Options:")
    print("           --en / --English    |    --zh / --Chinese")
    print("           --nl / --Dutch      |    --fr / --French")
    print("           --it / --Italian    |    --ja / --Japanese")
    print("           --ko / --Korean     |    --pt / --Portuguese")
    print("           --ru / --Russian    |    --es / --Spanish")
    print("  Output:")
    print("           Creates a new SBase test file with boilerplate code.")
    print("           If the file already exists, an error is raised.")
    print("           By default, uses English mode and creates a")
    print("           boilerplate with the 5 most common SeleniumBase")
    print('           methods, which are "open", "type", "click",')
    print('           "assert_element", and "assert_text". If using the')
    print('           basic boilerplate option, only the "open" method')
    print("           is included.")
    print("")

def show_mkrec_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "mkrec" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase mkrec [FILE.py] [OPTIONS]")
    print("           OR:    sbase mkrec [FILE.py] [OPTIONS]")
    print("  Examples:")
    print("           sbase mkrec new_test.py")
    print("           sbase mkrec new_test.py --url=wikipedia.org")
    print("  Options:")
    print("           --url=URL  (Sets the initial start page URL.)")
    print("           --edge  (Use Edge browser instead of Chrome.)")
    print("           --gui / --headed  (Use headed mode on Linux.)")
    print("           --overwrite  (Overwrite file when it exists.)")
    print("           --behave  (Also output Behave/Gherkin files.)")
    print("  Output:")
    print("           Creates a new SeleniumBase test using the Recorder.")
    print("           If the filename already exists, an error is raised.")
    print("")

def show_codegen_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "codegen" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase codegen [FILE.py] [OPTIONS]")
    print("           OR:    sbase codegen [FILE.py] [OPTIONS]")
    print("  Examples:")
    print("           sbase codegen new_test.py")
    print("           sbase codegen new_test.py --url=wikipedia.org")
    print("  Options:")
    print("           --url=URL  (Sets the initial start page URL.)")
    print("           --edge  (Use Edge browser instead of Chrome.)")
    print("           --gui / --headed  (Use headed mode on Linux.)")
    print("           --overwrite  (Overwrite file when it exists.)")
    print("           --behave  (Also output Behave/Gherkin files.)")
    print("  Output:")
    print("           Creates a new SeleniumBase test using the Recorder.")
    print("           If the filename already exists, an error is raised.")
    print("")

def show_recorder_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "recorder" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase recorder [OPTIONS]")
    print("           OR:    sbase recorder [OPTIONS]")
    print("  Options:")
    print("           --behave  (Also output Behave/Gherkin files.)")
    print("  Output:")
    print("           Launches the SeleniumBase Recorder Desktop App.")
    print("")

def show_mkpres_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "mkpres" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase mkpres [FILE.py] [LANG]")
    print("           OR:    sbase mkpres [FILE.py] [LANG]")
    print("  Example:")
    print("           sbase mkpres new_presentation.py --en")
    print("  Language Options:")
    print("           --en / --English    |    --zh / --Chinese")
    print("           --nl / --Dutch      |    --fr / --French")
    print("           --it / --Italian    |    --ja / --Japanese")
    print("           --ko / --Korean     |    --pt / --Portuguese")
    print("           --ru / --Russian    |    --es / --Spanish")
    print("  Output:")
    print("           Creates a new presentation with 3 example slides.")
    print("           If the file already exists, an error is raised.")
    print("           By default, the slides are written in English,")
    print('           and use "serif" theme with "slide" transition.')
    print("           The slides can be used as a basic boilerplate.")
    print("")

def show_mkchart_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "mkchart" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase mkchart [FILE.py] [LANG]")
    print("           OR:    sbase mkchart [FILE.py] [LANG]")
    print("  Example:")
    print("           sbase mkchart new_chart.py --en")
    print("  Language Options:")
    print("           --en / --English    |    --zh / --Chinese")
    print("           --nl / --Dutch      |    --fr / --French")
    print("           --it / --Italian    |    --ja / --Japanese")
    print("           --ko / --Korean     |    --pt / --Portuguese")
    print("           --ru / --Russian    |    --es / --Spanish")
    print("  Output:")
    print("           Creates a new SeleniumBase chart presentation.")
    print("           If the file already exists, an error is raised.")
    print("           By default, the slides are written in English,")
    print('           and use a "sky" theme with "slide" transition.')
    print("           The chart can be used as a basic boilerplate.")
    print("")

def show_convert_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "convert" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase convert [WEBDRIVER_UNITTEST_FILE.py]")
    print("           OR:    sbase convert [WEBDRIVER_UNITTEST_FILE.py]")
    print("  Output:")
    print("           Converts a Selenium IDE exported WebDriver unittest")
    print("           file into a SeleniumBase file. Adds _SB to the new")
    print("           file name while keeping the original file intact.")
    print("           Works with Katalon Recorder scripts.")
    print("           See: http://www.katalon.com/automation-recorder")
    print("")

def show_print_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "print" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase print [FILE] [OPTIONS]")
    print("           OR:    sbase print [FILE] [OPTIONS]")
    print("  Options:")
    print("           -n   (Add line Numbers to the rows)")
    print("  Output:")
    print("           Prints the code/text of any file")
    print("           with syntax-highlighting.")
    print("")

def show_translate_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "translate" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase translate [SB_FILE.py] [LANG] [ACTION]")
    print("           OR:    sbase translate [SB_FILE.py] [LANG] [ACTION]")
    print("  Languages:")
    print("           --en / --English    |    --zh / --Chinese")
    print("           --nl / --Dutch      |    --fr / --French")
    print("           --it / --Italian    |    --ja / --Japanese")
    print("           --ko / --Korean     |    --pt / --Portuguese")
    print("           --ru / --Russian    |    --es / --Spanish")
    print("  Actions:")
    print("           -p / --print  (Print translation output to the screen)")
    print("           -o / --overwrite  (Overwrite the file being translated)")
    print("           -c / --copy  (Copy the translation to a new .py file)")
    print("  Options:")
    print("           -n  (include line Numbers when using the Print action)")
    print("  Output:")
    print("           Translates a SeleniumBase Python file into the language")
    print('           specified. Method calls and "import" lines get swapped.')
    print("           Both a language and an action must be specified.")
    print('           The "-p" action can be paired with one other action.')
    print('           When running with "-c" (or "--copy"), the new file name')
    print("           will be the original name appended with an underscore")
    print("           plus the 2-letter language code of the new language.")
    print('           (Example: Translating "test_1.py" into Japanese with')
    print('            "-c" will create a new file called "test_1_ja.py".)')
    print("")

def show_extract_objects_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "extract-objects" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase extract-objects [SB_FILE.py]")
    print("           OR:    sbase extract-objects [SB_FILE.py]")
    print("  Output:")
    print("           Creates page objects based on selectors found in a")
    print("           seleniumbase Python file and saves those objects to the")
    print('           "page_objects.py" file in the same folder as the tests.')
    print("")

def show_inject_objects_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "inject-objects" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase inject-objects [SB_FILE.py] [OPTIONS]")
    print("           OR:    sbase inject-objects [SB_FILE.py] [OPTIONS]")
    print("  Options:")
    print("           -c, --comments  (Add object selectors to the comments.)")
    print("                           (Default: No added comments.)")
    print("  Output:")
    print('           Takes the page objects found in the "page_objects.py"')
    print("           file and uses those to replace matching selectors in")
    print("           the selected seleniumbase Python file.")
    print("")

def show_objectify_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "objectify" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase objectify [SB_FILE.py] [OPTIONS]")
    print("           OR:    sbase objectify [SB_FILE.py] [OPTIONS]")
    print("  Options:")
    print("           -c, --comments  (Add object selectors to the comments.)")
    print("                           (Default: No added comments.)")
    print("  Output:")
    print("           A modified version of the file where the selectors")
    print("           have been replaced with variable names defined in")
    print('           "page_objects.py", supporting the Page Object Pattern.')
    print("")
    print('           (seleniumbase "objectify" has the same outcome as')
    print('            combining "extract-objects" with "inject-objects")')
    print("")

def show_revert_objects_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "revert-objects" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase revert-objects [SB_FILE.py] [OPTIONS]")
    print("           OR:    sbase revert-objects [SB_FILE.py] [OPTIONS]")
    print("  Options:")
    print("           -c, --comments  (Keep existing comments for the lines.)")
    print("                           (Default: No comments are kept.)")
    print("  Output:")
    print('           Reverts the changes made by "seleniumbase objectify" or')
    print('           "seleniumbase inject-objects" when run against a')
    print("           seleniumbase Python file. Objects will get replaced by")
    print('           selectors stored in the "page_objects.py" file.')
    print("")

def show_encrypt_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "encrypt OR obfuscate" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase encrypt   ||   seleniumbase obfuscate")
    print("                                --OR--")
    print("                  sbase encrypt   ||          sbase obfuscate")
    print("  Output:")
    print("           Runs the password encryption/obfuscation tool.")
    print("           (Where you can enter a password to encrypt/obfuscate.)")
    print("")

def show_decrypt_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "decrypt OR unobfuscate" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase decrypt   ||   seleniumbase unobfuscate")
    print("                                --OR--")
    print("                  sbase decrypt   ||          sbase unobfuscate")
    print("  Output:")
    print("           Runs the password decryption/unobfuscation tool.")
    print("           (Where you can enter an encrypted password to decrypt.)")
    print("")

def show_download_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "download" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase download server")
    print("           OR:    sbase download server")
    print("  Output:")
    print("           Downloads the Selenium Standalone Server.")
    print("           (Server is required for using your own Selenium Grid.)")
    print("")

def show_grid_hub_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "grid-hub" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase grid-hub {start|stop|restart} [OPTIONS]")
    print("           OR:    sbase grid-hub {start|stop|restart} [OPTIONS]")
    print("  Options:")
    print("           -v, --verbose  (Increase verbosity of logging output.)")
    print("                          (Default: Quiet logging / not verbose.)")
    print("           --timeout=TIMEOUT  (Close idle browser after TIMEOUT.)")
    print("                              (The default TIMEOUT: 230 seconds.)")
    print("                              (Use --timeout=0 to skip timeouts.)")
    print("  Example:")
    print("           seleniumbase grid-hub start")
    print("  Output:")
    print("           Controls the Selenium Grid Hub Server, which allows")
    print("           for running tests on multiple machines in parallel")
    print("           to speed up test runs and reduce the total time")
    print("           of test suite execution.")
    print('           You can "start" or "stop" the Grid Hub server.')
    print("")

def show_grid_node_usage():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "  " + c2 + "** " + c3 + "grid-node" + c2 + " **" + cr
    print(sc)
    print("")
    print("  Usage:")
    print("           seleniumbase grid-node {start|stop|restart} [OPTIONS]")
    print("           OR:    sbase grid-node {start|stop|restart} [OPTIONS]")
    print("  Options:")
    print("           --hub=[HOST/IP]  (The Grid Hub Hostname / IP Address.)")
    print("                                 (Default: 127.0.0.1 if not set.)")
    print("           -v, --verbose  (Increase verbosity of logging output.)")
    print("                          (Default: Quiet logging / Not verbose.)")
    print("  Example:")
    print("           seleniumbase grid-node start --hub=127.0.0.1")
    print("  Output:")
    print("           Controls the Selenium Grid node, which serves as a")
    print("           worker machine for your Selenium Grid Hub server.")
    print('           You can "start" or "stop" the Grid node.')
    print("")

def get_version_info():
    # from pkg_resources import get_distribution
    # version = get_distribution("seleniumbase").version
    from seleniumbase import __version__

    version_info = None
    c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sb_text = c1 + "selenium" + c2 + "base" + cr
    version_info = "%s %s%s%s" % (sb_text, c3, __version__, cr)
    return version_info

def show_version_info():
    version_info = get_version_info()
    print("%s" % version_info)

def get_package_location():
    # from pkg_resources import get_distribution
    # location = get_distribution("seleniumbase").location
    import os
    import seleniumbase

    location = os.path.dirname(os.path.realpath(seleniumbase.__file__))
    if location.endswith("seleniumbase"):
        location = location[0 : -len("seleniumbase")]  # noqa: E203
    return location

def show_package_location():
    location = get_package_location()
    print("%s" % location)

def show_methods():
    c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    c4 = colorama.Fore.MAGENTA + colorama.Back.LIGHTYELLOW_EX
    c5 = colorama.Fore.LIGHTRED_EX + colorama.Back.LIGHTGREEN_EX
    cr = colorama.Style.RESET_ALL
    sc = (
        "\n " + c2 + " ** " + c3 + " SeleniumBase Python Methods "
        "" + c2 + " ** " + cr
    )
    print(sc)
    print("")
    line = "Here are some common methods that come with SeleniumBase:"
    line = c1 + line + cr
    print(line)
    line = "(Some optional args are not shown here)"
    print(line)
    print("")
    sbm = ""
    sbm += "*.open(url) => Navigate the browser window to the URL.\n"
    sbm += "*.type(selector, text) => Update the field with the text.\n"
    sbm += "*.click(selector) => Click the element with the selector.\n"
    sbm += "*.click_link(link_text) => Click the link containing text.\n"
    sbm += "*.go_back() => Navigate back to the previous URL.\n"
    sbm += "*.select_option_by_text(dropdown_selector, option)\n"
    sbm += "*.hover_and_click(hover_selector, click_selector)\n"
    sbm += "*.drag_and_drop(drag_selector, drop_selector)\n"
    sbm += "*.get_text(selector) => Get the text from the element.\n"
    sbm += "*.get_current_url() => Get the URL of the current page.\n"
    sbm += "*.get_page_source() => Get the HTML of the current page.\n"
    sbm += "*.get_attribute(selector, attribute) => Get element attribute.\n"
    sbm += "*.get_title() => Get the title of the current page.\n"
    sbm += "*.switch_to_frame(frame) => Switch into the iframe container.\n"
    sbm += "*.switch_to_default_content() => Exit all iframe containers.\n"
    sbm += "*.switch_to_parent_frame() => Exit from the current iframe.\n"
    sbm += "*.open_new_window() => Open a new window in the same browser.\n"
    sbm += "*.switch_to_window(window) => Switch to the browser window.\n"
    sbm += "*.switch_to_default_window() => Switch to the original window.\n"
    sbm += "*.get_new_driver(OPTIONS) => Open a new driver with OPTIONS.\n"
    sbm += "*.switch_to_driver(driver) => Switch to the browser driver.\n"
    sbm += "*.switch_to_default_driver() => Switch to the original driver.\n"
    sbm += "*.wait_for_element(selector) => Wait until element is visible.\n"
    sbm += "*.is_element_visible(selector) => Return element visibility.\n"
    sbm += "*.is_text_visible(text, selector) => Return text visibility.\n"
    sbm += "*.sleep(seconds) => Do nothing for the given amount of time.\n"
    sbm += "*.save_screenshot(name) => Save a screenshot in .png format.\n"
    sbm += "*.assert_element(selector) => Verify the element is visible.\n"
    sbm += "*.assert_text(text, selector) => Verify text in the element.\n"
    sbm += "*.assert_title(title) => Verify the title of the web page.\n"
    sbm += "*.assert_downloaded_file(file) => Verify file was downloaded.\n"
    sbm += "*.assert_no_404_errors() => Verify there are no broken links.\n"
    sbm += "*.assert_no_js_errors() => Verify there are no JS errors.\n"
    sbm = sbm.replace("*.", "self." + c1).replace("(", cr + "(")
    sbm = sbm.replace("self.", c2 + "self" + c5 + "." + cr)
    sbm = sbm.replace("(", c3 + "(" + c4)
    sbm = sbm.replace(")", c3 + ")" + cr)
    print(sbm)

def show_options():
    c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    c4 = colorama.Fore.MAGENTA + colorama.Back.LIGHTYELLOW_EX
    c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "\n " + c2 + " ** " + c3 + " pytest CLI Options " + c2 + " ** " + cr
    print(sc)
    print("")
    line = "Here are some common pytest options to use with SeleniumBase:"
    line = c1 + line + cr
    print(line)
    line = '(Some options are Chromium-specific, e.g. "--guest --mobile")'
    print(line)
    op = "\n"
    op += '--browser=BROWSER  (The web browser to use. Default is "chrome")\n'
    op += "--headless  (Run tests headlessly. Default mode on Linux OS.)\n"
    op += "--demo  (Slow down and visually see test actions as they occur.)\n"
    op += "--slow  (Slow down the automation. Faster than using Demo Mode.)\n"
    op += "--reuse-session / --rs  (Reuse browser session between tests.)\n"
    op += "--crumbs  (Clear all cookies between tests reusing a session.)\n"
    op += "--maximize  (Start tests with the web browser window maximized.)\n"
    op += "--dashboard  (Enable SeleniumBase's Dashboard at dashboard.html)\n"
    op += "--incognito  (Enable Chromium's Incognito mode.)\n"
    op += "--guest  (Enable Chromium's Guest mode.)\n"
    op += "-m=MARKER  (Run tests with the specified pytest marker.)\n"
    op += "-n=NUM  (Multithread the tests using that many threads.)\n"
    op += "-v  (Verbose mode. Print the full names of each test run.)\n"
    op += "--html=report.html  (Create a detailed pytest-html report.)\n"
    op += "--collect-only / --co  (Only show discovered tests. No run.)\n"
    op += "--co -q  (Only show full names of discovered tests. No run.)\n"
    op += "-x  (Stop running tests after the first failure is reached.)\n"
    op += "--pdb  (Enter the Post Mortem Debug Mode after any test fails.)\n"
    op += "--trace  (Enter Debug Mode immediately after starting any test.)\n"
    op += "      | Debug Mode Commands  >>>   help / h: List all commands. |\n"
    op += "      |   n: Next line of method. s: Step through. c: Continue. |\n"
    op += "      |  return / r: Run until method returns. j: Jump to line. |\n"
    op += "      | where / w: Show stack spot. u: Up stack. d: Down stack. |\n"
    op += "      | longlist / ll: See code. dir(): List namespace objects. |\n"
    op += "--recorder  (Record browser actions to generate test scripts.)\n"
    op += "--save-screenshot  (Save a screenshot at the end of each test.)\n"
    op += "--archive-logs  (Archive old log files instead of deleting them.)\n"
    op += "--check-js  (Check for JavaScript errors after page loads.)\n"
    op += "--start-page=URL  (The browser start page when tests begin.)\n"
    op += "--agent=STRING  (Modify the web browser's User-Agent string.)\n"
    op += "--mobile  (Use Chromium's mobile device emulator during tests.)\n"
    op += '--metrics=STRING  (Set mobile "CSSWidth,CSSHeight,PixelRatio".)\n'
    op += "--ad-block  (Block some types of display ads after page loads.)\n"
    op += "--settings-file=FILE  (Override default SeleniumBase settings.)\n"
    op += '--env=ENV  (Set the test env. Access with "self.env" in tests.)\n'
    op += '--data=DATA  (Extra test data. Access with "self.data" in tests.)\n'
    op += "--disable-csp  (Disable the Content Security Policy of websites.)\n"
    op += "--server=SERVER  (The Selenium Grid server/IP used for tests.)\n"
    op += "--port=PORT  (The Selenium Grid port used by the test server.)\n"
    op += "--proxy=SERVER:PORT  (Connect to a proxy server:port for tests.)\n"
    op += "--proxy=USER:PASS@SERVER:PORT  (Use authenticated proxy server.)\n"
    op += cr
    op = op.replace("\n-", "\n" + c1 + "-").replace("  (", cr + "  (")
    op = op.replace(" / -", cr + " / " + c1 + "-")
    op = op.replace("=", c2 + "=" + c3)
    op = op.replace(" | ", " |" + c3 + " ").replace("|\n", cr + "|\n")
    op = op.replace(": ", c5 + ":" + c3 + " ")
    op = op.replace("Debug Mode Commands", c5 + "Debug Mode Commands" + c3)
    op = op.replace(">>>", c4 + ">>>" + c3)
    print(op)
    line = "For the full list of " + c2 + "command-line options" + cr
    line += ', type: "' + c3 + "pytest" + cr + " " + c1 + "--help" + cr + '".'
    print(line)
    print("")

def show_behave_options():
    c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    c4 = colorama.Fore.MAGENTA + colorama.Back.LIGHTYELLOW_EX
    c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
    cr = colorama.Style.RESET_ALL
    sc = "\n " + c2 + " ** " + c3 + " Behave CLI Options " + c2 + " ** " + cr
    print(sc)
    print("")
    line = 'Here are some common "behave" options to use with SeleniumBase:'
    line = c1 + line + cr
    print(line)
    line = '(Some options are Chromium-specific, e.g. "-D guest -D mobile")'
    print(line)
    op = "\n"
    op += '-D browser=BROWSER  (The web browser to use. Default is "chrome")\n'
    op += "-D headless  (Run tests headlessly. Default mode on Linux OS.)\n"
    op += "-D demo  (Slow down and visually see test actions as they occur.)\n"
    op += "-D slow  (Slow down the automation. Faster than using Demo Mode.)\n"
    op += "-D reuse-session / -D rs  (Reuse browser session between tests.)\n"
    op += "-D crumbs  (Clear all cookies between tests reusing a session.)\n"
    op += "-D maximize  (Start tests with the web browser window maximized.)\n"
    op += "-D dashboard  (Enable SeleniumBase's Dashboard at dashboard.html)\n"
    op += "-D incognito  (Enable Chromium's Incognito mode.)\n"
    op += "-D guest  (Enable Chromium's Guest mode.)\n"
    op += "--no-snippets / -q  (Quiet mode. Don't print snippets.)\n"
    op += "--dry-run / -d  (Dry run. Only show discovered tests.)\n"
    op += "--stop  (Stop running tests after the first failure is reached.)\n"
    op += "-D pdb  (Enter the Post Mortem Debug Mode after any test fails.)\n"
    op += "      | Debug Mode Commands  >>>   help / h: List all commands. |\n"
    op += "      |   n: Next line of method. s: Step through. c: Continue. |\n"
    op += "      |  return / r: Run until method returns. j: Jump to line. |\n"
    op += "      | where / w: Show stack spot. u: Up stack. d: Down stack. |\n"
    op += "      | longlist / ll: See code. dir(): List namespace objects. |\n"
    op += "-D recorder  (Record browser actions to generate test scripts.)\n"
    op += "-D save-screenshot  (Save a screenshot at the end of each test.)\n"
    op += "-D archive-logs  (Archive log files instead of deleting them.)\n"
    op += "-D check-js  (Check for JavaScript errors after page loads.)\n"
    op += "-D start-page=URL  (The browser start page when tests begin.)\n"
    op += "-D agent=STRING  (Modify the web browser's User-Agent string.)\n"
    op += "-D mobile  (Use Chromium's mobile device emulator during tests.)\n"
    op += '-D metrics=STRING  (Set mobile "CSSWidth,CSSHeight,PixelRatio".)\n'
    op += "-D ad-block  (Block some types of display ads after page loads.)\n"
    op += "-D settings-file=FILE  (Override default SeleniumBase settings.)\n"
    op += '-D env=ENV  (Set the test env. Access using "self.env" in tests.)\n'
    op += '-D data=DATA  (Extra test data. Access using "self.data".)\n'
    op += "-D disable-csp  (Disable the Content Security Policy of sites.)\n"
    op += "-D server=SERVER  (The Selenium Grid server/IP used for tests.)\n"
    op += "-D port=PORT  (The Selenium Grid port used by the test server.)\n"
    op += "-D proxy=SERVER:PORT  (Connect to a proxy server:port for tests.)\n"
    op += "-D proxy=USER:PASS@SERVER:PORT  (Use authenticated proxy server.)\n"
    op += cr
    op = op.replace("\n-", "\n" + c1 + "-").replace("  (", cr + "  (")
    op = op.replace(" / -", cr + " / " + c1 + "-")
    op = op.replace("=", c2 + "=" + c3)
    op = op.replace(" | ", " |" + c3 + " ").replace("|\n", cr + "|\n")
    op = op.replace(": ", c5 + ":" + c3 + " ")
    op = op.replace("Debug Mode Commands", c5 + "Debug Mode Commands" + c3)
    op = op.replace(">>>", c4 + ">>>" + c3)
    print(op)
    line = "For the full list of " + c2 + "command-line options" + cr
    line += ', type: "' + c3 + "behave" + cr + " " + c1 + "--help" + cr + '".'
    print(line)
    print("")

def show_detailed_help():
    c2 = colorama.Fore.BLUE + colorama.Back.LIGHTGREEN_EX
    c3 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX
    c6 = colorama.Back.CYAN
    cr = colorama.Style.RESET_ALL
    show_basic_usage()
    print(c6 + "            " + c2 + "  Commands:  " + c6 + "            ")
    print(cr)
    show_install_usage()
    show_commander_usage()
    show_behave_gui_usage()
    show_mkdir_usage()
    show_mkfile_usage()
    show_mkrec_usage()
    show_codegen_usage()
    show_recorder_usage()
    show_mkpres_usage()
    show_mkchart_usage()
    show_convert_usage()
    show_print_usage()
    show_translate_usage()
    show_extract_objects_usage()
    show_inject_objects_usage()
    show_objectify_usage()
    show_revert_objects_usage()
    show_encrypt_usage()
    show_decrypt_usage()
    show_download_usage()
    show_grid_hub_usage()
    show_grid_node_usage()
    print('* (Use "' + c3 + "pytest" + cr + '" for running tests) *\n')

def main():
    command = None
    command_args = None
    num_args = len(sys.argv)
    if num_args == 1:
        show_usage()
        return
    elif num_args == 2:
        command = sys.argv[1]
        command_args = []
    elif num_args > 2:
        command = sys.argv[1]
        command_args = sys.argv[2:]
    command = command.lower()

    if command == "get" or command == "install":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_install

            sb_install.main()
        else:
            show_basic_usage()
            show_install_usage()
    elif command == "commander" or command == "gui":
        from seleniumbase.console_scripts import sb_commander

        sb_commander.main()
    elif command == "behave-gui" or command == "gui-behave":
        from seleniumbase.console_scripts import sb_behave_gui

        sb_behave_gui.main()
    elif (
        command == "recorder"
        or (command == "record" and len(command_args) == 0)
    ):
        from seleniumbase.console_scripts import sb_recorder

        sb_recorder.main()
    elif (
        command == "mkrec"
        or command == "codegen"
        or (command == "record" and len(command_args) >= 1)
    ):
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_mkrec

            sb_mkrec.main()
        else:
            show_basic_usage()
            if command == "codegen":
                show_codegen_usage()
            else:
                show_mkrec_usage()
    elif command == "mkdir":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_mkdir

            sb_mkdir.main()
        else:
            show_basic_usage()
            show_mkdir_usage()
    elif command == "mkfile":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_mkfile

            sb_mkfile.main()
        else:
            show_basic_usage()
            show_mkfile_usage()
    elif command == "mkpres":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_mkpres

            sb_mkpres.main()
        else:
            show_basic_usage()
            show_mkpres_usage()
    elif command == "mkchart":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_mkchart

            sb_mkchart.main()
        else:
            show_basic_usage()
            show_mkchart_usage()
    elif command == "convert":
        if len(command_args) == 1:
            from seleniumbase.utilities.selenium_ide import convert_ide

            convert_ide.main()
        else:
            show_basic_usage()
            show_convert_usage()
    elif command == "print":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import sb_print

            sb_print.main()
        else:
            show_basic_usage()
            show_print_usage()
    elif command == "translate":
        if len(command_args) >= 1:
            if sys.version_info[0] == 2:
                c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
                cr = colorama.Style.RESET_ALL
                msg = "The SeleniumBase Translator does NOT support Python 2!"
                message = "\n" + c5 + msg + cr + "\n"
                print("")
                raise Exception(message)
            from seleniumbase.translate import translator

            translator.main()
        else:
            show_basic_usage()
            show_translate_usage()
    elif command == "extract-objects" or command == "extract_objects":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import objectify

            objectify.extract_objects()
        else:
            show_basic_usage()
            show_extract_objects_usage()
    elif command == "inject-objects" or command == "inject_objects":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import objectify

            objectify.inject_objects()
        else:
            show_basic_usage()
            show_inject_objects_usage()
    elif command == "objectify":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import objectify

            objectify.objectify()
        else:
            show_basic_usage()
            show_objectify_usage()
    elif command == "revert-objects" or command == "revert_objects":
        if len(command_args) >= 1:
            from seleniumbase.console_scripts import objectify

            objectify.revert_objects()
        else:
            show_basic_usage()
            show_revert_objects_usage()
    elif command == "encrypt" or command == "obfuscate":
        if len(command_args) >= 0:
            from seleniumbase.common import obfuscate

            obfuscate.main()
        else:
            show_basic_usage()
            show_encrypt_usage()
    elif command == "decrypt" or command == "unobfuscate":
        if len(command_args) >= 0:
            from seleniumbase.common import unobfuscate

            unobfuscate.main()
        else:
            show_basic_usage()
            show_decrypt_usage()
    elif command == "download":
        if len(command_args) >= 1 and command_args[0].lower() == "server":
            from seleniumbase.utilities.selenium_grid import (
                download_selenium_server,
            )

            download_selenium_server.main(force_download=True)
        else:
            show_basic_usage()
            show_download_usage()
    elif command == "grid-hub" or command == "grid_hub":
        if len(command_args) >= 1:
            from seleniumbase.utilities.selenium_grid import grid_hub

            grid_hub.main()
        else:
            show_basic_usage()
            show_grid_hub_usage()
    elif command == "grid-node" or command == "grid_node":
        if len(command_args) >= 1:
            from seleniumbase.utilities.selenium_grid import grid_node

            grid_node.main()
        else:
            show_basic_usage()
            show_grid_node_usage()
    elif command == "version" or command == "--version":
        if len(command_args) == 0:
            from seleniumbase.console_scripts import logo_helper

            seleniumbase_logo = logo_helper.get_seleniumbase_logo()
            print(seleniumbase_logo)
            print("")
            show_package_location()
            show_version_info()
            print("")
        else:
            show_basic_usage()
    elif command == "methods" or command == "--methods":
        show_methods()
    elif command == "options" or command == "--options":
        show_options()
    elif command == "behave-options" or command == "--behave-options":
        show_behave_options()
    elif command == "help" or command == "--help":
        if len(command_args) >= 1:
            if command_args[0] == "get":
                print("")
                show_install_usage()
                return
            elif command_args[0] == "install":
                print("")
                show_install_usage()
                return
            elif command_args[0] == "commander":
                print("")
                show_commander_usage()
                return
            elif command_args[0] == "gui":
                print("")
                show_commander_usage()
                return
            elif command_args[0] == "behave-gui":
                print("")
                show_behave_gui_usage()
                return
            elif command_args[0] == "gui-behave":
                print("")
                show_behave_gui_usage()
                return
            elif command_args[0] == "mkdir":
                print("")
                show_mkdir_usage()
                return
            elif command_args[0] == "mkfile":
                print("")
                show_mkfile_usage()
                return
            elif command_args[0] == "mkrec":
                print("")
                show_mkrec_usage()
                return
            elif command_args[0] == "codegen":
                print("")
                show_codegen_usage()
                return
            elif command_args[0] == "recorder":
                print("")
                show_recorder_usage()
                return
            elif command_args[0] == "mkpres":
                print("")
                show_mkpres_usage()
                return
            elif command_args[0] == "mkchart":
                print("")
                show_mkchart_usage()
                return
            elif command_args[0] == "convert":
                print("")
                show_convert_usage()
                return
            elif command_args[0] == "print":
                print("")
                show_print_usage()
                return
            elif command_args[0] == "translate":
                print("")
                show_translate_usage()
                return
            elif command_args[0] == "extract-objects":
                print("")
                show_extract_objects_usage()
                return
            elif command_args[0] == "inject-objects":
                print("")
                show_inject_objects_usage()
                return
            elif command_args[0] == "objectify":
                print("")
                show_objectify_usage()
                return
            elif command_args[0] == "revert-objects":
                print("")
                show_revert_objects_usage()
                return
            elif command_args[0] == "encrypt":
                print("")
                show_encrypt_usage()
                return
            elif command_args[0] == "obfuscate":
                print("")
                show_encrypt_usage()
                return
            elif command_args[0] == "decrypt":
                print("")
                show_decrypt_usage()
                return
            elif command_args[0] == "unobfuscate":
                print("")
                show_decrypt_usage()
                return
            elif command_args[0] == "download":
                print("")
                show_download_usage()
                return
            elif command_args[0] == "grid-hub":
                print("")
                show_grid_hub_usage()
                return
            elif command_args[0] == "grid-node":
                print("")
                show_grid_node_usage()
                return
        show_detailed_help()
    else:
        show_usage()
        colorama.init(autoreset=True)
        c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
        c7 = colorama.Fore.BLACK + colorama.Back.MAGENTA
        cr = colorama.Style.RESET_ALL
        invalid_cmd = "===> INVALID COMMAND: >> %s <<\n" % command
        invalid_cmd = invalid_cmd.replace(">> ", ">>" + c5 + " ")
        invalid_cmd = invalid_cmd.replace(" <<", " " + cr + "<<")
        invalid_cmd = invalid_cmd.replace(">>", c7 + ">>" + cr)
        invalid_cmd = invalid_cmd.replace("<<", c7 + "<<" + cr)
        print(invalid_cmd)

if __name__ == "__main__":
    main()


text:
'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.netflix.fastProperties.scopeLadder.strategy.controller', [
    require('../../../../core/utils/lodash'),
    require('../../fastProperty.write.service.js')
  ])
  .controller('ScopeLadderStrategyController', function(parentVM, fastPropertyWriter, modalInstance,  _) {
    let vm = parentVM;

    //vm.property = $scope.property;
    //vm.property.targetScope = $scope.selectedScope;
    //vm.property.impactCount = $scope.impactCount;
    //vm.selectedScope = $scope.selectedScope;
    //vm.clusters = $scope.clusters;
    //vm.isEditing = $scope.isEditing;
    //vm.appName = $scope.appName;
    vm.property.strategy.name = 'naive';

    vm.submit = () => {
      vm.property.startScope = vm.transformScope(vm.property.startScope);
      vm.property.targetScope = vm.transformScope(vm.property.targetScope);

      delete vm.property.env; //removing to help with downstream marshalling.
      delete vm.property.canary;

      fastPropertyWriter.upsertFastProperty(vm.property).then(
        function(result) {
          modalInstance.close(result);
        },
        function(error) {
          window.alert(JSON.stringify(error));
        });
    };

    vm.update = () => {
      var updatedParams = _(vm.property).omit(['ts', 'createdAsCanary']).value();
      vm.property.startScope = vm.transformScope(vm.property.startScope);
      vm.property.targetScope = vm.transformScope(vm.property.targetScope);

      delete vm.property.env; //removing to help with downstream marshalling.
      delete vm.property.canary;

      fastPropertyWriter.upsertFastProperty(updatedParams).then(
        function(result) {
          modalInstance.close(result);
        }
      );
    };

    return vm;
  })
 .name;

redpajama_set_name: RedPajamaGithub


text:
package dynamodb

import (
	"context"
	"fmt"
	"strings"

	"github.com/Clever/wag/samples/v8/gen-go-db-only/db"
	"github.com/Clever/wag/samples/v8/gen-go-db-only/models"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
	"github.com/go-openapi/strfmt"
)

var _ = strfmt.DateTime{}

// DeploymentTable represents the user-configurable properties of the Deployment table.
type DeploymentTable struct {
	DynamoDBAPI        dynamodbiface.DynamoDBAPI
	Prefix             string
	TableName          string
	ReadCapacityUnits  int64
	WriteCapacityUnits int64
}

// ddbDeploymentPrimaryKey represents the primary key of a Deployment in DynamoDB.
type ddbDeploymentPrimaryKey struct {
	EnvApp  string `dynamodbav:"envApp"`
	Version string `dynamodbav:"version"`
}

// ddbDeploymentGSIByDate represents the byDate GSI.
type ddbDeploymentGSIByDate struct {
	EnvApp string          `dynamodbav:"envApp"`
	Date   strfmt.DateTime `dynamodbav:"date"`
}

// ddbDeploymentGSIByEnvironment represents the byEnvironment GSI.
type ddbDeploymentGSIByEnvironment struct {
	Environment string          `dynamodbav:"environment"`
	Date        strfmt.DateTime `dynamodbav:"date"`
}

// ddbDeploymentGSIByVersion represents the byVersion GSI.
type ddbDeploymentGSIByVersion struct {
	Version string `dynamodbav:"version"`
}

// ddbDeployment represents a Deployment as stored in DynamoDB.
type ddbDeployment struct {
	models.Deployment
}

func (t DeploymentTable) name() string {
	if t.TableName != "" {
		return t.TableName
	}
	return fmt.Sprintf("%s-deployments", t.Prefix)
}

func (t DeploymentTable) create(ctx context.Context) error {
	if _, err := t.DynamoDBAPI.CreateTableWithContext(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []*dynamodb.AttributeDefinition{
			{
				AttributeName: aws.String("date"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("envApp"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("environment"),
				AttributeType: aws.String("S"),
			},
			{
				AttributeName: aws.String("version"),
				AttributeType: aws.String("S"),
			},
		},
		KeySchema: []*dynamodb.KeySchemaElement{
			{
				AttributeName: aws.String("envApp"),
				KeyType:       aws.String(dynamodb.KeyTypeHash),
			},
			{
				AttributeName: aws.String("version"),
				KeyType:       aws.String(dynamodb.KeyTypeRange),
			},
		},
		GlobalSecondaryIndexes: []*dynamodb.GlobalSecondaryIndex{
			{
				IndexName: aws.String("byDate"),
				Projection: &dynamodb.Projection{
					ProjectionType: aws.String("ALL"),
				},
				KeySchema: []*dynamodb.KeySchemaElement{
					{
						AttributeName: aws.String("envApp"),
						KeyType:       aws.String(dynamodb.KeyTypeHash),
					},
					{
						AttributeName: aws.String("date"),
						KeyType:       aws.String(dynamodb.KeyTypeRange),
					},
				},
				ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
					ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
					WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
				},
			},
			{
				IndexName: aws.String("byEnvironment"),
				Projection: &dynamodb.Projection{
					ProjectionType: aws.String("ALL"),
				},
				KeySchema: []*dynamodb.KeySchemaElement{
					{
						AttributeName: aws.String("environment"),
						KeyType:       aws.String(dynamodb.KeyTypeHash),
					},
					{
						AttributeName: aws.String("date"),
						KeyType:       aws.String(dynamodb.KeyTypeRange),
					},
				},
				ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
					ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
					WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
				},
			},
			{
				IndexName: aws.String("byVersion"),
				Projection: &dynamodb.Projection{
					ProjectionType: aws.String("ALL"),
				},
				KeySchema: []*dynamodb.KeySchemaElement{
					{
						AttributeName: aws.String("version"),
						KeyType:       aws.String(dynamodb.KeyTypeHash),
					},
				},
				ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
					ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
					WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
				},
			},
		},
		ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
			ReadCapacityUnits:  aws.Int64(t.ReadCapacityUnits),
			WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits),
		},
		TableName: aws.String(t.name()),
	}); err != nil {
		return err
	}
	return nil
}

func (t DeploymentTable) saveDeployment(ctx context.Context, m models.Deployment) error {
	data, err := encodeDeployment(m)
	if err != nil {
		return err
	}
	_, err = t.DynamoDBAPI.PutItemWithContext(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(t.name()),
		Item:      data,
	})
	return err
}

func (t DeploymentTable) getDeployment(ctx context.Context, environment string, application string, version string) (*models.Deployment, error) {
	key, err := dynamodbattribute.MarshalMap(ddbDeploymentPrimaryKey{
		EnvApp:  fmt.Sprintf("%s--%s", environment, application),
		Version: version,
	})
	if err != nil {
		return nil, err
	}
	res, err := t.DynamoDBAPI.GetItemWithContext(ctx, &dynamodb.GetItemInput{
		Key:            key,
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(true),
	})
	if err != nil {
		return nil, err
	}

	if len(res.Item) == 0 {
		return nil, db.ErrDeploymentNotFound{
			Environment: environment,
			Application: application,
			Version:     version,
		}
	}

	var m models.Deployment
	if err := decodeDeployment(res.Item, &m); err != nil {
		return nil, err
	}

	return &m, nil
}

func (t DeploymentTable) scanDeployments(ctx context.Context, input db.ScanDeploymentsInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	scanInput := &dynamodb.ScanInput{
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(!input.DisableConsistentRead),
		Limit:          input.Limit,
	}
	if input.StartingAfter != nil {
		exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter)
		if err != nil {
			return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error())
		}
		// must provide only the fields constituting the index
		scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
			"version": exclusiveStartKey["version"],
		}
	}
	totalRecordsProcessed := int64(0)
	var innerErr error
	err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool {
		items, err := decodeDeployments(out.Items)
		if err != nil {
			innerErr = fmt.Errorf("error decoding %s", err.Error())
			return false
		}
		for i := range items {
			if input.Limiter != nil {
				if err := input.Limiter.Wait(ctx); err != nil {
					innerErr = err
					return false
				}
			}
			isLastModel := lastPage && i == len(items)-1
			if shouldContinue := fn(&items[i], isLastModel); !shouldContinue {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	})
	if innerErr != nil {
		return innerErr
	}
	return err
}

func (t DeploymentTable) getDeploymentsByEnvAppAndVersionParseFilters(queryInput *dynamodb.QueryInput, input db.GetDeploymentsByEnvAppAndVersionInput) {
	for _, filterValue := range input.FilterValues {
		switch filterValue.AttributeName {
		case db.DeploymentDate:
			queryInput.ExpressionAttributeNames["#DATE"] = aws.String(string(db.DeploymentDate))
			for i, attributeValue := range filterValue.AttributeValues {
				queryInput.ExpressionAttributeValues[fmt.Sprintf(":%s_value%d", string(db.DeploymentDate), i)] = &dynamodb.AttributeValue{
					S: aws.String(toDynamoTimeString(attributeValue.(strfmt.DateTime))),
				}
			}
		}
	}
}

func (t DeploymentTable) getDeploymentsByEnvAppAndVersion(ctx context.Context, input db.GetDeploymentsByEnvAppAndVersionInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	if input.VersionStartingAt != nil && input.StartingAfter != nil {
		return fmt.Errorf("Can specify only one of input.VersionStartingAt or input.StartingAfter")
	}
	if input.Environment == "" {
		return fmt.Errorf("Hash key input.Environment cannot be empty")
	}
	if input.Application == "" {
		return fmt.Errorf("Hash key input.Application cannot be empty")
	}
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		ExpressionAttributeNames: map[string]*string{
			"#ENVAPP": aws.String("envApp"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.Environment, input.Application)),
			},
		},
		ScanIndexForward: aws.Bool(!input.Descending),
		ConsistentRead:   aws.Bool(!input.DisableConsistentRead),
	}
	if input.Limit != nil {
		queryInput.Limit = input.Limit
	}
	if input.VersionStartingAt == nil {
		queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp")
	} else {
		queryInput.ExpressionAttributeNames["#VERSION"] = aws.String("version")
		queryInput.ExpressionAttributeValues[":version"] = &dynamodb.AttributeValue{
			S: aws.String(*input.VersionStartingAt),
		}
		if input.Descending {
			queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp AND #VERSION <= :version")
		} else {
			queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp AND #VERSION >= :version")
		}
	}
	if input.StartingAfter != nil {
		queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"version": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Version),
			},
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
		}
	}
	if len(input.FilterValues) > 0 && input.FilterExpression != "" {
		t.getDeploymentsByEnvAppAndVersionParseFilters(queryInput, input)
		queryInput.FilterExpression = aws.String(input.FilterExpression)
	}

	totalRecordsProcessed := int64(0)
	var pageFnErr error
	pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool {
		// Only assume an empty page means no more results if there are no filters applied
		if (len(input.FilterValues) == 0 || input.FilterExpression == "") && len(queryOutput.Items) == 0 {
			return false
		}
		items, err := decodeDeployments(queryOutput.Items)
		if err != nil {
			pageFnErr = err
			return false
		}
		hasMore := true
		for i := range items {
			if lastPage == true {
				hasMore = i < len(items)-1
			}
			if !fn(&items[i], !hasMore) {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	}

	err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn)
	if err != nil {
		return err
	}
	if pageFnErr != nil {
		return pageFnErr
	}

	return nil
}

func (t DeploymentTable) deleteDeployment(ctx context.Context, environment string, application string, version string) error {
	key, err := dynamodbattribute.MarshalMap(ddbDeploymentPrimaryKey{
		EnvApp:  fmt.Sprintf("%s--%s", environment, application),
		Version: version,
	})
	if err != nil {
		return err
	}
	_, err = t.DynamoDBAPI.DeleteItemWithContext(ctx, &dynamodb.DeleteItemInput{
		Key:       key,
		TableName: aws.String(t.name()),
	})
	if err != nil {
		return err
	}

	return nil
}

func (t DeploymentTable) getDeploymentsByEnvAppAndDate(ctx context.Context, input db.GetDeploymentsByEnvAppAndDateInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	if input.DateStartingAt != nil && input.StartingAfter != nil {
		return fmt.Errorf("Can specify only one of input.DateStartingAt or input.StartingAfter")
	}
	if input.Environment == "" {
		return fmt.Errorf("Hash key input.Environment cannot be empty")
	}
	if input.Application == "" {
		return fmt.Errorf("Hash key input.Application cannot be empty")
	}
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		IndexName: aws.String("byDate"),
		ExpressionAttributeNames: map[string]*string{
			"#ENVAPP": aws.String("envApp"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.Environment, input.Application)),
			},
		},
		ScanIndexForward: aws.Bool(!input.Descending),
		ConsistentRead:   aws.Bool(false),
	}
	if input.Limit != nil {
		queryInput.Limit = input.Limit
	}
	if input.DateStartingAt == nil {
		queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp")
	} else {
		queryInput.ExpressionAttributeNames["#DATE"] = aws.String("date")
		queryInput.ExpressionAttributeValues[":date"] = &dynamodb.AttributeValue{
			S: aws.String(toDynamoTimeString(*input.DateStartingAt)),
		}
		if input.Descending {
			queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp AND #DATE <= :date")
		} else {
			queryInput.KeyConditionExpression = aws.String("#ENVAPP = :envApp AND #DATE >= :date")
		}
	}
	if input.StartingAfter != nil {
		queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"date": &dynamodb.AttributeValue{
				S: aws.String(toDynamoTimeString(input.StartingAfter.Date)),
			},
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
			"version": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Version),
			},
		}
	}

	totalRecordsProcessed := int64(0)
	var pageFnErr error
	pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool {
		if len(queryOutput.Items) == 0 {
			return false
		}
		items, err := decodeDeployments(queryOutput.Items)
		if err != nil {
			pageFnErr = err
			return false
		}
		hasMore := true
		for i := range items {
			if lastPage == true {
				hasMore = i < len(items)-1
			}
			if !fn(&items[i], !hasMore) {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	}

	err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn)
	if err != nil {
		return err
	}
	if pageFnErr != nil {
		return pageFnErr
	}

	return nil
}
func (t DeploymentTable) scanDeploymentsByEnvAppAndDate(ctx context.Context, input db.ScanDeploymentsByEnvAppAndDateInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	scanInput := &dynamodb.ScanInput{
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(!input.DisableConsistentRead),
		Limit:          input.Limit,
		IndexName:      aws.String("byDate"),
	}
	if input.StartingAfter != nil {
		exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter)
		if err != nil {
			return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error())
		}
		// must provide the fields constituting the index and the primary key
		// https://stackoverflow.com/questions/40988397/dynamodb-pagination-with-withexclusivestartkey-on-a-global-secondary-index
		scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
			"version": exclusiveStartKey["version"],
			"date":    exclusiveStartKey["date"],
		}
	}
	totalRecordsProcessed := int64(0)
	var innerErr error
	err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool {
		items, err := decodeDeployments(out.Items)
		if err != nil {
			innerErr = fmt.Errorf("error decoding %s", err.Error())
			return false
		}
		for i := range items {
			if input.Limiter != nil {
				if err := input.Limiter.Wait(ctx); err != nil {
					innerErr = err
					return false
				}
			}
			isLastModel := lastPage && i == len(items)-1
			if shouldContinue := fn(&items[i], isLastModel); !shouldContinue {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	})
	if innerErr != nil {
		return innerErr
	}
	return err
}
func (t DeploymentTable) getDeploymentsByEnvironmentAndDate(ctx context.Context, input db.GetDeploymentsByEnvironmentAndDateInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	if input.DateStartingAt != nil && input.StartingAfter != nil {
		return fmt.Errorf("Can specify only one of input.DateStartingAt or input.StartingAfter")
	}
	if input.Environment == "" {
		return fmt.Errorf("Hash key input.Environment cannot be empty")
	}
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		IndexName: aws.String("byEnvironment"),
		ExpressionAttributeNames: map[string]*string{
			"#ENVIRONMENT": aws.String("environment"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":environment": &dynamodb.AttributeValue{
				S: aws.String(input.Environment),
			},
		},
		ScanIndexForward: aws.Bool(!input.Descending),
		ConsistentRead:   aws.Bool(false),
	}
	if input.Limit != nil {
		queryInput.Limit = input.Limit
	}
	if input.DateStartingAt == nil {
		queryInput.KeyConditionExpression = aws.String("#ENVIRONMENT = :environment")
	} else {
		queryInput.ExpressionAttributeNames["#DATE"] = aws.String("date")
		queryInput.ExpressionAttributeValues[":date"] = &dynamodb.AttributeValue{
			S: aws.String(toDynamoTimeString(*input.DateStartingAt)),
		}
		if input.Descending {
			queryInput.KeyConditionExpression = aws.String("#ENVIRONMENT = :environment AND #DATE <= :date")
		} else {
			queryInput.KeyConditionExpression = aws.String("#ENVIRONMENT = :environment AND #DATE >= :date")
		}
	}
	if input.StartingAfter != nil {
		queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"date": &dynamodb.AttributeValue{
				S: aws.String(toDynamoTimeString(input.StartingAfter.Date)),
			},
			"environment": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Environment),
			},
			"version": &dynamodb.AttributeValue{
				S: aws.String(input.StartingAfter.Version),
			},
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
		}
	}

	totalRecordsProcessed := int64(0)
	var pageFnErr error
	pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool {
		if len(queryOutput.Items) == 0 {
			return false
		}
		items, err := decodeDeployments(queryOutput.Items)
		if err != nil {
			pageFnErr = err
			return false
		}
		hasMore := true
		for i := range items {
			if lastPage == true {
				hasMore = i < len(items)-1
			}
			if !fn(&items[i], !hasMore) {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	}

	err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn)
	if err != nil {
		return err
	}
	if pageFnErr != nil {
		return pageFnErr
	}

	return nil
}
func (t DeploymentTable) getDeploymentByVersion(ctx context.Context, version string) (*models.Deployment, error) {
	queryInput := &dynamodb.QueryInput{
		TableName: aws.String(t.name()),
		IndexName: aws.String("byVersion"),
		ExpressionAttributeNames: map[string]*string{
			"#VERSION": aws.String("version"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":version": &dynamodb.AttributeValue{
				S: aws.String(version),
			},
		},
		KeyConditionExpression: aws.String("#VERSION = :version"),
	}

	queryOutput, err := t.DynamoDBAPI.QueryWithContext(ctx, queryInput)
	if err != nil {
		return nil, err
	}
	if len(queryOutput.Items) == 0 {
		return nil, db.ErrDeploymentByVersionNotFound{Version: version}
	}

	var deployment models.Deployment
	if err := decodeDeployment(queryOutput.Items[0], &deployment); err != nil {
		return nil, err
	}
	return &deployment, nil
}
func (t DeploymentTable) scanDeploymentsByVersion(ctx context.Context, input db.ScanDeploymentsByVersionInput, fn func(m *models.Deployment, lastDeployment bool) bool) error {
	scanInput := &dynamodb.ScanInput{
		TableName:      aws.String(t.name()),
		ConsistentRead: aws.Bool(!input.DisableConsistentRead),
		Limit:          input.Limit,
		IndexName:      aws.String("byVersion"),
	}
	if input.StartingAfter != nil {
		exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter)
		if err != nil {
			return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error())
		}
		// must provide the fields constituting the index and the primary key
		// https://stackoverflow.com/questions/40988397/dynamodb-pagination-with-withexclusivestartkey-on-a-global-secondary-index
		scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{
			"envApp": &dynamodb.AttributeValue{
				S: aws.String(fmt.Sprintf("%s--%s", input.StartingAfter.Environment, input.StartingAfter.Application)),
			},
			"version": exclusiveStartKey["version"],
		}
	}
	totalRecordsProcessed := int64(0)
	var innerErr error
	err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool {
		items, err := decodeDeployments(out.Items)
		if err != nil {
			innerErr = fmt.Errorf("error decoding %s", err.Error())
			return false
		}
		for i := range items {
			if input.Limiter != nil {
				if err := input.Limiter.Wait(ctx); err != nil {
					innerErr = err
					return false
				}
			}
			isLastModel := lastPage && i == len(items)-1
			if shouldContinue := fn(&items[i], isLastModel); !shouldContinue {
				return false
			}
			totalRecordsProcessed++
			// if the Limit of records have been passed to fn, don't pass anymore records.
			if input.Limit != nil && totalRecordsProcessed == *input.Limit {
				return false
			}
		}
		return true
	})
	if innerErr != nil {
		return innerErr
	}
	return err
}

// encodeDeployment encodes a Deployment as a DynamoDB map of attribute values.
func encodeDeployment(m models.Deployment) (map[string]*dynamodb.AttributeValue, error) {
	val, err := dynamodbattribute.MarshalMap(ddbDeployment{
		Deployment: m,
	})
	if err != nil {
		return nil, err
	}
	// make sure composite attributes don't contain separator characters
	if strings.Contains(m.Application, "--") {
		return nil, fmt.Errorf("application cannot contain '--': %s", m.Application)
	}
	if strings.Contains(m.Environment, "--") {
		return nil, fmt.Errorf("environment cannot contain '--': %s", m.Environment)
	}
	// add in composite attributes
	primaryKey, err := dynamodbattribute.MarshalMap(ddbDeploymentPrimaryKey{
		EnvApp:  fmt.Sprintf("%s--%s", m.Environment, m.Application),
		Version: m.Version,
	})
	if err != nil {
		return nil, err
	}
	for k, v := range primaryKey {
		val[k] = v
	}
	byDate, err := dynamodbattribute.MarshalMap(ddbDeploymentGSIByDate{
		EnvApp: fmt.Sprintf("%s--%s", m.Environment, m.Application),
		Date:   m.Date,
	})
	if err != nil {
		return nil, err
	}
	for k, v := range byDate {
		val[k] = v
	}
	return val, err
}

// decodeDeployment translates a Deployment stored in DynamoDB to a Deployment struct.
func decodeDeployment(m map[string]*dynamodb.AttributeValue, out *models.Deployment) error {
	var ddbDeployment ddbDeployment
	if err := dynamodbattribute.UnmarshalMap(m, &ddbDeployment); err != nil {
		return err
	}
	*out = ddbDeployment.Deployment
	return nil
}

// decodeDeployments translates a list of Deployments stored in DynamoDB to a slice of Deployment structs.
func decodeDeployments(ms []map[string]*dynamodb.AttributeValue) ([]models.Deployment, error) {
	deployments := make([]models.Deployment, len(ms))
	for i, m := range ms {
		var deployment models.Deployment
		if err := decodeDeployment(m, &deployment); err != nil {
			return nil, err
		}
		deployments[i] = deployment
	}
	return deployments, nil
}


text:
layout: page
title: Mason Palace Systems Show
date: 2016-05-24
author: William Rodgers
tags: weekly links, java
status: published
summary: Curabitur eget tellus dapibus, posuere libero.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/08/2019
  endDate: 08/13/2019
  ctyhocn: TXLBCHX
  groupCode: MPSS
published: true
---
Morbi vel erat ac diam venenatis efficitur. Integer pellentesque placerat tortor at sagittis. Donec malesuada pretium justo vitae eleifend. Ut consectetur ullamcorper nisl vitae tincidunt. Suspendisse at viverra nulla, in sollicitudin mi. Proin pharetra posuere lorem, tempor maximus mi ultricies non. Mauris eget ullamcorper lectus. In hac habitasse platea dictumst. Curabitur euismod laoreet lacus non imperdiet. Nam rhoncus maximus felis.
Quisque tempor, odio vestibulum rutrum pellentesque, erat nibh tristique nibh, sit amet volutpat odio magna sed magna. Etiam lacinia ligula eget maximus elementum. Vestibulum dui neque, eleifend ut nisi a, tempus ullamcorper mi. Quisque fringilla nulla in lacus imperdiet, sit amet laoreet mi interdum. Etiam auctor enim dignissim cursus suscipit. Morbi laoreet, mi nec malesuada laoreet, urna ante sodales metus, ut efficitur dolor mi quis quam. Nam interdum vestibulum risus, eget pellentesque urna venenatis et. Curabitur eu sollicitudin sem. Mauris et rhoncus ante, a bibendum sem. Integer vitae auctor felis. Ut velit lectus, varius at pretium vel, facilisis non massa.

1 Phasellus tristique lectus et lectus porttitor gravida
1 Etiam semper eros ultrices orci suscipit commodo
1 Phasellus ut est ultrices, laoreet dui vel, feugiat risus.

Ut varius nisl ut orci laoreet, quis ultricies lacus gravida. Aliquam quis tempor quam, ut eleifend dui. Donec fringilla augue sed semper tempus. Morbi venenatis eu turpis eget auctor. Sed quam ligula, commodo in ante ac, fermentum vestibulum mauris. Quisque tellus erat, pulvinar in molestie eu, ullamcorper id dui. Nullam sollicitudin massa non nisi consectetur, ac pharetra est consequat. Aenean tincidunt volutpat felis a scelerisque.
Sed mi elit, malesuada eget mollis quis, pulvinar quis ante. In at tincidunt ante. Vestibulum consectetur odio vitae aliquam blandit. Aenean interdum turpis ut erat finibus sodales. Ut pharetra urna nec vehicula sollicitudin. Donec fermentum felis in neque laoreet, vitae tempor quam commodo. In hac habitasse platea dictumst.


text:
        <title>AngularJs - Date/Timepicker</title>

        <meta name="viewport" content="initial-scale=1, maximum-scale=1">

        <link rel="stylesheet" href="./source/css/style.css">

                <input type="text" datetimepicker datetimepicker-options="vm.properties" ng-model="vm.datum" />

                <input type="text">

                <input type="text">

                <input type="text" datetimepicker datetimepicker-options="vm.properties" ng-model="vm.datum2" />


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace NavigationControls
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class HubPage : Page
    {
        public HubPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
        }

        public void OnHeaderClick(object sender, HubSectionHeaderClickEventArgs e)
        {
            Info = e.Section.Tag as string;
        }

        public string Info
        {
            get { return (string)GetValue(InfoProperty); }
            set { SetValue(InfoProperty, value); }
        }

        public static readonly DependencyProperty InfoProperty =
            DependencyProperty.Register("Info", typeof(string), typeof(HubPage), new PropertyMetadata(string.Empty));

    }
}


text:
namespace CircuitSimulator
{
    public enum Greatness
    {
        Volt,
        Resistance,
        Current,
        Frequency,
        Time
    }
}


text:
import pygame
import sys
from pygame.locals import *

from LeeColor import create_path

#This file gives a much more indepth look at the A* algorithm, allowing
#the user to see exacly how a search is made, and how paths are traced
#When a path is created:
#Blue squares: nodes on the open list
#Red squares: nodes on the closed list
#Grey/black squares: shows the best path

#each square has an arrow pointing to its parent square

class Source(object):
    def __init__(self, loc, image, screen):
        self.rloc = (loc[0]*10, loc[1]*10)#'real' location
        self.loc, self.path = loc, []
        self.image = pygame.image.load(image)
        self.goal = ()
        self.theta = self.changex = self.changey = 0
        self.wait = 0
        self.screen = screen

    def set_path(self, grid1,grid2, end,IsBlack):
        "sets a path for the source to follow"
        self.goal = end # reset the goal

        #create a path using A*
        #draw stuff as well in these functions
        self.path = create_path(self.loc,end,grid1,grid2,self.screen,False,False)

        grid1[self.rloc[0]/10][self.rloc[1]/10] = False   # make the source as a wall for next path
        selfPathLength = len(self.path)
        for i in range(0,selfPathLength):#To delete the already formed line to avoid from further calculation
            grid1[self.path[i][0]][self.path[i][1]] = False

        if selfPathLength == 0:
            self.path = create_path(self.loc,end,grid1,grid2,self.screen,True,True)
            grid2[self.rloc[0]/10][self.rloc[1]/10] = False   # make the source as a wall for next path
            selfPathLength = len(self.path)
            for i in range(0,selfPathLength):#To delete the already formed line to avoid from further calculation
                grid2[self.path[i][0]][self.path[i][1]] = False

        pygame.display.flip()#update the screen

    def draw_source(self):
        #blit the dude on the screen, based on his 'real' coordinates
        self.screen.blit(self.image, (self.rloc[0], self.rloc[1]))

def creategrid(dim):
    #This function makes the screen to a 2D array of small squares
    x,y = dim[0]/10-2, dim[1]/10-2
    grid = []
    for gx in xrange(x+2):
        row = []
        for gy in xrange(y+2):
            if gx == 0 or gy == 0 or gx == x+1 or gy == y+1:
                row.append(False)
            else: row.append(True)
        grid.append(row)
    return grid

def update(screen, grid, source = None):
    #'erase' the source, draw him, then update the screen
    if source != None:
        pygame.draw.rect(screen, (100,255,100),(source.rloc[0],source.rloc[1],10,10))
        source.draw_source()
    #pygame.display.update((source.rloc[0]-20),(source.rloc[1]-20),40, 40)
    for r in xrange(1,100):
        pygame.draw.line(screen,(0,0,0),(r*10,0),(r*10,1000),1)
        pygame.draw.line(screen,(0,0,0),(0,r*10),(1000,r*10),1)
    pygame.display.update()

def draw_all(screen, grid, source = None):
    "Draws the entire screen"
    for x in xrange(len(grid)):
        for y in xrange(len(grid[x])):
            #draw either walls or grass
            if grid[x][y] == True:
                pygame.draw.rect(screen, (100,255,100), (x*10, y * 10, 10, 10))
            elif grid[x][y] == False:
                pygame.draw.rect(screen, (150,100,50) , (x*10, y * 10, 10, 10))

    for r in xrange(1,100):
        pygame.draw.line(screen,(0,0,0),(r*10,0),(r*10,1000),1)
        pygame.draw.line(screen,(0,0,0),(0,r*10),(1000,r*10),1)
    #draw the source and update the entire screen
    if source != None:
        source.draw_source()
    pygame.display.flip()

def change(screen, grid, deleting, mx, my):
    "either draws or erases a wall"
    grid[mx][my] = deleting
    if deleting: pygame.draw.rect(screen,(100,255,100),(mx*10, my*10,10,10))
    else       : pygame.draw.rect(screen,(150,100,50) ,(mx*10, my*10,10,10))
    pygame.display.update(mx*10, my * 10, 10, 10)
    return grid

def main(dim):
    #initialize pygame, the display caption, and the screen
    pygame.init(); pygame.display.set_caption("A* Maze")
    grid1 = creategrid(dim)
    grid2 = creategrid(dim) # second layer.
    screen = pygame.display.set_mode((dim[0], dim[1]))#initialize the screen for the display
    source = None #Initialize the source object
    #we aren't drawing or deleting. This is for drawing/deleting the walls
    drawing = deleting = False
    #draw everything on the screen
    draw_all(screen,grid1)
    startingNode = True
    IsBlack = True
    clock = pygame.time.Clock()
    while True:#main loop
        clock.tick(1000)#limits the speed of the operation

        events = pygame.event.get()#get the inputs
        for e in events: #processes key/mouse inputs
            #getting the mouse position
            mousex = (pygame.mouse.get_pos()[0])/10
            mousey = (pygame.mouse.get_pos()[1])/10

            if e.type == MOUSEBUTTONDOWN:
                #left mouse button pressed
                #An active node at at which a left click occured will be considered as a source/target node.
                if pygame.mouse.get_pressed()[0] == 1 and startingNode == True and grid1[mousex][mousey]!= False:
                    startingNode = False
                    source = Source((mousex,mousey),"source.bmp", screen)
                    update(screen, grid1,source)
                    continue
                #right mouse button pressed
                #right click will draw a wall or delete
                elif pygame.mouse.get_pressed()[2] == 1:
                    #if we start by seleting a wall, then we are deleting
                    #else we start drawing
                    if grid1[mousex][mousey] == True:
                        drawing = True
                    else:
                        deleting = True

                #set a new path for the source
                elif source != None and pygame.mouse.get_pressed()[0] == 1:
                    if grid1[mousex][mousey]!= False and (mousex,mousey)!=source.loc:
                        update(screen, grid1,source)#redraw everythin
                        IsBlack = not(IsBlack)
                        source.set_path(grid1,grid2,(mousex,mousey),IsBlack)
                        startingNode = True
            #stop deleting/drawing walls
            elif e.type == MOUSEBUTTONUP:drawing = deleting = False

            elif e.type == KEYDOWN:

                #escape to quit
                if e.key == K_ESCAPE: pygame.quit();  sys.exit()

        if source != None:
            update(screen, grid1, source)

        if   drawing  == True: grid1 = change(screen, grid1,False, mousex,mousey)
        elif deleting == True: grid1 = change(screen, grid1, True, mousex,mousey)

if __name__ == "__main__": main((1000,700))


text:
package pl.tomaszdziurko.jvm_bloggers.mailing;

import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.antlr.stringtemplate.StringTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;
import pl.tomaszdziurko.jvm_bloggers.people.domain.Person;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BlogSummaryMailGenerator {

    private Resource blogsSummaryTemplate;

    @Autowired
    public BlogSummaryMailGenerator(@Value("classpath:mail_templates/blog_summary.st") Resource blogsSummaryTemplate) {
        this.blogsSummaryTemplate = blogsSummaryTemplate;
    }

    public String generateSummaryMail(List<BlogPost> posts, List<Person> blogsAddedSinceLastNewsletter, int numberOfDaysBackInThePast) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(blogsSummaryTemplate.getInputStream(), "UTF-8"));
            String templateContent =  Joiner.on("\n").join(bufferedReader.lines().collect(Collectors.toList()));
            StringTemplate template = new StringTemplate(templateContent);
            template.setAttribute("days", numberOfDaysBackInThePast);
            template.setAttribute("newPosts", posts.stream().map(BlogPostForMailItem::new).collect(Collectors.toList()));
            template.setAttribute("newBlogs", blogsAddedSinceLastNewsletter);
            return template.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}