text:
import win32security
import win32api
import ntsecuritycon
import win32net
import ctypes
import uuid

from firmware_variables import *
from firmware_variables.load_option  import LoadOptionAttributes, LoadOption
from firmware_variables.device_path import DevicePathList, DevicePath, DevicePathType, MediaDevicePathSubtype, EndOfHardwareDevicePathSubtype
from firmware_variables.utils import verify_uefi_firmware, string_to_utf16_bytes, utf16_string_from_bytes
import struct

import sys
import os
import traceback
import time
import logging

import util

from color import p

from mgmt_ProcessManagement import ProcessManagement
from mgmt_RegistrySettings import RegistrySettings

class FolderPermissions:
    # Class to deal with folder permissions

    GROUP_EVERYONE = None
    GROUP_ADMINISTRATORS = None
    CURRENT_USER = None
    SYSTEM_USER = None

    @staticmethod
    def init_win_user_accounts():
        # Load account information for groups/users
        domain = None
        acct_type = None

        if FolderPermissions.GROUP_EVERYONE is None:
            EVERYONE, domain, acct_type = win32security.LookupAccountName("", "Everyone")
            FolderPermissions.GROUP_EVERYONE = EVERYONE

        if FolderPermissions.GROUP_ADMINISTRATORS is None:
            ADMINISTRATORS, domain, acct_type = win32security.LookupAccountName("", "Administrators")
            FolderPermissions.GROUP_ADMINISTRATORS = ADMINISTRATORS

        if FolderPermissions.CURRENT_USER is None:
            CURRENT_USER, domain, acct_type = win32security.LookupAccountName("", win32api.GetUserName())

            if CURRENT_USER is None:
                try:
                    CURRENT_USER, domain, acct_type = win32security.LookupAccountName("", "huskers")
                except:
                    CURRENT_USER = None
                if CURRENT_USER is None:
                    try:
                        CURRENT_USER, domain, acct_type = win32security.LookupAccountName("", "ray")
                    except:
                        CURRENT_USER = None
            FolderPermissions.CURRENT_USER = CURRENT_USER

        if FolderPermissions.SYSTEM_USER is None:
            SYSTEM_USER, domain, acct_type = win32security.LookupAccountName("", "System")
            FolderPermissions.SYSTEM_USER = SYSTEM_USER

        # Pretend to use these so pylint shuts up
        if domain is None or acct_type is None:
            pass

    @staticmethod
    def show_cacls(filename):
        p("\n\n")
        for line in os.popen("cacls %s" % filename).read().splitlines():
            p(line)

    @staticmethod
    def set_ope_folder_permissions(folder_path, everyone_rights="r", walk_files=True):
        # everyone_rights: r - readonly, n - none, rw - readwrite, f - full, c - create/append
        # a - append (for files?)

        # EVERYONE - Figure out proper perms for everyone group
        everyone_perms = ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE
        if everyone_rights == "r":
            everyone_perms = ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE
        if everyone_rights == "n":
            everyone_perms = 0
        if everyone_rights == "rw":
            everyone_perms = ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE | ntsecuritycon.FILE_GENERIC_WRITE
        if everyone_rights == "f":
            everyone_perms = ntsecuritycon.FILE_ALL_ACCESS
        if everyone_rights == "c":
            everyone_perms = ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE
        if everyone_rights == "a":
            everyone_perms = ntsecuritycon.FILE_APPEND_DATA | ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE

        # Make sure our global accounts are available
        FolderPermissions.init_win_user_accounts()

        # All folders get admins/system_user/current_user (logged in admin) full rights
        # and limited rights for the everyone group

        # Setup new DACL for the folder
        # Set inheritance flags
        flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
        sd = win32security.GetFileSecurity(folder_path, win32security.DACL_SECURITY_INFORMATION)
        # Create the blank DACL and add our ACE's
        dacl = win32security.ACL()
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.GROUP_ADMINISTRATORS)
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.SYSTEM_USER)
        # Make sure current user (admin running this) has rights too
        if not FolderPermissions.CURRENT_USER is None:
            dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.CURRENT_USER)

        if everyone_perms != 0:
            dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags,
                                   everyone_perms,
                                   FolderPermissions.GROUP_EVERYONE)
        # Set our ACL
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(folder_path, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

        # Possible to set whole tree? - Doesn't seem to work, use file walk instead
        # win32security.TreeSetNamedSecurityInfo(folder, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, sd, None)

        # Walk sub folders
        if walk_files is True:
            for root, dirs, files in os.walk(folder_path, topdown=False):
                for f in files:
                    try:
                        win32security.SetFileSecurity(os.path.join(root, f), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
                    except:
                        logging.info("Error setting file permissions " + os.path.join(root, f))
                for d in dirs:
                    try:
                        win32security.SetFileSecurity(os.path.join(root, d), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
                    except:
                        logging.info("Error setting folder permissions " + os.path.join(root, d))

        return

    @staticmethod
    def get_acl_rights_for_user(folder_path, username):
        # Look at the ACL, see if this user is allowed to access this folder
        ret = []

        # Make sure our global accounts are available
        FolderPermissions.init_win_user_accounts()

        OWNER = d = atime = None
        try:
            OWNER, d, atype = win32security.LookupAccountName("", username)
        except:
            p("is_user_in_acl - Unable to find user: " + str(username))
            return None

        sd = win32security.GetFileSecurity(
            folder_path,
            win32security.DACL_SECURITY_INFORMATION |
            win32security.OWNER_SECURITY_INFORMATION |
            win32security.GROUP_SECURITY_INFORMATION |
            win32security.SACL_SECURITY_INFORMATION
            )
        o, d, atime = win32security.LookupAccountSid(None, sd.GetSecurityDescriptorOwner())
        if o == username:
            ret.append("o")

        dacl = sd.GetSecurityDescriptorDacl()
        mask = dacl.GetEffectiveRightsFromAcl(
            {
                'TrusteeForm': win32security.TRUSTEE_IS_NAME,
                'TrusteeType': win32security.TRUSTEE_IS_USER,
                'Identifier': username
            }
        )

        if bool(mask & 0x00000001):
            ret.append('r') # read
        if bool(mask & 0x00000002):
            ret.append('w') # write
        if bool(mask & 0x00000004):
            ret.append('a') # append
        if bool(mask & 0x00000008):
            ret.append('rea') # read ea
        if bool(mask & 0x00000010):
            ret.append('wea')  # write ea
        if bool(mask & 0x00000020):
            ret.append('x')   # execute
        if bool(mask & 0x00000040):
            ret.append('dc') # delete children
        if bool(mask & 0x00000080):
            ret.append("ra")  # read attributes
        if bool(mask & 0x00000100):
            ret.append("wa")  # write attributes
        if bool(mask & 0x00010000):
            ret.append('d')  # delete
        if bool(mask & 0x00020000):
            ret.append('rc')  # Read Control
        if bool(mask & 0x00040000):
            ret.append('wdac')  # write dac
        if bool(mask & 0x00080000):
            ret.append('wo')    # write owner
        if bool(mask & 0x00100000):
            ret.append('s') # syncronise

        return ret

    @staticmethod
    def set_home_folder_permissions(folder_path, owner_user, walk_files=True):
        if owner_user is None or owner_user == "":
            p("Invalid Owner, can't set home folder permissions: " + str(folder_path))
            return False

        # owner_rights: r - readonly, n - none, rw - readwrite, f - full, c - create/append
        # a - append (for files?)

        #owner_perms = ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE | ntsecuritycon.FILE_GENERIC_WRITE
        owner_perms = ntsecuritycon.FILE_ALL_ACCESS

        # Make sure our global accounts are available
        FolderPermissions.init_win_user_accounts()

        OWNER = d = atime = None
        try:
            OWNER, d, atype = win32security.LookupAccountName("", owner_user)
        except:
            p("Unable to find user: " + str(owner_user))
            return False

        # Setup new DACL for the folder
        # Set inheritance flags
        flags = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
        sd = win32security.GetFileSecurity(folder_path, win32security.DACL_SECURITY_INFORMATION)
        # Create the blank DACL and add our ACE's
        dacl = win32security.ACL()
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.GROUP_ADMINISTRATORS)
        dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.SYSTEM_USER)
        # Make sure current user (admin running this) has rights too
        if not FolderPermissions.CURRENT_USER is None:
            dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags, ntsecuritycon.FILE_ALL_ACCESS, FolderPermissions.CURRENT_USER)

        if owner_perms != 0:
            dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, flags,
                                   owner_perms,
                                   OWNER)
        # Set our ACL
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(folder_path, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)

        # Possible to set whole tree? - Doesn't seem to work, use file walk instead
        # win32security.TreeSetNamedSecurityInfo(folder, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, sd, None)

        # Walk sub folders
        if walk_files is True:
            for root, dirs, files in os.walk(folder_path, topdown=False):
                for f in files:
                    try:
                        win32security.SetFileSecurity(os.path.join(root, f), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
                    except:
                        logging.info("Error setting file permissions " + os.path.join(root, f))
                for d in dirs:
                    try:
                        win32security.SetFileSecurity(os.path.join(root, d), win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, sd)
                    except:
                        logging.info("Error setting folder permissions " + os.path.join(root, d))

        return True

    @staticmethod
    def is_time_to_set_default_ope_folder_permissions():
        # How long has it been since we synced our time?
        last_time_sync = RegistrySettings.get_reg_value(value_name="last_apply_ope_folder_permissions", default=0)
        curr_time = time.time()

        set_default_permissions_timer = RegistrySettings.get_reg_value(value_name="apply_ope_folder_permissions_timer", default=3600*3)

        # Only sync every ?? minutes
        if curr_time - last_time_sync > set_default_permissions_timer:
            return True

        return False

    @staticmethod
    def set_default_ope_folder_permissions(force=False):

        # Command that is run to start this function
        only_for = "set_default_ope_folder_permissions"
        param_force = util.pop_force_flag(only_for=only_for)
        if force is False:
            force = param_force

        if force is not True and not FolderPermissions.is_time_to_set_default_ope_folder_permissions():
            p("}}gnNot time to set ope folder permissions yet, skipping.}}xx", log_level=4)
            return True

        # Set permissions on OPE folder so inmates can't change things
        p("}}gnTrying to set OPE Folder Permissions...}}xx", log_level=3)

        RegistrySettings.set_reg_value(value_name="last_apply_ope_folder_permissions", value=time.time(), value_type="REG_DWORD")

        # Load up the system goups/users
        FolderPermissions.init_win_user_accounts()

        # Make sure folders exits
        if not os.path.isdir(util.ROOT_FOLDER):
            os.makedirs(util.ROOT_FOLDER, exist_ok=True)
        if not os.path.isdir(util.TMP_FOLDER):
            os.makedirs(util.TMP_FOLDER, exist_ok=True)
        if not os.path.isdir(util.LOCK_SCREEN_WIDGET_FOLDER):
            os.makedirs(util.LOCK_SCREEN_WIDGET_FOLDER, exist_ok=True)
        if not os.path.isdir(util.LOG_FOLDER):
            os.makedirs(util.LOG_FOLDER, exist_ok=True)
        if not os.path.isdir(util.SCREEN_SHOTS_FOLDER):
            os.makedirs(util.SCREEN_SHOTS_FOLDER, exist_ok=True)
        if not os.path.isdir(util.BINARIES_FOLDER):
            os.makedirs(util.BINARIES_FOLDER, exist_ok=True)
        if not os.path.isdir(util.GIT_FOLDER):
            os.makedirs(util.GIT_FOLDER, exist_ok=True)
        if not os.path.isdir(util.STUDENT_DATA_FOLDER):
            os.makedirs(util.STUDENT_DATA_FOLDER, exist_ok=True)

        # ---- ope-sshot.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "ope-sshot.log")):
            f = open(os.path.join(util.LOG_FOLDER, "ope-sshot.log"), "w")
            f.close()

        # ---- ope-mgmt.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "ope-mgmt.log")):
            f = open(os.path.join(util.LOG_FOLDER, "ope-mgmt.log"), "w")
            f.close()

         # ---- ope-lockscreen.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "ope-lockscreen.log")):
            f = open(os.path.join(util.LOG_FOLDER, "ope-lockscreen.log"), "w")
            f.close()

        # ---- ope-state.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "ope-state.log")):
            f = open(os.path.join(util.LOG_FOLDER, "ope-state.log"), "w")
            f.close()

        # ---- lms_app_debug.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "lms_app_debug.log")):
            f = open(os.path.join(util.LOG_FOLDER, "lms_app_debug.log"), "w")
            f.close()

        # ---- upgrade.log ----
        # Make sure the log file exists so we can set permissions on it later
        if not os.path.isfile(os.path.join(util.LOG_FOLDER, "upgrade.log")):
            f = open(os.path.join(util.LOG_FOLDER, "upgrade.log"), "w")
            f.close()

        # App folder permissions are set based on this list
        # r - read/execute, n - none, c - create/append, a - appendonly, f - full
        app_folders = {
            util.ROOT_FOLDER: "r",
            util.BINARIES_FOLDER: "r",
            util.STUDENT_DATA_FOLDER: "r",
            util.TMP_FOLDER: "r",
            util.GIT_FOLDER: "r",  # TODO - change to n when we can avoid security prompts
            util.LOG_FOLDER: "c",
            os.path.join(util.LOG_FOLDER, "ope-sshot.log"): "a",
            os.path.join(util.LOG_FOLDER, "ope-mgmt.log"): "a",
            os.path.join(util.LOG_FOLDER, "ope-lockscreen.log"): "a",
            os.path.join(util.LOG_FOLDER, "ope-state.log"): "r",
            os.path.join(util.LOG_FOLDER, "lms_app_debug.log"): "a",
            os.path.join(util.LOG_FOLDER, "upgrade.log"): "r",
            util.SCREEN_SHOTS_FOLDER: "c",
            util.LOCK_SCREEN_WIDGET_FOLDER: "r",

        }

        for f in app_folders.keys():
            everyone_rights = app_folders[f]
            p("}}gnSetting permissions on " + f + " (rights for everyone " + \
                everyone_rights + ")}}xx", log_level=5)
            FolderPermissions.set_ope_folder_permissions(f, everyone_rights=everyone_rights)

        return True

    @staticmethod
    def rebuild_bcd_data_wmi():
        GUID_WINDOWS_BOOTMGR = "{9dea862c-5cdd-4e70-acc1-f32b344d4795}"
        GUID_WINDOWS_FWBOOTMGR = "{a5a30fa2-3d06-4e9f-b5f4-a01df9d1fcba}"
        GUID_DEBUGGER_SETTINGS_GROUP = "{4636856e-540f-4170-a130-a84776f4c654}"
        GUID_CURRENT_BOOT_ENTRY = "{fa926493-6f1c-4193-a414-58f0b2456d1e}"      # {current} or
        GUID_DEFAULT_BOOT_ENTRY = ""                                            # {default}??
        GUID_WINDOWS_LEGACY_NTLDR = "{466f5a88-0af2-4f76-9038-095b170dc21c}"
        GUID_WINDOWS_MEMORY_DIAG = "{b2721d73-1db4-4c62-bf78-c548a880142d}"     # {memdiag}
        GUID_WINDOWS_RESUME = "{147aa509-0358-4473-b83b-d950dda00615}"

        GUID_WINDOWS_BADMEMORY = "{5189b25c-5558-4bf2-bca4-289b11bd29e2}"       # {badmemory}
        GUID_BOOT_LOADER_SETTINGS = "{6efb52bf-1766-41db-a6b3-0ee5eff72bd7}"    # {bootloadersettings}
        GUID_EMS_SETTINGS = "{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}"            # {emssettings}
        GUID_GLOBAL_SETTINGS = "{7ea2e1ac-2e61-4728-aaa3-896d9d0a9f0e}"         # {globalsettings}
        GUID_RESUME_LOADER_SETTINGS = "{1afa9c49-16ab-4a5c-901b-212802da9460}"  # {resumeloadersettings}

        BCDE_DEVICE_TYPE_BOOT_DEVICE    =0x00000001
        BCDE_DEVICE_TYPE_PARTITION      =0x00000002
        BCDE_DEVICE_TYPE_FILE           =0x00000003
        BCDE_DEVICE_TYPE_RAMDISK        =0x00000004
        BCDE_DEVICE_TYPE_UNKNOWN        =0x00000005

        BCD_COPY_CREATE_NEW_OBJECT_IDENTIFIER = 0x00000001

        BCDE_VISTA_OS_ENTRY = 0x10200003
        BCDE_LEGACY_OS_ENTRY = 0x10300006

        BCDE_LIBRARY_TYPE_APPLICATIONPATH = \
            MAKE_BCDE_DATA_TYPE(BCDE_CLASS.LIBRARY, BCDE_FORMAT.STRING, 0x000002)
        # Get the current boot loader GUID
        w = wmi.WMI(computer=".", impersonation_level="Impersonate", privileges=("Backup", "Restore"), namespace="WMI", suffix="BcdStore")
        success, store = w.OpenStore("")
        if success is True:
            # Have to convert to wmi object
            store = wmi._wmi_object(store)

        # Get the bootmgr (yes - obj first)
        b_mgr, success = store.OpenObject("{9dea862c-5cdd-4e70-acc1-f32b344d4795}")
        if success is True:
            # Have to convert to wmi object
            b_mgr = wmi._wmi_object(b_mgr)

        # Get all boot loader objects
        obj_list, success = store.EnumerateObjects(0)
        if success is True:
            obj_list = wmi._wmi_object(obj_list)

        w.close()

        # Rebuild BCD Database
        cmd = "%SystemRoot%\\System32\\bcdboot c:\\windows /m " + boot_loader_guid + " /f ALL" #UEFI"
        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=3, require_return_code=0)
        #p(str(returncode) + " - " + output)
        if returncode == -2:
            # Error running command?
            p("}}rbError - get boot options!}}xx\n" + output)
            return False

        return True

    @staticmethod
    def rebuild_bcd_data_cmd_line():

        # Rebuild BCD Database
        cmd = "%SystemRoot%\\System32\\bcdboot c:\\windows"
        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=3, require_return_code=0)
        #p(str(returncode) + " - " + output)
        if returncode == -2:
            # Error running command?
            p("}}rbError - bcdboot failed!}}xx\n" + output)
            return False

        return True

    @staticmethod
    def lock_boot_settings():
        ret = True

        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping lock_boot_settings policy}}xx")
            return True

        # Make sure bootim.exe is disabled (the blue screen menu) This will block recovery options
        #New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\bootim.exe"
        #Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\bootim.exe" -Name "Debugger" -Type "String" -Value "taskill /F /IM bootim.exe" -Force
        RegistrySettings.set_reg_value(
            root="HKLM",
            app="Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options",
            subkey="bootim.exe",
            value_name="Debugger",
            value="taskill /F /IM bootim.exe",
            value_type="REG_SZ")

        # Rewrite UEFI values
        FolderPermissions.update_uefi_boot_order()

        FolderPermissions.rebuild_bcd_data_cmd_line()

        # Get the default from the boot manager
        cmd = "%SystemRoot%\\System32\\bcdedit.exe"
        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=3, require_return_code=0)
        #p(str(returncode) + " - " + output)
        if returncode == -2:
            # Error running command?
            p("}}rbError - get boot options!}}xx\n" + output)
            return False

        # Is the boot manager listed as {current} or {default}
        boot_identifier = "{current}"
        if "{default}" in output:
            boot_identifier = "{default}"

        p("}}gnBoot ID: " + boot_identifier + "}}xx", log_level=5)

        # https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/%SystemRoot%\\system32\\bcdedit.exe--set

        # Lock down boot settings
        # (cmd, required_return_code)
        cmds = [
            ("%SystemRoot%\\system32\\bcdedit.exe /deletevalue \"{current}\" recoverysequence ", None),

            ("%SystemRoot%\\System32\\bcdedit.exe /timeout 0", 0),
            # Set in uefi area
            #("%SystemRoot%\\System32\\bcdedit.exe /set \"{fwbootmgr}\" timeout 0", None),

            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{bootmgr}\" displaybootmenu no", 0),
            # Use standard policy - no F8 key
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootmenupolicy Standard", 0),
            # Try to boot normally every time - helps to not show recovery options
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootstatuspolicy ignoreallfailures", 0),
            # Disable recovery
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" recoveryenabled off", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{globalsettings}\" recoveryenabled off", 0),
            # Disable Advanced Options
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" advancedoptions off", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{globalsettings}\" advancedoptions off", 0),

            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootems off", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" optionsedit off", 0),

            # disable Win Recovery Environment (WinRE)
            ("%SystemRoot%\\system32\\reagentc /disable", None),

            ("%SystemRoot%\\system32\\bcdedit.exe /deletevalue \"" + boot_identifier + "\" safeboot ", None),

            # Set boot UEFI boot order so hard disk is first
            #("%SystemRoot%\\system32\\bcdedit.exe /set \"{bootmgr}\" displayorder \"" + boot_identifier + "\"", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{bootmgr}\" displayorder \"" + boot_identifier + "\" /addfirst", 0),

            #("%SystemRoot%\\system32\\bcdedit.exe /set \"{fwbootmgr}\" displayorder \"{bootmgr}\"", None),
            #("%SystemRoot%\\system32\\bcdedit.exe /set \"{fwbootmgr}\" displayorder \"{bootmgr}\" /addfirst", None),
            #("%SystemRoot%\\system32\\bcdedit.exe /set \"{fwbootmgr}\" displayorder \"{bootmgr}\"", None),
            #("%SystemRoot%\\system32\\bcdedit.exe /set \"{fwbootmgr}\" displayorder \"{bootmgr}\"", None),
            # TODO - boot setting still not taking in nvram?
            #("%SystemRoot%\\system32\\bcdboot.exe %windir%", 0),
            #("%SystemRoot%\\system32\\mountvol.exe  s: /s", None),
            #("%SystemRoot%\\system32\\bcdboot.exe %SystemRoot% /s s: /F UEFI", None),
            #("%SystemRoot%\\system32\\mountvol.exe  s: /D", None),
            #mountvol s: /S
            #bcdboot c:\windows /s s: /F UEFI
            #mountvol s: /D
        ]

        for tcmd in cmds:
            cmd = tcmd[0]
            require_return_code = tcmd[1]
            cmd = os.path.expandvars(cmd)
            returncode, output = ProcessManagement.run_cmd(cmd,
                attempts=3, require_return_code=require_return_code)
            fail_ok = ""
            if require_return_code is None:
                fail_ok = " (ok if this fails) "
            p(str(returncode) + " - " + fail_ok + output, log_level=4)
            if returncode == -2:
                # Error running command?
                p("}}rbError - set boot options!}}xx\n" + output)
                return False

        # Ensure that RE is disabled
        # Get the default from the boot manager
        cmd = "%SystemRoot%\\system32\\reagentc /info"
        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=3, require_return_code=0)
        p(str(returncode) + " - " + output, log_level=5)
        if returncode == -2:
            # Error running command?
            p("}}rbError - get reagentc /info!}}xx\n" + output)
            return False

        if "Disabled" not in output:
            p("}}rbERROR - Windows Recovery Environment NOT disabled!}}xx")
            return False
        else:
            p("}}gnWinRE Disabled!}}xx", log_level=3)

        # ALT INFO - shouldn't need these w current commands
        # rem Option to kill safemode w bluescreen/error
        # rem HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SafeBoot
        # rem rename "minimal" and "Network" to cause blue screens
        # rem OK IF THERE ARE FAILURES ON SECOND RUNS!
        # rem echo Modifying Registry to break safeboot
        # rem reg copy HKLM\System\CurrentControlSet\Control\SafeBoot\Minimal HKLM\System\CurrentControlSet\Control\SafeBoot\MinimalX /s /f
        # rem reg delete HKLM\System\CurrentControlSet\Control\SafeBoot\Minimal /f

        # rem reg copy HKLM\System\CurrentControlSet\Control\SafeBoot\Network HKLM\System\CurrentControlSet\Control\SafeBoot\NetworkX /s /f
        # rem reg delete HKLM\System\CurrentControlSet\Control\SafeBoot\Network /f

        # rem todo - return proper error
        # rem return 0 for now so we don't blow up credential process

        return ret

    @staticmethod
    def enable_uefi_pxe_boot():
        # Enable PXE boot option to image the server

        return True

    @staticmethod
    def disable_uefi_alt_boot():
        # Set boot options to disabled if they aren't our windows boot option
        return True

    @staticmethod
    def update_uefi_boot_partition():
        from mgmt_Computer import Computer
        # Find the current windows boot entry and make sure the GPT partition is correct
        with privileges():
            try:
                verify_uefi_firmware()
            except:
                p("}}gnNOT UEFI BIOS!}}xx", log_level=3)
                return True

            # Get the list of disks
            # https://stackoverflow.com/questions/56784915/python-wmi-can-we-really-say-that-c-is-always-the-boot-drive
            w = Computer.get_wmi_connection(namespace='root/Microsoft/Windows/Storage')
            drives = w.MSFT_Disk() #w.Win32_DiskDrive()

            part_info = None
            for drive in drives:
                # print(r)
                disk_number = drive.Number # r.Index
                # physical_path = r'\\.\PHYSICALDRIVE' + str(disk_number)  # r.DeviceID

                # Get partitions for this drive if it is the boot drive
                if drive.IsBoot == True:
                    partitions = drive.associators("MSFT_DiskToPartition")
                    for part in partitions:
                        if part.GptType == "{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}":
                            # Found EFI partition
                            sector_size = int(drive.PhysicalSectorSize)
                            part_starting_sector = int(int(part.Offset) / sector_size)
                            part_size = int(int(part.Size) / sector_size)
                            part_guid = part.Guid
                            part_number = part.PartitionNumber
                            part_info = (part, part_guid, part_number, part_starting_sector, part_size)
                            break

            if part_info is None:
                # Couldn't find EFI partition!
                p("}}gnUEFI - Couldn't find system EFI partition!}}xx", log_level=3)
                return False

            # Create the device path list for windows boot manager
            bootmgr_path_list = DevicePathList()
            bootmgr_path_list.paths = []  # Make sure we clear out any default stuff
            # Calculate path data we need
            #part_info = (part, part_guid, part_number, part_starting_sector, part_size)
            # Get in RFC4122 binary encoded format (first half in different endian mode?)
            packed_guid = uuid.UUID(part_info[1]).bytes_le
            WIN_HARD_DRIVE_MEDIA_PATH = struct.Struct("<LQQ16sBB").pack(
                part_info[2],             # Long - 4  bytes
                part_info[3],             # long long - 8 bytes
                part_info[4],             # long long - 8 bytes
                packed_guid,              # 16 bytes,
                0x02,                     # 1 byte - 0x01 for mbr, 0x02 for gpt
                0x02,                     # 1 byte - 0x00 none, 0x01 mbr, 0x02 gpt
            )

            WIN_DEVICE_PATH_DATA = string_to_utf16_bytes("\\EFI\\Microsoft\\Boot\\bootmgfw.efi")

            # Add the disk GUID entry
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.MEDIA_DEVICE_PATH, MediaDevicePathSubtype.HARD_DRIVE, WIN_HARD_DRIVE_MEDIA_PATH
                )
            )
            # Add the file path
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.MEDIA_DEVICE_PATH, MediaDevicePathSubtype.FILE_PATH, WIN_DEVICE_PATH_DATA
                )
            )
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.END_OF_HARDWARE_DEVICE_PATH, EndOfHardwareDevicePathSubtype.END_ENTIRE_DEVICE_PATH
            ))

            # Get the current boot item
            curr_boot_index, attr = get_variable("BootCurrent")
            # Convert from bytes to a integer value
            curr_boot_index = struct.unpack("<h", curr_boot_index)[0]

            # Adjust the current boot item to point to the proper partition
            try:
                boot_entry = get_parsed_boot_entry(curr_boot_index)

                #boot_entry.attributes = LoadOptionAttributes.LOAD_OPTION_ACTIVE
                boot_entry.device_path_list = bootmgr_path_list
                set_parsed_boot_entry(curr_boot_index, boot_entry)
            except Exception as ex:
                # Will get errors if we run out of entries. That is OK.
                if "environment option" not in str(ex):
                    p("}}rbError: }}xx" + str(ex))
                    #traceback.print_exc()
                pass

        return True

    @staticmethod
    def update_uefi_boot_order():
        from mgmt_Computer import Computer

        # NOTE - Likely need to rebuild BCD after this!

        # Elevate privileges for reading/writing uefi values
        with privileges():
            try:
                verify_uefi_firmware()
            except:
                p("}}gnNOT UEFI BIOS!}}xx", log_level=3)
                return True

            # Get the list of disks
            # https://stackoverflow.com/questions/56784915/python-wmi-can-we-really-say-that-c-is-always-the-boot-drive
            w = Computer.get_wmi_connection(namespace='root/Microsoft/Windows/Storage')
            drives = w.MSFT_Disk() #w.Win32_DiskDrive()

            part_info = None
            for drive in drives:
                # print(r)
                disk_number = drive.Number # r.Index
                # physical_path = r'\\.\PHYSICALDRIVE' + str(disk_number)  # r.DeviceID

                # Get partitions for this drive if it is the boot drive
                if drive.IsBoot == True:
                    partitions = drive.associators("MSFT_DiskToPartition")
                    for part in partitions:
                        if part.GptType == "{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}":
                            # Found EFI partition
                            sector_size = int(drive.PhysicalSectorSize)
                            part_starting_sector = int(int(part.Offset) / sector_size)
                            part_size = int(int(part.Size) / sector_size)
                            part_guid = part.Guid
                            part_number = part.PartitionNumber
                            part_info = (part, part_guid, part_number, part_starting_sector, part_size)
                            break

            if part_info is None:
                # Couldn't find EFI partition!
                p("}}gnUEFI - Couldn't find system EFI partition!}}xx", log_level=3)
                return False

            # Create the device path list for windows boot manager
            bootmgr_path_list = DevicePathList()
            bootmgr_path_list.paths = []  # Make sure we clear out any default stuff
            # Calculate path data we need
            #part_info = (part, part_guid, part_number, part_starting_sector, part_size)
            # Get in RFC4122 binary encoded format (first half in different endian mode?)
            packed_guid = uuid.UUID(part_info[1]).bytes_le
            WIN_HARD_DRIVE_MEDIA_PATH = struct.Struct("<LQQ16sBB").pack(
                part_info[2],             # Long - 4  bytes
                part_info[3],             # long long - 8 bytes
                part_info[4],             # long long - 8 bytes
                packed_guid,              # 16 bytes,
                0x02,                     # 1 byte - 0x01 for mbr, 0x02 for gpt
                0x02,                     # 1 byte - 0x00 none, 0x01 mbr, 0x02 gpt
            )

            WIN_DEVICE_PATH_DATA = string_to_utf16_bytes("\\EFI\\Microsoft\\Boot\\bootmgfw.efi")

            # Add the disk GUID entry
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.MEDIA_DEVICE_PATH, MediaDevicePathSubtype.HARD_DRIVE, WIN_HARD_DRIVE_MEDIA_PATH
                )
            )
            # Add the file path
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.MEDIA_DEVICE_PATH, MediaDevicePathSubtype.FILE_PATH, WIN_DEVICE_PATH_DATA
                )
            )
            bootmgr_path_list.paths.append(DevicePath(
                DevicePathType.END_OF_HARDWARE_DEVICE_PATH, EndOfHardwareDevicePathSubtype.END_ENTIRE_DEVICE_PATH
            ))

            # Get the current boot item
            curr_boot_index, attr = get_variable("BootCurrent")
            # Convert from bytes to a integer value
            curr_boot_index = struct.unpack("<h", curr_boot_index)[0]

            # Adjust the current boot item to point to the proper partition
            try:
                boot_entry = get_parsed_boot_entry(curr_boot_index)

                #boot_entry.attributes = LoadOptionAttributes.LOAD_OPTION_ACTIVE
                boot_entry.device_path_list = bootmgr_path_list
                set_parsed_boot_entry(curr_boot_index, boot_entry)
            except Exception as ex:
                # Will get errors if we run out of entries. That is OK.
                if "environment option" not in str(ex):
                    p("}}rbError: }}xx" + str(ex))
                    #traceback.print_exc()
                pass

            # Make sure we push this item to the top of the boot order
            # Get current boot order
            curr_boot_order = get_boot_order()
            new_boot_order = []
            new_boot_order.append(curr_boot_index)
            for item in curr_boot_order:
                if item != curr_boot_index:
                    new_boot_order.append(item)
            set_boot_order(new_boot_order)

            # Disable all other boot options by hiding them?
            for i in range(0, 24):
                try:
                    if i == curr_boot_index:
                        # Skip the current boot entry
                        pass
                    else:
                        boot_entry = get_parsed_boot_entry(i)
                        boot_entry.attributes = LoadOptionAttributes.LOAD_OPTION_HIDDEN | LoadOptionAttributes.LOAD_OPTION_ACTIVE
                        set_boot_entry(i, boot_entry)
                except Exception as ex:
                    # Will get errors if we run out of entries. That is OK.
                    if "environment option" not in str(ex):
                        p("}}rbError: }}xx" + str(ex))
                        #traceback.print_exc()
                    pass

            # Set timeout to 0
            set_variable("Timeout", 0)
            # Make sure we don't boot to something else later
            delete_variable("BootNext")

        return True

    @staticmethod
    def enable_pxe_boot():
        return False

    @staticmethod
    def unlock_boot_settings():
        ret = True

        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping unlock_boot_settings}}xx")
            return True

        # Unblock bootim (recovery screen stuff)
        RegistrySettings.remove_key("HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\bootim.exe")

        # Get the default from the boot manager
        cmd = "%SystemRoot%\\System32\\bcdedit.exe"
        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=3, require_return_code=0)
        #p(str(returncode) + " - " + output)
        if returncode == -2:
            # Error running command?
            p("}}rbError - get boot options!}}xx\n" + output)
            return False

        # Is the boot manager listed as {current} or {default}
        boot_identifier = "{current}"
        #if "{default}" in output:
        #    boot_identifier = "{default}"

        p("}}gnBoot ID: " + boot_identifier + "}}xx", log_level=4)

        cmds = [
            ("%SystemRoot%\\System32\\bcdedit.exe /timeout 30", 0),

            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{bootmgr}\" displaybootmenu yes", 0),
            # Use standard policy - no F8 key
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootmenupolicy Standard", 0),
            # Try to boot normally every time - helps to not show recovery options
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootstatuspolicy IgnoreShutdownFailures", 0),
            # Disable recovery
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" recoveryenabled on", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{globalsettings}\" recoveryenabled on", 0),
            # Disable Advanced Options
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" advancedoptions on", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"{globalsettings}\" advancedoptions on", 0),

            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" bootems on", 0),
            ("%SystemRoot%\\system32\\bcdedit.exe /set \"" + boot_identifier + "\" optionsedit on", 0),

            # enable Win Recovery Environment (WinRE)
            ("%SystemRoot%\\system32\\reagentc /enable", None),
            # issues enabling?
            # https://www.terabyteunlimited.com/kb/article.php?id=587
            # bcdboot c:\windows /v

            #"%SystemRoot%\\system32\\bcdedit.exe /deletevalue " + boot_identifier + " safeboot ",

        ]

        for tcmd in cmds:
            cmd = tcmd[0]
            require_return_code = tcmd[1]
            cmd = os.path.expandvars(cmd)
            returncode, output = ProcessManagement.run_cmd(cmd,
                attempts=3, require_return_code=require_return_code)
            p(str(returncode) + " - " + output)
            if returncode == -2:
                # Error running command?
                p("}}rbError - set boot options!}}xx\n" + output)
                return False

        return ret

    @staticmethod
    def disable_volume_shadow_copies():
        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping disable volume shadow copies}}xx")
            return True

        # Make sure SAM isn't readable: https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-36934
        cmd = "icacls %windir%\\system32\\config\\*.* /inheritance:e"

        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=1, require_return_code=None, cmd_timeout=300)

        cmd = "vssadmin delete shadows /for=c: /all /Quiet"

        cmd = os.path.expandvars(cmd)
        returncode, output = ProcessManagement.run_cmd(cmd,
            attempts=1, require_return_code=None, cmd_timeout=300)

        return True

if __name__ == "__main__":
    p("Testing:")
    ret = FolderPermissions.lock_boot_settings()
    p("Return: "  + str(ret))


text:
// ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
//  2013/03/01  Martin D. Flynn
//     -Initial release
// ----------------------------------------------------------------------------
package org.opengts.war.report;

import java.util.*;
import java.io.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
import org.opengts.db.tables.*;

import org.opengts.war.report.*;

public class ReportHeaderGroup
{

    // ------------------------------------------------------------------------

    private int       colIndex          = -1;
    private int       colSpan           = 1;
    private I18N.Text colTitle          = null;

    public ReportHeaderGroup(int index, int span, I18N.Text title)
    {
        this.colIndex = index;
        this.colSpan  = span;
        this.colTitle = title;
    }

    // ------------------------------------------------------------------------

    /* set column index */
    public void setColIndex(int index)
    {
        this.colIndex = index;
    }

    /* get column index */
    public int getColIndex()
    {
        return this.colIndex;
    }

    // ------------------------------------------------------------------------

    /* set column span */
    public void setColSpan(int span)
    {
        this.colSpan = span;
    }

    /* get column span */
    public int getColSpan()
    {
        return this.colSpan;
    }

    // ------------------------------------------------------------------------

    /* set column title */
    public void setTitle(I18N.Text title)
    {
        this.colTitle = title;
    }

    /* return true if a title is defined */
    public boolean hasTitle()
    {
        return (this.colTitle != null);
    }

    /* get column title */
    public String getTitle(Locale loc)
    {
        return (this.colTitle != null)? this.colTitle.toString(loc) : "";
    }

    // ------------------------------------------------------------------------

    /* debug: convert to string */
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        sb.append("colIndex=").append(this.getColIndex());
        sb.append(", ");
        sb.append("colspan=").append(this.getColSpan());
        sb.append("] ");
        sb.append(this.getTitle(null));
        return sb.toString();
    }

    // ------------------------------------------------------------------------

}

redpajama_set_name: RedPajamaGithub


text:
"use strict"

module.exports = findZeroCrossings

var core = require("./lib/zc-core")

function findZeroCrossings(array, level) {
  var cross = []
  level = +level || 0.0
  core(array.hi(array.shape[0]-1), cross, level)
  return cross
}


text:
:- ensure_loaded('$REGULUS/PrologLib/compatibility').

:- module(logging,
	  [
	   log_event/2,
	   log_event/3,
	   finish_logfile/0,
	   read_logfile/2
	  ]
	 ).

:- use_module('$REGULUS/Prolog/regulus_utilities').
:- use_module('$REGULUS/PrologLib/utilities').

:- use_module(library(lists)).
:- use_module(library(system)).
'SICSTUS4ONLY'( ( :- use_module(library(file_systems)) ) ).
:- use_module(library(xml)).

%-----------------------------------------------------------

%log_start_new_session(CFGFile) :-
%	get_new_logfile_name(File),
%	set_current_logfile(File),
%	log_event('START_SESSION', [CFGFile]).

%-----------------------------------------------------------

log_event(Operation, Args) :-
	log_event(Operation, "*null_comment*", Args).

log_event(Operation, CommentChars, Args) :-
	(   get_current_logfile(File) ->
	    true
	;
	    get_new_logfile_name(File),
	    write_logfile_header(File),
	    set_current_logfile(File)
	),
	log_event_to_logfile(Operation, CommentChars, Args, File).

finish_logfile :-
	(   get_current_logfile(File) ->
	    write_logfile_footer(File),
	    unset_current_logfile
	;
	    format2error('~N*** Error: request to finish logfile but no current logfile defined~n', []),
	    fail
	).

log_event_to_logfile(Operation, CommentChars, Args, File) :-
	open_regulus_file(File, append, S),
	write_log_term(S, Operation, CommentChars, Args),
	close(S),
	!.
log_event_to_logfile(Operation, CommentChars, Args, File) :-
	format2error('~N*** Error: bad call: ~w~n', [log_event_to_logfile(Operation, CommentChars, Args, File)]),
	fail.

%-----------------------------------------------------------

write_logfile_header(File) :-
	open_regulus_file(File, append, S),
	format(S, "~N<?xml version='1.0' encoding='ISO-8859-1'?>~n", []),
	format(S, "~N<logfile>~n", []),
	close(S),
	!.
write_logfile_header(File) :-
	format2error('~N*** Error: bad call: ~w~n', [write_logfile_header(File)]),
	fail.

write_logfile_footer(File) :-
	open_regulus_file(File, append, S),
	format(S, "~N</logfile>~n", []),
	close(S),
	!.
write_logfile_footer(File) :-
	format2error('~N*** Error: bad call: ~w~n', [write_logfile_footer(File)]),
	fail.

%-----------------------------------------------------------

read_logfile(File, XMLTerm) :-
	absolute_file_name(File, AbsFile),
	read_file_to_string(AbsFile, String),
	xml_parse(String, XMLTerm).

%-----------------------------------------------------------

write_log_term(S, Operation, CommentChars, Args) :-
	datime(Datime),
	datime_to_timestamp(Datime, Timestamp),
	comment_atom(CommentChars, CommentAtom),
	write_log_term1(S, Timestamp, CommentAtom, Operation, Args).

comment_atom("*null_comment*", '') :-
	!.
comment_atom(CommentChars, CommentAtom) :-
	format_to_atom('comment="~s" ', [CommentChars], CommentAtom).

write_log_term1(S, Timestamp, CommentAtom, Operation, []) :-
	format(S, '~N~n<EVENT operation="~w" ~wtimestamp="~w"/>~n', [Operation, CommentAtom, Timestamp]),
	!.
write_log_term1(S, Timestamp, CommentAtom, Operation, Args) :-
	format(S, '~N~n<EVENT operation="~w" ~wtimestamp="~w">~n', [Operation, CommentAtom, Timestamp]),
	write_log_term_args(Args, 1, S),
	format(S, '~N</EVENT>~n', []),
	!.

write_log_term_args([], _I, _S).
write_log_term_args([F | R], I, S) :-
	write_log_term_arg(F, I, S),
	I1 is I + 1,
	!,
	write_log_term_args(R, I1, S).

write_log_term_arg(Arg, I, S) :-
	make_arg_into_atom(Arg, Atom),
	format(S, '~N   <ARG~d>~w</ARG~d>~n', [I, Atom, I]),
	!.
write_log_term_arg(Arg, I, S) :-
	format2error('~N*** Error: bad call: ~w~n', [write_log_term_arg(Arg, I, S)]),
	fail.

%-----------------------------------------------------------

make_arg_into_atom(Arg, Atom) :-
	atomic(Arg),
	!,
	Arg = Atom.
make_arg_into_atom(Arg, Atom) :-
	is_list(Arg),
	make_arg_into_atom_list(Arg, AtomList),
	join_with_spaces(AtomList, Atom).

make_arg_into_atom_list([], []).
make_arg_into_atom_list([F | R], [F1 | R1]) :-
	make_arg_into_atom(F, F1),
	make_arg_into_atom_list(R, R1).

%-----------------------------------------------------------

get_new_logfile_name(AbsFile) :-
	get_logfile_dir(Dir),
	datime(Datime),
	datime_to_timestamp(Datime, Timestamp),
	format_to_atom('~w/log_~w.xml', [Dir, Timestamp], File),
	absolute_file_name(File, AbsFile),
	!.
get_new_logfile_name(AbsFile) :-
	format2error('~N*** Error: bad call: ~w~n', [get_new_logfile_name(AbsFile)]),
	fail.

get_logfile_dir(Dir) :-
	absolute_file_name('$REGULUS/logfiles', Dir),
	(   safe_directory_exists(Dir) ->
	    true
	;
	    otherwise ->
	    make_directory(Dir)
	),
	!.
get_logfile_dir(Dir) :-
	format2error('~N*** Error: bad call: ~w~n', [get_logfile_dir(Dir)]),
	fail.

%-----------------------------------------------------------

:- dynamic current_logfile/1.

set_current_logfile(File) :-
	retractall(current_logfile(_)),
	assertz(current_logfile(File)).

get_current_logfile(File) :-
	current_logfile(File).

unset_current_logfile :-
	retractall(current_logfile(_)).


text:
//
//  RMAppReceipt.m
//  RMStore
//
//  Created by Hermes on 10/12/13.
//  Copyright (c) 2013 Robot Media. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "RMAppReceipt.h"
#import <UIKit/UIKit.h>
#import <openssl/pkcs7.h>
#import <openssl/objects.h>
#import <openssl/sha.h>
#import <openssl/x509.h>

// From https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1
NSInteger const RMAppReceiptASN1TypeBundleIdentifier = 2;
NSInteger const RMAppReceiptASN1TypeAppVersion = 3;
NSInteger const RMAppReceiptASN1TypeOpaqueValue = 4;
NSInteger const RMAppReceiptASN1TypeHash = 5;
NSInteger const RMAppReceiptASN1TypeInAppPurchaseReceipt = 17;
NSInteger const RMAppReceiptASN1TypeOriginalAppVersion = 19;
NSInteger const RMAppReceiptASN1TypeExpirationDate = 21;

NSInteger const RMAppReceiptASN1TypeQuantity = 1701;
NSInteger const RMAppReceiptASN1TypeProductIdentifier = 1702;
NSInteger const RMAppReceiptASN1TypeTransactionIdentifier = 1703;
NSInteger const RMAppReceiptASN1TypePurchaseDate = 1704;
NSInteger const RMAppReceiptASN1TypeOriginalTransactionIdentifier = 1705;
NSInteger const RMAppReceiptASN1TypeOriginalPurchaseDate = 1706;
NSInteger const RMAppReceiptASN1TypeSubscriptionExpirationDate = 1708;
NSInteger const RMAppReceiptASN1TypeWebOrderLineItemID = 1711;
NSInteger const RMAppReceiptASN1TypeCancellationDate = 1712;

#pragma mark - ANS1

static int RMASN1ReadInteger(const uint8_t **pp, long omax)
{
    int tag, asn1Class;
    long length;
    int value = 0;
    ASN1_get_object(pp, &length, &tag, &asn1Class, omax);
    if (tag == V_ASN1_INTEGER)
    {
        for (int i = 0; i < length; i++)
        {
            value = value * 0x100 + (*pp)[i];
        }
    }
    *pp += length;
    return value;
}

static NSData* RMASN1ReadOctectString(const uint8_t **pp, long omax)
{
    int tag, asn1Class;
    long length;
    NSData *data = nil;
    ASN1_get_object(pp, &length, &tag, &asn1Class, omax);
    if (tag == V_ASN1_OCTET_STRING)
    {
        data = [NSData dataWithBytes:*pp length:length];
    }
    *pp += length;
    return data;
}

static NSString* RMASN1ReadString(const uint8_t **pp, long omax, int expectedTag, NSStringEncoding encoding)
{
    int tag, asn1Class;
    long length;
    NSString *value = nil;
    ASN1_get_object(pp, &length, &tag, &asn1Class, omax);
    if (tag == expectedTag)
    {
        value = [[NSString alloc] initWithBytes:*pp length:length encoding:encoding];
    }
    *pp += length;
    return value;
}

static NSString* RMASN1ReadUTF8String(const uint8_t **pp, long omax)
{
    return RMASN1ReadString(pp, omax, V_ASN1_UTF8STRING, NSUTF8StringEncoding);
}

static NSString* RMASN1ReadIA5SString(const uint8_t **pp, long omax)
{
    return RMASN1ReadString(pp, omax, V_ASN1_IA5STRING, NSASCIIStringEncoding);
}

static NSURL *_appleRootCertificateURL = nil;

@implementation RMAppReceipt

- (instancetype)initWithASN1Data:(NSData*)asn1Data
{
    if (self = [super init])
    {
        NSMutableArray *purchases = [NSMutableArray array];
         // Explicit casting to avoid errors when compiling as Objective-C++
        [RMAppReceipt enumerateASN1Attributes:(const uint8_t*)asn1Data.bytes length:asn1Data.length usingBlock:^(NSData *data, int type) {
            const uint8_t *s = (const uint8_t*)data.bytes;
            const NSUInteger length = data.length;
            switch (type)
            {
                case RMAppReceiptASN1TypeBundleIdentifier:
                    _bundleIdentifierData = data;
                    _bundleIdentifier = RMASN1ReadUTF8String(&s, length);
                    break;
                case RMAppReceiptASN1TypeAppVersion:
                    _appVersion = RMASN1ReadUTF8String(&s, length);
                    break;
                case RMAppReceiptASN1TypeOpaqueValue:
                    _opaqueValue = data;
                    break;
                case RMAppReceiptASN1TypeHash:
                    _receiptHash = data;
                    break;
                case RMAppReceiptASN1TypeInAppPurchaseReceipt:
                {
                    RMAppReceiptIAP *purchase = [[RMAppReceiptIAP alloc] initWithASN1Data:data];
                    [purchases addObject:purchase];
                    break;
                }
                case RMAppReceiptASN1TypeOriginalAppVersion:
                    _originalAppVersion = RMASN1ReadUTF8String(&s, length);
                    break;
                case RMAppReceiptASN1TypeExpirationDate:
                {
                    NSString *string = RMASN1ReadIA5SString(&s, length);
                    _expirationDate = [RMAppReceipt formatRFC3339String:string];
                    break;
                }
            }
        }];
        _inAppPurchases = purchases;
    }
    return self;
}

- (BOOL)containsInAppPurchaseOfProductIdentifier:(NSString*)productIdentifier
{
    for (RMAppReceiptIAP *purchase in _inAppPurchases)
    {
        if ([purchase.productIdentifier isEqualToString:productIdentifier]) return YES;
    }
    return NO;
}

-(BOOL)containsActiveAutoRenewableSubscriptionOfProductIdentifier:(NSString *)productIdentifier forDate:(NSDate *)date
{
    RMAppReceiptIAP *lastTransaction = nil;

    for (RMAppReceiptIAP *iap in self.inAppPurchases)
    {
        if (![iap.productIdentifier isEqualToString:productIdentifier]) continue;

        if (!lastTransaction || [iap.subscriptionExpirationDate compare:lastTransaction.subscriptionExpirationDate] == NSOrderedDescending)
        {
            lastTransaction = iap;
        }
    }

    return [lastTransaction isActiveAutoRenewableSubscriptionForDate:date];
}

- (BOOL)verifyReceiptHash
{
    // TODO: Getting the uuid in Mac is different. See: https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html#//apple_ref/doc/uid/TP40010573-CH1-SW5
    NSUUID *uuid = [UIDevice currentDevice].identifierForVendor;
    unsigned char uuidBytes[16];
    [uuid getUUIDBytes:uuidBytes];

    // Order taken from: https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html#//apple_ref/doc/uid/TP40010573-CH1-SW5
    NSMutableData *data = [NSMutableData data];
    [data appendBytes:uuidBytes length:sizeof(uuidBytes)];
    [data appendData:self.opaqueValue];
    [data appendData:self.bundleIdentifierData];

    NSMutableData *expectedHash = [NSMutableData dataWithLength:SHA_DIGEST_LENGTH];
    SHA1((const uint8_t*)data.bytes, data.length, (uint8_t*)expectedHash.mutableBytes); // Explicit casting to avoid errors when compiling as Objective-C++

    return [expectedHash isEqualToData:self.receiptHash];
}

+ (RMAppReceipt*)bundleReceipt
{
    NSURL *URL = [NSBundle mainBundle].appStoreReceiptURL;
    NSString *path = URL.path;
    const BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:nil];
    if (!exists) return nil;

    NSData *data = [RMAppReceipt dataFromPCKS7Path:path];
    if (!data) return nil;

    RMAppReceipt *receipt = [[RMAppReceipt alloc] initWithASN1Data:data];
    return receipt;
}

+ (void)setAppleRootCertificateURL:(NSURL*)url
{
    _appleRootCertificateURL = url;
}

#pragma mark - Utils

+ (NSData*)dataFromPCKS7Path:(NSString*)path
{
    const char *cpath = path.stringByStandardizingPath.fileSystemRepresentation;
    FILE *fp = fopen(cpath, "rb");
    if (!fp) return nil;

    PKCS7 *p7 = d2i_PKCS7_fp(fp, NULL);
    fclose(fp);

    if (!p7) return nil;

    NSData *data;
    NSURL *certificateURL = _appleRootCertificateURL ? : [[NSBundle mainBundle] URLForResource:@"AppleIncRootCertificate" withExtension:@"cer"];
    NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL];
    if (!certificateData || [self verifyPCKS7:p7 withCertificateData:certificateData])
    {
        struct pkcs7_st *contents = p7->d.sign->contents;
        if (PKCS7_type_is_data(contents))
        {
            ASN1_OCTET_STRING *octets = contents->d.data;
            data = [NSData dataWithBytes:octets->data length:octets->length];
        }
    }
    PKCS7_free(p7);
    return data;
}

+ (BOOL)verifyPCKS7:(PKCS7*)container withCertificateData:(NSData*)certificateData
{ // Based on: https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html#//apple_ref/doc/uid/TP40010573-CH1-SW17
    static int verified = 1;
    int result = 0;
    OpenSSL_add_all_digests(); // Required for PKCS7_verify to work
    X509_STORE *store = X509_STORE_new();
    if (store)
    {
        const uint8_t *certificateBytes = (uint8_t *)(certificateData.bytes);
        X509 *certificate = d2i_X509(NULL, &certificateBytes, (long)certificateData.length);
        if (certificate)
        {
            X509_STORE_add_cert(store, certificate);

            BIO *payload = BIO_new(BIO_s_mem());
            result = PKCS7_verify(container, NULL, store, NULL, payload, 0);
            BIO_free(payload);

            X509_free(certificate);
        }
    }
    X509_STORE_free(store);
    EVP_cleanup(); // Balances OpenSSL_add_all_digests (), perhttp://www.openssl.org/docs/crypto/OpenSSL_add_all_algorithms.html

    return result == verified;
}

/*
 Based on https://github.com/rmaddy/VerifyStoreReceiptiOS
 */
+ (void)enumerateASN1Attributes:(const uint8_t*)p length:(long)tlength usingBlock:(void (^)(NSData *data, int type))block
{
    int type, tag;
    long length;

    const uint8_t *end = p + tlength;

    ASN1_get_object(&p, &length, &type, &tag, end - p);
    if (type != V_ASN1_SET) return;

    while (p < end)
    {
        ASN1_get_object(&p, &length, &type, &tag, end - p);
        if (type != V_ASN1_SEQUENCE) break;

        const uint8_t *sequenceEnd = p + length;

        const int attributeType = RMASN1ReadInteger(&p, sequenceEnd - p);
        RMASN1ReadInteger(&p, sequenceEnd - p); // Consume attribute version

        NSData *data = RMASN1ReadOctectString(&p, sequenceEnd - p);
        if (data)
        {
            block(data, attributeType);
        }

        while (p < sequenceEnd)
        { // Skip remaining fields
            ASN1_get_object(&p, &length, &type, &tag, sequenceEnd - p);
            p += length;
        }
    }
}

+ (NSDate*)formatRFC3339String:(NSString*)string
{
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
    });
    NSDate *date = [formatter dateFromString:string];
    return date;
}

@end

@implementation RMAppReceiptIAP

- (instancetype)initWithASN1Data:(NSData*)asn1Data
{
    if (self = [super init])
    {
        // Explicit casting to avoid errors when compiling as Objective-C++
        [RMAppReceipt enumerateASN1Attributes:(const uint8_t*)asn1Data.bytes length:asn1Data.length usingBlock:^(NSData *data, int type) {
            const uint8_t *p = (const uint8_t*)data.bytes;
            const NSUInteger length = data.length;
            switch (type)
            {
                case RMAppReceiptASN1TypeQuantity:
                    _quantity = RMASN1ReadInteger(&p, length);
                    break;
                case RMAppReceiptASN1TypeProductIdentifier:
                    _productIdentifier = RMASN1ReadUTF8String(&p, length);
                    break;
                case RMAppReceiptASN1TypeTransactionIdentifier:
                    _transactionIdentifier = RMASN1ReadUTF8String(&p, length);
                    break;
                case RMAppReceiptASN1TypePurchaseDate:
                {
                    NSString *string = RMASN1ReadIA5SString(&p, length);
                    _purchaseDate = [RMAppReceipt formatRFC3339String:string];
                    break;
                }
                case RMAppReceiptASN1TypeOriginalTransactionIdentifier:
                    _originalTransactionIdentifier = RMASN1ReadUTF8String(&p, length);
                    break;
                case RMAppReceiptASN1TypeOriginalPurchaseDate:
                {
                    NSString *string = RMASN1ReadIA5SString(&p, length);
                    _originalPurchaseDate = [RMAppReceipt formatRFC3339String:string];
                    break;
                }
                case RMAppReceiptASN1TypeSubscriptionExpirationDate:
                {
                    NSString *string = RMASN1ReadIA5SString(&p, length);
                    _subscriptionExpirationDate = [RMAppReceipt formatRFC3339String:string];
                    break;
                }
                case RMAppReceiptASN1TypeWebOrderLineItemID:
                    _webOrderLineItemID = RMASN1ReadInteger(&p, length);
                    break;
                case RMAppReceiptASN1TypeCancellationDate:
                {
                    NSString *string = RMASN1ReadIA5SString(&p, length);
                    _cancellationDate = [RMAppReceipt formatRFC3339String:string];
                    break;
                }
            }
        }];
    }
    return self;
}

- (BOOL)isActiveAutoRenewableSubscriptionForDate:(NSDate*)date
{
    NSAssert(self.subscriptionExpirationDate != nil, @"The product %@ is not an auto-renewable subscription.", self.productIdentifier);

    if (self.cancellationDate) return NO;

    return [self.purchaseDate compare:date] != NSOrderedDescending && [date compare:self.subscriptionExpirationDate] != NSOrderedDescending;
}

@end


text:
@interface ImagePicker : CDVPlugin

@property(nonatomic, copy) NSString *callback;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong, nonatomic) CLLocation *location;
// 设置开关
@property (nonatomic, assign) BOOL enableShowTakePhoto; ///< 在内部显示拍照按钮
@property (nonatomic, assign) BOOL enableShowTakeVideo; ///< 在内部显示拍视频按钮
@property (nonatomic, assign) BOOL enableSortAscending;     ///< 照片排列按修改时间升序
@property (nonatomic, assign) BOOL enablePickingVideo; ///< 允许选择视频
@property (nonatomic, assign) BOOL enablePickingImage; ///< 允许选择图片
@property (nonatomic, assign) BOOL enablePickingGif;   ///< 允许选择GIF图片
@property (nonatomic, assign) BOOL enablePickingOriginalPhoto; ///< 允许选择原图
@property (nonatomic, assign) BOOL enableShowSheet; ///< 显示一个sheet,把拍照按钮放在外面

@property (nonatomic, assign) NSUInteger  maxCountTF;  ///< 照片最大可选张数,设置为1即为单选模式
@property (nonatomic, assign) NSUInteger  columnNumberTF; ///< 每行显示的照片张数
@property (nonatomic, assign) BOOL enableCrop; ///< 单选模式下裁剪
@property (nonatomic, assign) BOOL enableCircleCrop; ///< 使用圆形裁剪框
@property (nonatomic, assign) BOOL enablePickingMuitlpleVideo; ///< 允许多选视频
@property (nonatomic, assign) BOOL enableSelectedIndex; ///< 是否显示图片序号

@property (nonatomic, assign) NSInteger width;
@property (nonatomic, assign) NSInteger height;
@property (nonatomic, assign) NSInteger quality;

- (void)getPictures:(CDVInvokedUrlCommand *)command;
- (void)takePhoto:(CDVInvokedUrlCommand *)command;
- (NSString *)saveAndGetImageDocuments:(UIImage *)currentImage withName: (NSString *)imageName;

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#eeeeee"
    android:padding="1dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF">

    <ImageView
        android:id="@+id/dribbble_image"
        android:layout_margin="4dp"
        android:minHeight="160dp"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="160dp" />

    <ImageView
        android:id="@+id/player_image"
        android:paddingLeft="4dp"
        android:paddingBottom="4dp"
        android:minHeight="40dp"
        android:scaleType="centerCrop"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_below="@id/dribbble_image"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:layout_below="@id/dribbble_image"
        android:layout_toRightOf="@id/player_image"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title_text"
            android:textSize="16sp"
            android:singleLine="true"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:ellipsize="end"
            android:textColor="#000000"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" />
        <TextView
            android:id="@+id/player_text"
            android:textSize="12sp"
            android:layout_marginBottom="2dp"
            android:singleLine="true"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:ellipsize="end"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" />

    </LinearLayout>

    <LinearLayout
        android:layout_below="@id/player_image"
        android:layout_alignParentRight="true"
        android:paddingBottom="4dp"
        android:paddingLeft="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/views"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/views_image"
                android:layout_width="20dp"
                android:layout_height="15dp" />

            <TextView
                android:id="@+id/views_text"
                android:layout_width="wrap_content"
                android:layout_height="match_parent" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/comments"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/comments_image"
                android:layout_width="20dp"
                android:layout_height="15dp" />

            <TextView
                android:id="@+id/comments_text"
                android:layout_width="wrap_content"
                android:layout_height="match_parent" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/likes"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/likes_image"
                android:layout_width="20dp"
                android:layout_height="15dp" />

            <TextView
                android:id="@+id/likes_text"
                android:layout_width="wrap_content"
                android:layout_height="match_parent" />
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

</LinearLayout>


text:
module AsposeBarcodeCloud
  #
  class BarcodeResponse < BaseObject
    attr_accessor :barcode_value, :barcode_type, :region, :checksum
    # attribute mapping from ruby-style variable name to JSON key
    def self.attribute_map
      {

        #
        :'barcode_value' => :'BarcodeValue',

        #
        :'barcode_type' => :'BarcodeType',

        #
        :'region' => :'Region',

        #
        :'checksum' => :'Checksum'

      }
    end

    # attribute type
    def self.swagger_types
      {
        :'barcode_value' => :'String',
        :'barcode_type' => :'String',
        :'region' => :'Array<String>',
        :'checksum' => :'String'

      }
    end

    def initialize(attributes = {})
      return if !attributes.is_a?(Hash) || attributes.empty?

      # convert string to symbol for hash key
      attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

      if attributes[:'BarcodeValue']
        self.barcode_value = attributes[:'BarcodeValue']
      end

      if attributes[:'BarcodeType']
        self.barcode_type = attributes[:'BarcodeType']
      end

      if attributes[:'Region']
        if (value = attributes[:'Region']).is_a?(Array)
          self.region = value
        end
      end

      if attributes[:'Checksum']
        self.checksum = attributes[:'Checksum']
      end

    end

  end
end


text:
package com.oops.wifichat;

import android.app.Application;

public class ChatApplication extends Application {

	@Override
	public void onCreate() {
		super.onCreate();
	}

	public ChatConnection connection;
}


text:
package org.mrgeo.resources.raster.version;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.mrgeo.services.raster.version.VersionService;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Providers;

/**
 * @author Steve Ingram
 *         Date: 11/18/13
 */
@Path("/")
public class VersionResource
{

@Context
Providers providers;

@Context
VersionService service;

@GET
@Produces("application/json")
public Response getVersionAtApiRoot()
{
  getService();
  return Response.ok().entity(service.getVersionJson()).type("application/json").build();
}

@SuppressFBWarnings(value = "JAXRS_ENDPOINT", justification = "verified")
@GET
@Path("/version")
@Produces("application/json")
public Response getVersion()
{
  getService();
  return Response.ok().entity(service.getVersionJson()).type("application/json").build();
}

private void getService()
{
  if (service == null)
  {
    ContextResolver<VersionService> resolver =
        providers.getContextResolver(VersionService.class, MediaType.WILDCARD_TYPE);
    service = resolver.getContext(VersionService.class);
  }
}

}


text:
/* @font-face kit by Fonts2u (http://www.fonts2u.com) */ @font-face {font-family:"ONE PIECE";src:url("one_piece_font.eot?") format("eot"),url("one_piece_font.woff") format("woff"),url("one_piece_font.ttf") format("truetype"),url("one_piece_font.svg#ONEPIECE") format("svg");font-weight:normal;font-style:normal;}

body {
	text-align: center;
	background-color: lightblue;

}

h1 {
	font-family:"ONE PIECE";
	font-size: 60px;
}

h2 {
	font-family:"ONE PIECE";
}

img {
	margin: auto;
}

.copyright {
	font-family: "Times New Roman";
}


text:
namespace Envoy {
namespace Server {

WorkerPtr ProdWorkerFactory::createWorker(OverloadManager& overload_manager,
                                          const std::string& worker_name) {
  Event::DispatcherPtr dispatcher(api_.allocateDispatcher(worker_name));
  return WorkerPtr{
      new WorkerImpl(tls_, hooks_, std::move(dispatcher),
                     Network::ConnectionHandlerPtr{new ConnectionHandlerImpl(*dispatcher)},
                     overload_manager, api_)};
}

WorkerImpl::WorkerImpl(ThreadLocal::Instance& tls, ListenerHooks& hooks,
                       Event::DispatcherPtr&& dispatcher, Network::ConnectionHandlerPtr handler,
                       OverloadManager& overload_manager, Api::Api& api)
    : tls_(tls), hooks_(hooks), dispatcher_(std::move(dispatcher)), handler_(std::move(handler)),
      api_(api) {
  tls_.registerThread(*dispatcher_, false);
  overload_manager.registerForAction(
      OverloadActionNames::get().StopAcceptingConnections, *dispatcher_,
      [this](OverloadActionState state) { stopAcceptingConnectionsCb(state); });
}

void WorkerImpl::addListener(absl::optional<uint64_t> overridden_listener,
                             Network::ListenerConfig& listener, AddListenerCompletion completion) {
  // All listener additions happen via post. However, we must deal with the case where the listener
  // can not be created on the worker. There is a race condition where 2 processes can successfully
  // bind to an address, but then fail to listen() with EADDRINUSE. During initial startup, we want
  // to surface this.
  dispatcher_->post([this, overridden_listener, &listener, completion]() -> void {
    try {
      handler_->addListener(overridden_listener, listener);
      hooks_.onWorkerListenerAdded();
      completion(true);
    } catch (const Network::CreateListenerException& e) {
      ENVOY_LOG(error, "failed to add listener on worker: {}", e.what());
      completion(false);
    }
  });
}

uint64_t WorkerImpl::numConnections() const {
  uint64_t ret = 0;
  if (handler_) {
    ret = handler_->numConnections();
  }
  return ret;
}

void WorkerImpl::removeListener(Network::ListenerConfig& listener,
                                std::function<void()> completion) {
  ASSERT(thread_);
  const uint64_t listener_tag = listener.listenerTag();
  dispatcher_->post([this, listener_tag, completion]() -> void {
    handler_->removeListeners(listener_tag);
    completion();
    hooks_.onWorkerListenerRemoved();
  });
}

void WorkerImpl::removeFilterChains(uint64_t listener_tag,
                                    const std::list<const Network::FilterChain*>& filter_chains,
                                    std::function<void()> completion) {
  ASSERT(thread_);
  dispatcher_->post(
      [this, listener_tag, &filter_chains, completion = std::move(completion)]() -> void {
        handler_->removeFilterChains(listener_tag, filter_chains, completion);
      });
}

void WorkerImpl::start(GuardDog& guard_dog) {
  ASSERT(!thread_);

  // In posix, thread names are limited to 15 characters, so contrive to make
  // sure all interesting data fits there. The naming occurs in
  // ListenerManagerImpl's constructor: absl::StrCat("worker_", i). Let's say we
  // have 9999 threads. We'd need, so we need 7 bytes for "worker_", 4 bytes
  // for the thread index, leaving us 4 bytes left to distinguish between the
  // two threads used per dispatcher. We'll call this one "dsp:" and the
  // one allocated in guarddog_impl.cc "dog:".
  //
  // TODO(jmarantz): consider refactoring how this naming works so this naming
  // architecture is centralized, resulting in clearer names.
  Thread::Options options{absl::StrCat("wrk:", dispatcher_->name())};
  thread_ = api_.threadFactory().createThread(
      [this, &guard_dog]() -> void { threadRoutine(guard_dog); }, options);
}

void WorkerImpl::initializeStats(Stats::Scope& scope) { dispatcher_->initializeStats(scope); }

void WorkerImpl::stop() {
  // It's possible for the server to cleanly shut down while cluster initialization during startup
  // is happening, so we might not yet have a thread.
  if (thread_) {
    dispatcher_->exit();
    thread_->join();
  }
}

void WorkerImpl::stopListener(Network::ListenerConfig& listener, std::function<void()> completion) {
  ASSERT(thread_);
  const uint64_t listener_tag = listener.listenerTag();
  dispatcher_->post([this, listener_tag, completion]() -> void {
    handler_->stopListeners(listener_tag);
    if (completion != nullptr) {
      completion();
    }
  });
}

void WorkerImpl::threadRoutine(GuardDog& guard_dog) {
  ENVOY_LOG(debug, "worker entering dispatch loop");
  // The watch dog must be created after the dispatcher starts running and has post events flushed,
  // as this is when TLS stat scopes start working.
  dispatcher_->post([this, &guard_dog]() {
    watch_dog_ =
        guard_dog.createWatchDog(api_.threadFactory().currentThreadId(), dispatcher_->name());
    watch_dog_->startWatchdog(*dispatcher_);
  });
  dispatcher_->run(Event::Dispatcher::RunType::Block);
  ENVOY_LOG(debug, "worker exited dispatch loop");
  guard_dog.stopWatching(watch_dog_);

  // We must close all active connections before we actually exit the thread. This prevents any
  // destructors from running on the main thread which might reference thread locals. Destroying
  // the handler does this which additionally purges the dispatcher delayed deletion list.
  handler_.reset();
  tls_.shutdownThread();
  watch_dog_.reset();
}

void WorkerImpl::stopAcceptingConnectionsCb(OverloadActionState state) {
  if (state.isSaturated()) {
    handler_->disableListeners();
  } else {
    handler_->enableListeners();
  }
}

} // namespace Server
} // namespace Envoy