text:
import metadatautilspkg.globalvars as globalvars
from metadatautilspkg.metadatautils import *
from metadatautilspkg.adminmetadatautils import *

# FUNCTION DEFINITIONS

def getEventDetails():
    return ""  # TODO: temporary, needs more work!!

def getEventOutcome():
    return ""  # TODO: temporary, needs more work!!

def getEventOutcomeDetail():
    return ""  # TODO: temporary, needs more work!!

def getLinkingAgentId():
    return ""  # TODO: temporary, needs more work!!

def getLinkingAgentRole():
    return ""  # TODO: temporary, needs more work!!

def initMetadataRecord(initParams):
    """initMetadataRecord

    Arguments:
        initParams: initial parameters needed to populate the various fields
                    of the new metadata record. Passed as a dictionary object.

    This function creates a 'skeletal' metadata record, with as many fields
    populated as possible at this initialization stage.

    """

    metadataRecord = {}
    uniqueId = getUniqueID()
    metadataRecord["_id"] = uniqueId

    # Create the ADMIN entity here:
    arrangementInfo = initParams[globalvars.ARRANGEMENT_INFO_LABEL]
    adminEntity = initAdminMetadataEntity(arrangementInfo)

    metadataRecord[globalvars.labels.admn_entity.name] = adminEntity

    # Create the PREMIS (or preservation) entity here:
    metadataRecord[globalvars.labels.pres_entity.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_id.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_id.name][globalvars.labels.obj_id_typ.name] = globalvars.OBJ_ID_TYPE
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_id.name][globalvars.labels.obj_id_val.name] = uniqueId
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_cat.name] = globalvars.vocab.objCat
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst_algo.name] = globalvars.MD_INIT_STRING
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fixity.name][globalvars.labels.obj_msgdgst.name] = globalvars.MD_INIT_STRING
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_size.name] = initParams["fileSize"]
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fmt.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fmt.name][globalvars.labels.obj_fmt_dsgn.name] = {}
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fmt.name][globalvars.labels.obj_fmt_dsgn.name][globalvars.labels.obj_fmt_name.name] = initParams["fmtName"]
    #metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_chars.name][globalvars.labels.obj_fmt.name][globalvars.labels.obj_fmt_dsgn.name][globalvars.labels.obj_fmt_ver.name] = initParams["fmtVer"]

    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.obj_entity.name][globalvars.labels.obj_orig_name.name] = initParams["fileName"]

    # Create a parent entity (list) of all PREMIS 'event' entities.
    metadataRecord[globalvars.labels.pres_entity.name][globalvars.labels.evt_parent_entity.name] = []
    print_info("The following record has been initialized: {}".format(metadataRecord))

    return metadataRecord

def createIDAssignmentEvent(uniqueId):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.idAssgn
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    # Create a parent entity (list) for all PREMIS 'eventDetailInformation' entities
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_algo.name] = globalvars.UNIQUE_ID_ALGO
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_proglang.name] = globalvars.PYTHON_VER_STR
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_mthd.name] = globalvars.UNIQUE_ID_METHOD
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_idAssgn.name] = uniqueId

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createMsgDigestCalcEvent(chksm, chksmAlgo):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.msgDgstCalc
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_algo.name] = globalvars.CHECKSUM_ALGO
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_proglang.name] = globalvars.PYTHON_VER_STR
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_mthd.name] = globalvars.CHECKSUM_METHOD
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_msgDgst.name] = chksm
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createFileCopyEvent(evtTyp, srcFilePath, dstFilePath):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.replication
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_src.name] = srcFilePath
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_dst.name] = dstFilePath
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createFilenameChangeEvent(dstFilePrelimPath, dstFileUniquePath):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.filenameChg
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_src.name] = dstFilePrelimPath
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_dst.name] = dstFileUniquePath
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createFixityCheckEvent(status, calcChecksum):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.fixityChk
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createAccessionEvent():
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.accession
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createMetadataExtractionEvent(extdMethd, extdmeta):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.metadataExt
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_mthd.name] = extdMethd
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_metadataExtraction.name] = extdmeta
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createMetadataModificationEvent(before, after):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.metadataMod
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_before.name] = before
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_after.name] = after
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord

def createMigrationEvent(fileType, fileSize, imgWidth, imgHeight, fileName):
    eventRecord = {}
    eventRecord[globalvars.labels.evt_entity.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_typ.name] = globalvars.EVT_ID_TYP
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_id.name][globalvars.labels.evt_id_val.name] = getUniqueID()
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_typ.name] = globalvars.vocab.evtTyp.migration
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_dttime.name] = getCurrentEDTFTimestamp()

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name] = []
    eventDetailRecord = {}  # Create a single record for event detail information
    eventDetailRecord[globalvars.labels.evt_detail_info.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name] = {}
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_fileType.name] = fileType
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_fileSize.name] = fileSize
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_imgWidth.name] = imgWidth
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_imgHeight.name] = imgHeight
    eventDetailRecord[globalvars.labels.evt_detail_info.name][globalvars.labels.evt_detail_ext.name][globalvars.labels.evt_detail_fileName.name] = fileName
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_detail_parent.name].append(eventDetailRecord)

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_outcm_info.name][globalvars.labels.evt_outcm.name] = globalvars.vocab.evtOutcm.success

    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name] = {}
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_typ.name] = globalvars.LNK_AGNT_ID_TYPE
    eventRecord[globalvars.labels.evt_entity.name][globalvars.labels.evt_lnk_agnt_id.name][globalvars.labels.evt_lnk_agnt_id_val.name] = globalvars.LNK_AGNT_ID_VAL

    return eventRecord


text:
#ifndef __INC_USER_H__
#define __INC_USER_H__

/* There's no real rationale behind these values other
   than "they looked good" */
#define MAXNICKLEN 20
#define MAXACCOUNT 20
#define MAXIDENT 16
#define MAXHOST 120
#define MAXGECOS 40

#define MAXAWAY 256

#define UMODE_OPER             0x00000001
#define UMODE_INVISIBLE        0x00000002
#define UMODE_WALLOPS          0x00000004
#define UMODE_CLOAKED          0x00000008
#define UMODE_SERVICE          0x00000010

/* all users */
#define USER_MASK_FLAGS        0x000000ff
#define USER_IS_LOCAL          0x00000001

/* local */
#define USER_MASK_CAP          0x0000ff00
#define CAP_MULTI_PREFIX       0x00000100
#define CAP_AWAY_NOTIFY        0x00000200

/* registration postpone */
#define USER_MASK_WAIT         0x00ff0000
#define USER_WAIT_CAPS         0x00010000

typedef struct u_user u_user;

#include "conn.h"
#include "server.h"
#include "mode.h"
#include "ratelimit.h"

struct u_user {
	char uid[10];

	uint mode, flags;
	u_map *channels;
	u_map *invites;

	char nick[MAXNICKLEN+1];
	char acct[MAXACCOUNT+1];
	u_ts_t nickts;

	char ident[MAXIDENT+1];

	char ip[INET6_ADDRSTRLEN];
	char realhost[MAXHOST+1];
	char host[MAXHOST+1];

	char gecos[MAXGECOS+1];

	char away[MAXAWAY+1];

	u_ratelimit_t limit;

	u_link *link; /* never null, except when shutting down */
	u_oper_block *oper; /* local opers only */
	u_server *sv; /* never null */
};

#define IS_LOCAL_USER(u) ((u->flags & USER_IS_LOCAL) != 0)

#define IS_OPER(u)       ((u) && (u)->mode & UMODE_OPER)
#define IS_SERVICE(u)    ((u) && (u)->mode & UMODE_SERVICE)

#define IS_LOGGED_IN(u)  ((u) && (u)->acct[0])
#define IS_AWAY(u)       ((u) && (u)->away[0])

#define IS_REGISTERED(u) (!IS_LOCAL_USER(u) || \
                          ((u)->link->flags & U_LINK_REGISTERED) != 0)

extern mowgli_patricia_t *users_by_nick;
extern mowgli_patricia_t *users_by_uid;

extern u_mode_info umode_infotab[128];
extern u_mode_ctx umodes;
extern uint umode_default;

extern u_user *u_user_create_local(u_link *link);
extern u_user *u_user_create_remote(u_server*, char *uid);
extern void u_user_destroy(u_user*);

extern void u_user_try_register(u_user*);

extern u_user *u_user_by_nick_raw(const char*);
extern u_user *u_user_by_nick(const char*);
extern u_user *u_user_by_uid_raw(const char*);
extern u_user *u_user_by_uid(const char*);

static inline u_user *u_user_by_ref(u_link *link, char *ref)
{
	if (!ref) return NULL;
	return (link && link->type == LINK_SERVER && isdigit(*ref)) ?
	        u_user_by_uid(ref) : u_user_by_nick(ref);
}

extern char *u_user_modes(u_user*);

extern void u_user_set_nick(u_user*, char*, uint);

extern bool u_user_try_override(u_user*);

extern void u_user_vnum(u_user*, int, va_list);
extern int u_user_num(u_user*, int num, ...);

extern void u_user_send_isupport(u_user*);
extern void u_user_send_motd(u_user*);

extern void u_user_welcome(u_user*);

extern void u_user_make_euid(u_user*, char *buf); /* sizeof(buf) > 512 */

extern void u_user_flush_inputs(void);

extern int init_user(void);
extern int dump_user(void);
extern int restore_user(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
PKGNAME="Wct Editor"
TMP="/tmp/wct-install"
URL="https://github.com/Mihip/Wct/raw/master/src/tools/other/wct.tar.gz"
FILE="/usr/bin/wct"

if [ -f $FILE ];
then

	echo "Preparing to update package $PKGNAME"
	echo "Package $PKGNAME exists..."
	echo "Updating..."
	echo "Making temporary directory..."
	mkdir "$TMP"
	echo "Downloading tarball with binaries..."
	wget -qO "$TMP/wct.tar.gz" $URL
	echo "Unpacking downloaded archive..."
	tar -xf "$TMP/wct.tar.gz" -C "$TMP"
	echo "Copying to /usr/bin/wct..."
	sudo cp "$TMP/wct" /usr/bin/wct
	echo "Adding +x to /usr/bin/wct..."
	sudo chmod +x /usr/bin/wct
	echo "Removing temporary folder..."
	sudo rm -rf "$TMP"
	echo "Successfully updated package $PKGNAME"

else

	echo "Preparing to install package $PKGNAME"
	echo "Package $PKGNAME seems to not exists in system..."
	echo "Installing..."
	echo "Making temporary directory..."
	mkdir "$TMP"
	echo "Downloading tarball with binaries..."
	wget -qO "$TMP/wct.tar.gz" $URL
	echo "Unpacking downloaded archive..."
	tar -xf "$TMP/wct.tar.gz" -C "$TMP"
	echo "Copying to /usr/bin/wct..."
	sudo cp "$TMP/wct" /usr/bin/wct
	echo "Adding +x to /usr/bin/wct..."
	sudo chmod +x /usr/bin/wct
	echo "Removing temporary folder..."
	sudo rm -rf "$TMP"
	echo "Successfully installed package $PKGNAME"

fi


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var async = require('async');
var routes = require('./routes/index');
var cheese = require('./routes/cheese');
var reservations = require('./routes/reservations');
var spots = require('./routes/spots');
var users = require('./routes/users');
var cors = require('cors');
var jquery = require('jquery');
var client = require('twilio');
var app = express();

//enabling CORS Pre-flight
app.options('/users/login', cors()); // enable pre-flight request for DELETE request
app.delete('/products/:id', cors(), function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});
});

app.listen(3001, function(){
  console.log('CORS-enabled web server listening on port 3000');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Enable
app.all('*', function(req, res,next) {

    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.sendStatus(200);
    }
    else {
        next();
    }

});

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

app.use('/', routes);
app.use('/reservations', reservations);
app.use('/spots', spots);
app.use('/users', users);
app.use('/cheese',cheese);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;


text:
<?xml version="1.0" encoding="UTF-8"?>
<category/>


text:
package org.aludratest.service.gui.component.impl;

import org.aludratest.service.gui.component.Label;
import org.aludratest.service.gui.component.ValueComponent;
import org.databene.commons.Validator;

/** Default implementation of the Label interface. */
public class LabelImpl extends AbstractElement<Label> implements ValueComponent, Label {

    private ValueComponentHelper helper = new ValueComponentHelper(this, false);

    @Override
    public String getText() {
        return helper.getText();
    }

    @Override
    public void assertTextEquals(String expectedText) {
        helper.assertTextEquals(expectedText);
    }

    @Override
    public void assertTextNotEquals(String expectedText) {
        helper.assertTextNotEquals(expectedText);
    }

    @Override
    public void assertTextContains(String expectedText) {
        helper.assertTextContains(expectedText);
    }

    @Override
    public void assertTextContainsIgnoreCaseTrimmed(String expectedText) {
        helper.assertTextContainsIgnoreCaseTrimmed(expectedText);
    }

    @Override
    public void assertTextEqualsIgnoreCaseTrimmed(String expectedText) {
        helper.assertTextEqualsIgnoreCaseTrimmed(expectedText);
    }

    @Override
    public void assertTextMatches(Validator<String> validator) {
        helper.assertTextMatches(validator);
    }

    @Override
    public void assertValueGreaterThan(String value) {
        helper.assertValueGreaterThan(value);
    }

    @Override
    public void assertValueLessThan(String value) {
        helper.assertValueLessThan(value);
    }

}


text:
try:
    import json
except ImportError:
    import simplejson as json

import boto
from boto.connection import AWSQueryConnection
from boto.regioninfo import RegionInfo
from boto.exception import JSONResponseError
from boto.sqs import exceptions

class SQSConnection(AWSQueryConnection):
    """
    Welcome to the Amazon Simple Queue Service API Reference . This
    section describes who should read this guide, how the guide is
    organized, and other resources related to the Amazon Simple Queue
    Service (Amazon SQS).

    Amazon SQS offers reliable and scalable hosted queues for storing
    messages as they travel between computers. By using Amazon SQS,
    you can move data between distributed components of your
    applications that perform different tasks without losing messages
    or requiring each component to be always available.

    Helpful Links:

    + `Current WSDL (2012-11-05)`_
    + `Making API Requests`_
    + `Amazon SQS product page`_
    + `Regions and Endpoints`_

    We also provide SDKs that enable you to access Amazon SQS from
    your preferred programming language. The SDKs contain
    functionality that automatically takes care of tasks such as:

    + Cryptographically signing your service requests
    + Retrying requests
    + Handling error responses

    For a list of available SDKs, go to `Tools for Amazon Web
    Services`_.
    """
    APIVersion = "2012-11-05"
    DefaultRegionName = "us-east-1"
    DefaultRegionEndpoint = "sqs.us-east-1.amazonaws.com"
    ResponseError = JSONResponseError

    _faults = {
        "QueueDoesNotExist": exceptions.QueueDoesNotExist,
        "BatchEntryIdsNotDistinct": exceptions.BatchEntryIdsNotDistinct,
        "EmptyBatchRequest": exceptions.EmptyBatchRequest,
        "OverLimit": exceptions.OverLimit,
        "QueueNameExists": exceptions.QueueNameExists,
        "InvalidMessageContents": exceptions.InvalidMessageContents,
        "TooManyEntriesInBatchRequest": exceptions.TooManyEntriesInBatchRequest,
        "QueueDeletedRecently": exceptions.QueueDeletedRecently,
        "InvalidBatchEntryId": exceptions.InvalidBatchEntryId,
        "BatchRequestTooLong": exceptions.BatchRequestTooLong,
        "InvalidIdFormat": exceptions.InvalidIdFormat,
        "ReceiptHandleIsInvalid": exceptions.ReceiptHandleIsInvalid,
        "InvalidAttributeName": exceptions.InvalidAttributeName,
        "MessageNotInflight": exceptions.MessageNotInflight,
    }

    def __init__(self, **kwargs):
        region = kwargs.pop('region', None)
        if not region:
            region = RegionInfo(self, self.DefaultRegionName,
                                self.DefaultRegionEndpoint)

        if 'host' not in kwargs:
            kwargs['host'] = region.endpoint

        super(SQSConnection, self).__init__(**kwargs)
        self.region = region

    def _required_auth_capability(self):
        return ['hmac-v4']

    def add_permission(self, queue_url, label, aws_account_ids, actions):
        """
        Adds a permission to a queue for a specific `principal`_. This
        allows for sharing access to the queue.

        When you create a queue, you have full control access rights
        for the queue. Only you (as owner of the queue) can grant or
        deny permissions to the queue. For more information about
        these permissions, see `Shared Queues`_ in the Amazon SQS
        Developer Guide .

        `AddPermission` writes an Amazon SQS-generated policy. If you
        want to write your own policy, use SetQueueAttributes to
        upload your policy. For more information about writing your
        own policy, see `Using The Access Policy Language`_ in the
        Amazon SQS Developer Guide .
        Some API actions take lists of parameters. These lists are
        specified using the `param.n` notation. Values of `n` are
        integers starting from 1. For example, a parameter list with
        two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type label: string
        :param label: The unique identification of the permission you're
            setting (e.g., `AliceSendMessage`). Constraints: Maximum 80
            characters; alphanumeric characters, hyphens (-), and underscores
            (_) are allowed.

        :type aws_account_ids: list
        :param aws_account_ids: The AWS account number of the `principal`_ who
            will be given permission. The principal must have an AWS account,
            but does not need to be signed up for Amazon SQS. For information
            about locating the AWS account identification, see `Your AWS
            Identifiers`_ in the Amazon SQS Developer Guide .

        :type actions: list
        :param actions: The action the client wants to allow for the specified
            principal. The following are valid values: `* | SendMessage |
            ReceiveMessage | DeleteMessage | ChangeMessageVisibility |
            GetQueueAttributes | GetQueueUrl`. For more information about these
            actions, see `Understanding Permissions`_ in the Amazon SQS
            Developer Guide .
        Specifying `SendMessage`, `DeleteMessage`, or `ChangeMessageVisibility`
            for the `ActionName.n` also grants permissions for the
            corresponding batch versions of those actions: `SendMessageBatch`,
            `DeleteMessageBatch`, and `ChangeMessageVisibilityBatch`.

        """
        params = {'QueueUrl': queue_url, 'Label': label, }
        self.build_list_params(params,
                               aws_account_ids,
                               'AWSAccountIds.member')
        self.build_list_params(params,
                               actions,
                               'Actions.member')
        return self._make_request(
            action='AddPermission',
            verb='POST',
            path='/', params=params)

    def change_message_visibility(self, queue_url, receipt_handle,
                                  visibility_timeout):
        """
        Changes the visibility timeout of a specified message in a
        queue to a new value. The maximum allowed timeout value you
        can set the value to is 12 hours. This means you can't extend
        the timeout of a message in an existing queue to more than a
        total visibility timeout of 12 hours. (For more information
        visibility timeout, see `Visibility Timeout`_ in the Amazon
        SQS Developer Guide .)

        For example, let's say you have a message and its default
        message visibility timeout is 30 minutes. You could call
        `ChangeMessageVisiblity` with a value of two hours and the
        effective timeout would be two hours and 30 minutes. When that
        time comes near you could again extend the time out by calling
        ChangeMessageVisiblity, but this time the maximum allowed
        timeout would be 9 hours and 30 minutes.
        If you attempt to set the `VisibilityTimeout` to an amount
        more than the maximum time left, Amazon SQS returns an error.
        It will not automatically recalculate and increase the timeout
        to the maximum time remaining. Unlike with a queue, when you
        change the visibility timeout for a specific message, that
        timeout value is applied immediately but is not saved in
        memory for that message. If you don't delete a message after
        it is received, the visibility timeout for the message the
        next time it is received reverts to the original timeout
        value, not the value you set with the
        `ChangeMessageVisibility` action.

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type receipt_handle: string
        :param receipt_handle: The receipt handle associated with the message
            whose visibility timeout should be changed. This parameter is
            returned by the ReceiveMessage action.

        :type visibility_timeout: integer
        :param visibility_timeout: The new value (in seconds - from 0 to 43200
            - maximum 12 hours) for the message's visibility timeout.

        """
        params = {
            'QueueUrl': queue_url,
            'ReceiptHandle': receipt_handle,
            'VisibilityTimeout': visibility_timeout,
        }
        return self._make_request(
            action='ChangeMessageVisibility',
            verb='POST',
            path='/', params=params)

    def change_message_visibility_batch(self, queue_url, entries):
        """
        Changes the visibility timeout of multiple messages. This is a
        batch version of ChangeMessageVisibility. The result of the
        action on each message is reported individually in the
        response. You can send up to 10 ChangeMessageVisibility
        requests with each `ChangeMessageVisibilityBatch` action.
        Because the batch request can result in a combination of
        successful and unsuccessful actions, you should check for
        batch errors even when the call returns an HTTP status code of
        200. Some API actions take lists of parameters. These lists
        are specified using the `param.n` notation. Values of `n` are
        integers starting from 1. For example, a parameter list with
        two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type entries: list
        :param entries: A list of receipt handles of the messages for which the
            visibility timeout must be changed.

        """
        params = {'QueueUrl': queue_url, }
        self.build_complex_list_params(
            params, entries,
            'Entries.member',
            ('Id', 'ReceiptHandle', 'VisibilityTimeout'))
        return self._make_request(
            action='ChangeMessageVisibilityBatch',
            verb='POST',
            path='/', params=params)

    def create_queue(self, queue_name, attributes=None):
        """
        Creates a new queue, or returns the URL of an existing one.
        When you request `CreateQueue`, you provide a name for the
        queue. To successfully create a new queue, you must provide a
        name that is unique within the scope of your own queues.

        If you delete a queue, you must wait at least 60 seconds
        before creating a queue with the same name.

        You may pass one or more attributes in the request. If you do
        not provide a value for any attribute, the queue will have the
        default value for that attribute. Permitted attributes are the
        same that can be set using SetQueueAttributes.

        Use GetQueueUrl to get a queue's URL. GetQueueUrl requires
        only the `QueueName` parameter.

        If you provide the name of an existing queue, along with the
        exact names and values of all the queue's attributes,
        `CreateQueue` returns the queue URL for the existing queue. If
        the queue name, attribute names, or attribute values do not
        match an existing queue, `CreateQueue` returns an error.
        Some API actions take lists of parameters. These lists are
        specified using the `param.n` notation. Values of `n` are
        integers starting from 1. For example, a parameter list with
        two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_name: string
        :param queue_name: The name for the queue to be created.

        :type attributes: map
        :param attributes: A map of attributes with their corresponding values.
        The following lists the names, descriptions, and values of the special
            request parameters the `CreateQueue` action uses:

        + `DelaySeconds` - The time in seconds that the delivery of all
              messages in the queue will be delayed. An integer from 0 to 900 (15
              minutes). The default for this attribute is 0 (zero).
        + `MaximumMessageSize` - The limit of how many bytes a message can
              contain before Amazon SQS rejects it. An integer from 1024 bytes (1
              KiB) up to 262144 bytes (256 KiB). The default for this attribute
              is 262144 (256 KiB).
        + `MessageRetentionPeriod` - The number of seconds Amazon SQS retains a
              message. Integer representing seconds, from 60 (1 minute) to
              1209600 (14 days). The default for this attribute is 345600 (4
              days).
        + `Policy` - The queue's policy. A valid form-url-encoded policy. For
              more information about policy structure, see `Basic Policy
              Structure`_ in the Amazon SQS Developer Guide . For more
              information about form-url-encoding, see `http://www.w3.org/MarkUp
              /html-spec/html-spec_8.html#SEC8.2.1`_.
        + `ReceiveMessageWaitTimeSeconds` - The time for which a ReceiveMessage
              call will wait for a message to arrive. An integer from 0 to 20
              (seconds). The default for this attribute is 0.
        + `VisibilityTimeout` - The visibility timeout for the queue. An
              integer from 0 to 43200 (12 hours). The default for this attribute
              is 30. For more information about visibility timeout, see
              `Visibility Timeout`_ in the Amazon SQS Developer Guide .

        """
        params = {'QueueName': queue_name, }
        if attributes is not None:
            params['Attributes'] = attributes
        return self._make_request(
            action='CreateQueue',
            verb='POST',
            path='/', params=params)

    def delete_message(self, queue_url, receipt_handle):
        """
        Deletes the specified message from the specified queue. You
        specify the message by using the message's `receipt handle`
        and not the `message ID` you received when you sent the
        message. Even if the message is locked by another reader due
        to the visibility timeout setting, it is still deleted from
        the queue. If you leave a message in the queue for longer than
        the queue's configured retention period, Amazon SQS
        automatically deletes it.

        The receipt handle is associated with a specific instance of
        receiving the message. If you receive a message more than
        once, the receipt handle you get each time you receive the
        message is different. When you request `DeleteMessage`, if you
        don't provide the most recently received receipt handle for
        the message, the request will still succeed, but the message
        might not be deleted.

        It is possible you will receive a message even after you have
        deleted it. This might happen on rare occasions if one of the
        servers storing a copy of the message is unavailable when you
        request to delete the message. The copy remains on the server
        and might be returned to you again on a subsequent receive
        request. You should create your system to be idempotent so
        that receiving a particular message more than once is not a
        problem.

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type receipt_handle: string
        :param receipt_handle: The receipt handle associated with the message
            to delete.

        """
        params = {
            'QueueUrl': queue_url,
            'ReceiptHandle': receipt_handle,
        }
        return self._make_request(
            action='DeleteMessage',
            verb='POST',
            path='/', params=params)

    def delete_message_batch(self, queue_url, entries):
        """
        Deletes multiple messages. This is a batch version of
        DeleteMessage. The result of the delete action on each message
        is reported individually in the response.

        Because the batch request can result in a combination of
        successful and unsuccessful actions, you should check for
        batch errors even when the call returns an HTTP status code of
        200.
        Some API actions take lists of parameters. These lists are
        specified using the `param.n` notation. Values of `n` are
        integers starting from 1. For example, a parameter list with
        two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type entries: list
        :param entries: A list of receipt handles for the messages to be
            deleted.

        """
        params = {'QueueUrl': queue_url, }
        self.build_complex_list_params(
            params, entries,
            'Entries.member',
            ('Id', 'ReceiptHandle'))
        return self._make_request(
            action='DeleteMessageBatch',
            verb='POST',
            path='/', params=params)

    def delete_queue(self, queue_url):
        """
        Deletes the queue specified by the **queue URL**, regardless
        of whether the queue is empty. If the specified queue does not
        exist, Amazon SQS returns a successful response.

        Use `DeleteQueue` with care; once you delete your queue, any
        messages in the queue are no longer available.

        When you delete a queue, the deletion process takes up to 60
        seconds. Requests you send involving that queue during the 60
        seconds might succeed. For example, a SendMessage request
        might succeed, but after the 60 seconds, the queue and that
        message you sent no longer exist. Also, when you delete a
        queue, you must wait at least 60 seconds before creating a
        queue with the same name.

        We reserve the right to delete queues that have had no
        activity for more than 30 days. For more information, see `How
        Amazon SQS Queues Work`_ in the Amazon SQS Developer Guide .

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        """
        params = {'QueueUrl': queue_url, }
        return self._make_request(
            action='DeleteQueue',
            verb='POST',
            path='/', params=params)

    def get_queue_attributes(self, queue_url, attribute_names=None):
        """
        Gets attributes for the specified queue. The following
        attributes are supported:

        + `All` - returns all values.
        + `ApproximateNumberOfMessages` - returns the approximate
          number of visible messages in a queue. For more information,
          see `Resources Required to Process Messages`_ in the Amazon
          SQS Developer Guide .
        + `ApproximateNumberOfMessagesNotVisible` - returns the
          approximate number of messages that are not timed-out and not
          deleted. For more information, see `Resources Required to
          Process Messages`_ in the Amazon SQS Developer Guide .
        + `VisibilityTimeout` - returns the visibility timeout for the
          queue. For more information about visibility timeout, see
          `Visibility Timeout`_ in the Amazon SQS Developer Guide .
        + `CreatedTimestamp` - returns the time when the queue was
          created (epoch time in seconds).
        + `LastModifiedTimestamp` - returns the time when the queue
          was last changed (epoch time in seconds).
        + `Policy` - returns the queue's policy.
        + `MaximumMessageSize` - returns the limit of how many bytes a
          message can contain before Amazon SQS rejects it.
        + `MessageRetentionPeriod` - returns the number of seconds
          Amazon SQS retains a message.
        + `QueueArn` - returns the queue's Amazon resource name (ARN).
        + `ApproximateNumberOfMessagesDelayed` - returns the
          approximate number of messages that are pending to be added to
          the queue.
        + `DelaySeconds` - returns the default delay on the queue in
          seconds.
        + `ReceiveMessageWaitTimeSeconds` - returns the time for which
          a ReceiveMessage call will wait for a message to arrive.
        + `RedrivePolicy` - returns the parameters for dead letter
          queue functionality of the source queue. For more information
          about RedrivePolicy and dead letter queues, see `Using Amazon
          SQS Dead Letter Queues`_ in the Amazon SQS Developer Guide .

        Going forward, new attributes might be added. If you are
        writing code that calls this action, we recommend that you
        structure your code so that it can handle new attributes
        gracefully. Some API actions take lists of parameters. These
        lists are specified using the `param.n` notation. Values of
        `n` are integers starting from 1. For example, a parameter
        list with two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type attribute_names: list
        :param attribute_names: A list of attributes to retrieve information
            for.

        """
        params = {'QueueUrl': queue_url, }
        if attribute_names is not None:
            self.build_list_params(params,
                                   attribute_names,
                                   'AttributeNames.member')
        return self._make_request(
            action='GetQueueAttributes',
            verb='POST',
            path='/', params=params)

    def get_queue_url(self, queue_name, queue_owner_aws_account_id=None):
        """
        Returns the URL of an existing queue. This action provides a
        simple way to retrieve the URL of an Amazon SQS queue.

        To access a queue that belongs to another AWS account, use the
        `QueueOwnerAWSAccountId` parameter to specify the account ID
        of the queue's owner. The queue's owner must grant you
        permission to access the queue. For more information about
        shared queue access, see AddPermission or go to `Shared
        Queues`_ in the Amazon SQS Developer Guide .

        :type queue_name: string
        :param queue_name: The name of the queue whose URL must be fetched.
            Maximum 80 characters; alphanumeric characters, hyphens (-), and
            underscores (_) are allowed.

        :type queue_owner_aws_account_id: string
        :param queue_owner_aws_account_id: The AWS account ID of the account
            that created the queue.

        """
        params = {'QueueName': queue_name, }
        if queue_owner_aws_account_id is not None:
            params['QueueOwnerAWSAccountId'] = queue_owner_aws_account_id
        return self._make_request(
            action='GetQueueUrl',
            verb='POST',
            path='/', params=params)

    def list_dead_letter_source_queues(self, queue_url):
        """
        Returns a list of your queues that have the RedrivePolicy
        queue attribute configured with a dead letter queue.

        :type queue_url: string
        :param queue_url: The queue URL of a dead letter queue.

        """
        params = {'QueueUrl': queue_url, }
        return self._make_request(
            action='ListDeadLetterSourceQueues',
            verb='POST',
            path='/', params=params)

    def list_queues(self, queue_name_prefix=None):
        """
        Returns a list of your queues. The maximum number of queues
        that can be returned is 1000. If you specify a value for the
        optional `QueueNamePrefix` parameter, only queues with a name
        beginning with the specified value are returned.

        :type queue_name_prefix: string
        :param queue_name_prefix: A string to use for filtering the list
            results. Only those queues whose name begins with the specified
            string are returned.

        """
        params = {}
        if queue_name_prefix is not None:
            params['QueueNamePrefix'] = queue_name_prefix
        return self._make_request(
            action='ListQueues',
            verb='POST',
            path='/', params=params)

    def receive_message(self, queue_url, attribute_names=None,
                        max_number_of_messages=None, visibility_timeout=None,
                        wait_time_seconds=None):
        """
        Retrieves one or more messages from the specified queue. Long
        poll support is enabled by using the `WaitTimeSeconds`
        parameter. For more information, see `Amazon SQS Long Poll`_
        in the Amazon SQS Developer Guide .

        Short poll is the default behavior where a weighted random set
        of machines is sampled on a `ReceiveMessage` call. This means
        only the messages on the sampled machines are returned. If the
        number of messages in the queue is small (less than 1000), it
        is likely you will get fewer messages than you requested per
        `ReceiveMessage` call. If the number of messages in the queue
        is extremely small, you might not receive any messages in a
        particular `ReceiveMessage` response; in which case you should
        repeat the request.

        For each message returned, the response includes the
        following:

        + Message body
        + MD5 digest of the message body. For information about MD5,
          go to `http://www.faqs.org/rfcs/rfc1321.html`_.
        + Message ID you received when you sent the message to the
          queue.
        + Receipt handle.

        The receipt handle is the identifier you must provide when
        deleting the message. For more information, see `Queue and
        Message Identifiers`_ in the Amazon SQS Developer Guide .

        You can provide the `VisibilityTimeout` parameter in your
        request, which will be applied to the messages that Amazon SQS
        returns in the response. If you do not include the parameter,
        the overall visibility timeout for the queue is used for the
        returned messages. For more information, see `Visibility
        Timeout`_ in the Amazon SQS Developer Guide .

        Going forward, new attributes might be added. If you are
        writing code that calls this action, we recommend that you
        structure your code so that it can handle new attributes
        gracefully.

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type attribute_names: list
        :param attribute_names:
        A list of attributes that need to be returned along with each message.

        The following lists the names and descriptions of the attributes that
            can be returned:

        + `All` - returns all values.
        + `ApproximateFirstReceiveTimestamp` - returns the time when the
              message was first received (epoch time in milliseconds).
        + `ApproximateReceiveCount` - returns the number of times a message has
              been received but not deleted.
        + `SenderId` - returns the AWS account number (or the IP address, if
              anonymous access is allowed) of the sender.
        + `SentTimestamp` - returns the time when the message was sent (epoch
              time in milliseconds).

        :type max_number_of_messages: integer
        :param max_number_of_messages: The maximum number of messages to
            return. Amazon SQS never returns more messages than this value but
            may return fewer.
        All of the messages are not necessarily returned.

        :type visibility_timeout: integer
        :param visibility_timeout: The duration (in seconds) that the received
            messages are hidden from subsequent retrieve requests after being
            retrieved by a `ReceiveMessage` request.

        :type wait_time_seconds: integer
        :param wait_time_seconds: The duration (in seconds) for which the call
            will wait for a message to arrive in the queue before returning. If
            a message is available, the call will return sooner than
            WaitTimeSeconds.

        """
        params = {'QueueUrl': queue_url, }
        if attribute_names is not None:
            self.build_list_params(params,
                                   attribute_names,
                                   'AttributeNames.member')
        if max_number_of_messages is not None:
            params['MaxNumberOfMessages'] = max_number_of_messages
        if visibility_timeout is not None:
            params['VisibilityTimeout'] = visibility_timeout
        if wait_time_seconds is not None:
            params['WaitTimeSeconds'] = wait_time_seconds
        return self._make_request(
            action='ReceiveMessage',
            verb='POST',
            path='/', params=params)

    def remove_permission(self, queue_url, label):
        """
        Revokes any permissions in the queue policy that matches the
        specified `Label` parameter. Only the owner of the queue can
        remove permissions.

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type label: string
        :param label: The identification of the permission to remove. This is
            the label added with the AddPermission action.

        """
        params = {'QueueUrl': queue_url, 'Label': label, }
        return self._make_request(
            action='RemovePermission',
            verb='POST',
            path='/', params=params)

    def send_message(self, queue_url, message_body, delay_seconds=None):
        """
        Delivers a message to the specified queue. With Amazon SQS,
        you now have the ability to send large payload messages that
        are up to 256KB (262,144 bytes) in size. To send large
        payloads, you must use an AWS SDK that supports SigV4 signing.
        To verify whether SigV4 is supported for an AWS SDK, check the
        SDK release notes.

        The following list shows the characters (in Unicode) allowed
        in your message, according to the W3C XML specification. For
        more information, go to `http://www.w3.org/TR/REC-
        xml/#charsets`_ If you send any characters not included in the
        list, your request will be rejected.

        #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] |
        [#x10000 to #x10FFFF]

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type message_body: string
        :param message_body: The message to send. String maximum 256 KB in
            size. For a list of allowed characters, see the preceding important
            note.

        :type delay_seconds: integer
        :param delay_seconds: The number of seconds (0 to 900 - 15 minutes) to
            delay a specific message. Messages with a positive `DelaySeconds`
            value become available for processing after the delay time is
            finished. If you don't specify a value, the default value for the
            queue applies.

        """
        params = {
            'QueueUrl': queue_url,
            'MessageBody': message_body,
        }
        if delay_seconds is not None:
            params['DelaySeconds'] = delay_seconds
        return self._make_request(
            action='SendMessage',
            verb='POST',
            path='/', params=params)

    def send_message_batch(self, queue_url, entries):
        """
        Delivers up to ten messages to the specified queue. This is a
        batch version of SendMessage. The result of the send action on
        each message is reported individually in the response. The
        maximum allowed individual message size is 256 KB (262,144
        bytes).

        The maximum total payload size (i.e., the sum of all a batch's
        individual message lengths) is also 256 KB (262,144 bytes).

        If the `DelaySeconds` parameter is not specified for an entry,
        the default for the queue is used.
        The following list shows the characters (in Unicode) that are
        allowed in your message, according to the W3C XML
        specification. For more information, go to
        `http://www.faqs.org/rfcs/rfc1321.html`_. If you send any
        characters that are not included in the list, your request
        will be rejected.
        #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] |
        [#x10000 to #x10FFFF]
        Because the batch request can result in a combination of
        successful and unsuccessful actions, you should check for
        batch errors even when the call returns an HTTP status code of
        200. Some API actions take lists of parameters. These lists
        are specified using the `param.n` notation. Values of `n` are
        integers starting from 1. For example, a parameter list with
        two elements looks like this:
        `&Attribute.1=this`

        `&Attribute.2=that`

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type entries: list
        :param entries: A list of SendMessageBatchRequestEntry items.

        """
        params = {'QueueUrl': queue_url, }
        self.build_complex_list_params(
            params, entries,
            'Entries.member',
            ('Id', 'MessageBody', 'DelaySeconds'))
        return self._make_request(
            action='SendMessageBatch',
            verb='POST',
            path='/', params=params)

    def set_queue_attributes(self, queue_url, attributes):
        """
        Sets the value of one or more queue attributes.
        Going forward, new attributes might be added. If you are
        writing code that calls this action, we recommend that you
        structure your code so that it can handle new attributes
        gracefully.

        :type queue_url: string
        :param queue_url: The URL of the Amazon SQS queue to take action on.

        :type attributes: map
        :param attributes: A map of attributes to set.
        The following lists the names, descriptions, and values of the special
            request parameters the `SetQueueAttributes` action uses:

        + `DelaySeconds` - The time in seconds that the delivery of all
              messages in the queue will be delayed. An integer from 0 to 900 (15
              minutes). The default for this attribute is 0 (zero).
        + `MaximumMessageSize` - The limit of how many bytes a message can
              contain before Amazon SQS rejects it. An integer from 1024 bytes (1
              KiB) up to 262144 bytes (256 KiB). The default for this attribute
              is 262144 (256 KiB).
        + `MessageRetentionPeriod` - The number of seconds Amazon SQS retains a
              message. Integer representing seconds, from 60 (1 minute) to
              1209600 (14 days). The default for this attribute is 345600 (4
              days).
        + `Policy` - The queue's policy. A valid form-url-encoded policy. For
              more information about policy structure, see `Basic Policy
              Structure`_ in the Amazon SQS Developer Guide . For more
              information about form-url-encoding, see `http://www.w3.org/MarkUp
              /html-spec/html-spec_8.html#SEC8.2.1`_.
        + `ReceiveMessageWaitTimeSeconds` - The time for which a ReceiveMessage
              call will wait for a message to arrive. An integer from 0 to 20
              (seconds). The default for this attribute is 0.
        + `VisibilityTimeout` - The visibility timeout for the queue. An
              integer from 0 to 43200 (12 hours). The default for this attribute
              is 30. For more information about visibility timeout, see
              Visibility Timeout in the Amazon SQS Developer Guide .
        + `RedrivePolicy` - The parameters for dead letter queue functionality
              of the source queue. For more information about RedrivePolicy and
              dead letter queues, see Using Amazon SQS Dead Letter Queues in the
              Amazon SQS Developer Guide .

        """
        params = {'QueueUrl': queue_url, }
        # TODO: NEED TO PROCESS COMPLEX ARG attributes of type map.
        return self._make_request(
            action='SetQueueAttributes',
            verb='POST',
            path='/', params=params)

    def _make_request(self, action, verb, path, params):
        params['ContentType'] = 'JSON'
        response = self.make_request(action=action, verb='POST',
                                     path='/', params=params)
        body = response.read()
        boto.log.debug(body)
        if response.status == 200:
            return json.loads(body)
        else:
            json_body = json.loads(body)
            fault_name = json_body.get('Error', {}).get('Code', None)
            exception_class = self._faults.get(fault_name, self.ResponseError)
            raise exception_class(response.status, response.reason,
                                  body=json_body)


text:
package helpers

import (
	"io/ioutil"
	"strings"
	"talisman/detector/severity"
	mock "talisman/internal/mock/prompt"
	"talisman/prompt"
	"talisman/talismanrc"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/spf13/afero"

	logr "github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
)

func init() {
	logr.SetOutput(ioutil.Discard)
}

func TestNewDetectionResultsAreSuccessful(t *testing.T) {
	results := NewDetectionResults(talismanrc.HookMode)
	assert.True(t, results.Successful(), "New detection result is always expected to succeed")
	assert.False(t, results.HasFailures(), "New detection result is not expected to fail")
}

func TestCallingFailOnDetectionResultsFails(t *testing.T) {
	results := NewDetectionResults(talismanrc.HookMode)
	results.Fail("some_filename", "filename", "Bomb", []string{}, severity.Low)
	assert.False(t, results.Successful(), "Calling fail on a result should not make it succeed")
	assert.True(t, results.HasFailures(), "Calling fail on a result should make it fail")
}

func TestCanRecordMultipleErrorsAgainstASingleFile(t *testing.T) {
	results := NewDetectionResults(talismanrc.HookMode)
	results.Fail("some_filename", "filename", "Bomb", []string{}, severity.Low)
	results.Fail("some_filename", "filename", "Complete & utter failure", []string{}, severity.Low)
	results.Fail("another_filename", "filename", "Complete & utter failure", []string{}, severity.Low)
	assert.Len(t, results.GetFailures("some_filename"), 2, "Expected two errors against some_filename.")
	assert.Len(t, results.GetFailures("another_filename"), 1, "Expected one error against another_filename")
}

func TestResultsReportsFailures(t *testing.T) {
	results := NewDetectionResults(talismanrc.HookMode)
	results.Fail("some_filename", "", "Bomb", []string{}, severity.Low)
	results.Fail("some_filename", "", "Complete & utter failure", []string{}, severity.Low)
	results.Fail("another_filename", "", "Complete & utter failure", []string{}, severity.Low)

	actualErrorReport := results.ReportFileFailures("some_filename")
	firstErrorMessage := strings.Join(actualErrorReport[0], " ")
	secondErrorMessage := strings.Join(actualErrorReport[1], " ")
	finalStringMessage := firstErrorMessage + " " + secondErrorMessage

	assert.Regexp(t, "some_filename", finalStringMessage, "Error report does not contain expected output")
	assert.Regexp(t, "Bomb", finalStringMessage, "Error report does not contain expected output")
	assert.Regexp(t, "Complete & utter failure", finalStringMessage, "Error report does not contain expected output")
}

func TestUpdateResultsSummary(t *testing.T) {
	results := NewDetectionResults(talismanrc.HookMode)
	categories := []string{"filecontent", "filename", "filesize"}

	for _, category := range categories {
		results.updateResultsSummary(category, false)
	}
	assert.Equal(t, 1, results.Summary.Types.Filename)
	assert.Equal(t, 1, results.Summary.Types.Filecontent)
	assert.Equal(t, 1, results.Summary.Types.Filesize)

	for _, category := range categories {
		results.updateResultsSummary(category, true)
	}
	assert.Equal(t, 0, results.Summary.Types.Filename)
	assert.Equal(t, 0, results.Summary.Types.Filecontent)
	assert.Equal(t, 0, results.Summary.Types.Filesize)
}

func TestErrorExitCodeInInteractive(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	prompter := mock.NewMockPrompt(ctrl)
	results := NewDetectionResults(talismanrc.HookMode)

	promptContext := prompt.NewPromptContext(true, prompter)
	prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(2)
	results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
	results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)
	results.Report(promptContext, "default")
	assert.True(t, results.HasFailures())
}

func TestSuccessExitCodeInInteractive(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	prompter := mock.NewMockPrompt(ctrl)
	results := NewDetectionResults(talismanrc.HookMode)

	promptContext := prompt.NewPromptContext(true, prompter)
	prompter.EXPECT().Confirm(gomock.Any()).Return(true).Times(2)
	results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
	results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)
	results.Report(promptContext, "default")
	assert.False(t, results.HasFailures())
}

// Presently not showing the ignored files in the log
// func TestLoggingIgnoredFilesDoesNotCauseFailure(t *testing.T) {
// 	results := NewDetectionResults(talismanrc.HookMode)
// 	results.Ignore("some_file", "some-detector")
// 	results.Ignore("some/other_file", "some-other-detector")
// 	results.Ignore("some_file_ignored_for_multiple_things", "some-detector")
// 	results.Ignore("some_file_ignored_for_multiple_things", "some-other-detector")
// 	assert.True(t, results.Successful(), "Calling ignore should keep the result successful.")
// 	assert.True(t, results.HasIgnores(), "Calling ignore should be logged.")
// 	assert.False(t, results.HasFailures(), "Calling ignore should not cause a result to fail.")

// 	assert.Regexp(t, "some_file was ignored by .talismanrc for the following detectors: some-detector", results.Report(), "foo")
// 	assert.Regexp(t, "some/other_file was ignored by .talismanrc for the following detectors: some-other-detector", results.Report(), "foo")
// 	assert.Regexp(t, "some_file_ignored_for_multiple_things was ignored by .talismanrc for the following detectors: some-detector, some-other-detector", results.Report(), "foo")
// }

func TestTalismanRCSuggestionWhenThereAreFailures(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	prompter := mock.NewMockPrompt(ctrl)
	results := NewDetectionResults(talismanrc.HookMode)

	// Creating temp file with some content
	fs := afero.NewMemMapFs()
	file, err := afero.TempFile(fs, "", "talismanrc")
	assert.NoError(t, err)
	ignoreFile := file.Name()

	talismanrc.SetFs__(fs)
	talismanrc.SetRcFilename__(ignoreFile)

	existingContent := `fileignoreconfig:
- filename: existing.pem
  checksum: 123444ddssa75333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
`
	err = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	assert.NoError(t, err)

	// The tests below depend on the upper configuration which is shared across all three of them. Hence the order in
	// which they run matters.
	t.Run("should not prompt if there are no failures", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(true, prompter)
		prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(0)

		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, existingContent, string(bytesFromFile))
	})

	_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	t.Run("when user declines, entry should not be added to talismanrc", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(true, prompter)
		prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(false)
		results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)

		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, existingContent, string(bytesFromFile))
	})

	_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	t.Run("when interactive flag is set to false, it should not ask user", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(false, prompter)
		prompter.EXPECT().Confirm(gomock.Any()).Return(false).Times(0)
		results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)

		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, existingContent, string(bytesFromFile))
	})

	_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	t.Run("when user confirms, entry should be appended to given ignore file", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(true, prompter)
		prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(true)

		results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)

		expectedFileContent := `fileignoreconfig:
- filename: some_file.pem
  checksum: 87139cc4d975333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
version: "1.0"
`
		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, expectedFileContent, string(bytesFromFile))
	})

	_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	t.Run("when user confirms, entry for existing file should updated", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(true, prompter)
		prompter.EXPECT().Confirm("Do you want to add existing.pem with above checksum in talismanrc ?").Return(true)
		results := NewDetectionResults(talismanrc.HookMode)
		results.Fail("existing.pem", "filecontent", "This will bomb!", []string{}, severity.Low)

		expectedFileContent := `fileignoreconfig:
- filename: existing.pem
  checksum: 5bc0b0692a316bb2919263addaef0ffba3a21b9e1cca62a1028390e97e861e4e
version: "1.0"
`
		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, expectedFileContent, string(bytesFromFile))
	})

	_ = afero.WriteFile(fs, ignoreFile, []byte(existingContent), 0666)
	t.Run("when user confirms for multiple entries, they should be appended to given ignore file", func(t *testing.T) {
		promptContext := prompt.NewPromptContext(true, prompter)
		prompter.EXPECT().Confirm("Do you want to add some_file.pem with above checksum in talismanrc ?").Return(true)
		prompter.EXPECT().Confirm("Do you want to add another.pem with above checksum in talismanrc ?").Return(true)

		results.Fail("some_file.pem", "filecontent", "Bomb", []string{}, severity.Low)
		results.Fail("another.pem", "filecontent", "password", []string{}, severity.Low)

		expectedFileContent := `fileignoreconfig:
- filename: another.pem
  checksum: 117e23557c02cbd472854ebce4933d6daec1fd207971286f6ffc9f1774c1a83b
- filename: some_file.pem
  checksum: 87139cc4d975333b25b6275f97680604add51b84eb8f4a3b9dcbbc652e6f27ac
version: "1.0"
`
		results.Report(promptContext, "default")
		bytesFromFile, err := afero.ReadFile(fs, ignoreFile)

		assert.NoError(t, err)
		assert.Equal(t, expectedFileContent, string(bytesFromFile))
	})

	err = fs.Remove(ignoreFile)
	assert.NoError(t, err)
}


text:
package ru.playsoftware.j2meloader.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.nononsenseapps.filepicker.FilePickerActivity;

import ru.playsoftware.j2meloader.filepicker.FilteredFilePickerActivity;

public class PickFileResultContract extends ActivityResultContract<String, Uri> {
	@NonNull
	@Override
	public Intent createIntent(@NonNull Context context, String input) {
		Intent i = new Intent(context, FilteredFilePickerActivity.class);
		i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
		i.putExtra(FilePickerActivity.EXTRA_SINGLE_CLICK, true);
		i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
		i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);
		i.putExtra(FilePickerActivity.EXTRA_START_PATH, input);
		return i;
	}

	@Override
	public Uri parseResult(int resultCode, @Nullable Intent intent) {
		if (resultCode == Activity.RESULT_OK && intent != null) {
			return intent.getData();
		}
		return null;
	}
}


text:
FROM mcr.microsoft.com/windows:1809

USER ContainerAdministrator
# Install .NET 4.8
RUN curl -fSLo dotnet-framework-installer.exe https://download.visualstudio.microsoft.com/download/pr/7afca223-55d2-470a-8edc-6a1739ae3252/abd170b4b0ec15ad0222a809b761a036/ndp48-x86-x64-allos-enu.exe `
    && .\dotnet-framework-installer.exe /q `
    && del .\dotnet-framework-installer.exe `
    && powershell Remove-Item -Force -Recurse ${Env:TEMP}\*

# Apply latest patch
RUN curl -fSLo patch.msu http://download.windowsupdate.com/d/msdownload/update/software/secu/2020/05/windows10.0-kb4552930-x64-ndp48_3fb9f9a7b72e49707c8c49b4febc171411eca05f.msu `
    && mkdir patch `
    && expand patch.msu patch -F:* `
    && del /F /Q patch.msu `
    && DISM /Online /Quiet /Add-Package /PackagePath:C:\patch\windows10.0-kb4552930-x64-ndp48.cab `
    && rmdir /S /Q patch

# ngen .NET Fx
ENV COMPLUS_NGenProtectedProcess_FeatureEnabled 0
RUN \Windows\Microsoft.NET\Framework64\v4.0.30319\ngen uninstall "Microsoft.Tpm.Commands, Version=10.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=amd64" `
    && \Windows\Microsoft.NET\Framework64\v4.0.30319\ngen update `
    && \Windows\Microsoft.NET\Framework\v4.0.30319\ngen update


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using AutoMapper;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.Resources.Models;
using MNM = Microsoft.Azure.Management.Network.Models;

namespace Microsoft.Azure.Commands.Network
{
    [Cmdlet(VerbsCommon.Set, "AzureVirtualNetworkGatewayConnectionSharedKey"), OutputType(typeof(string))]
    public class NewAzureVirtualNetworkGatewayConnectionSharedKeyCommand : VirtualNetworkGatewayConnectionBaseCmdlet
    {
        [Alias("ResourceName")]
        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The resource name.")]
        [ValidateNotNullOrEmpty]
        public virtual string Name { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The resource group name.")]
        [ValidateNotNullOrEmpty]
        public virtual string ResourceGroupName { get; set; }

        [Parameter(
         Mandatory = true,
         ValueFromPipelineByPropertyName = true,
         HelpMessage = "The virtual network connection shared key value.")]
        [ValidateNotNullOrEmpty]
        public string Value { get; set; }

        [Parameter(
            Mandatory = false,
            HelpMessage = "Do not ask for confirmation if you want to overrite a resource")]
        public SwitchParameter Force { get; set; }

        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (this.IsVirtualNetworkGatewayConnectionSharedKeyPresent(this.ResourceGroupName, this.Name))
            {
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResource, Name),
                    Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResourceMessage,
                    Name,
                    () => SetVirtualNetworkGatewayConnectionSharedKey());

                WriteObject(this.GetVirtualNetworkGatewayConnectionSharedKey(this.ResourceGroupName, this.Name));
            }
            else
            {
                var virtualNetworkGatewayConnectionSharedKey = SetVirtualNetworkGatewayConnectionSharedKey();

                WriteObject(virtualNetworkGatewayConnectionSharedKey);
            }
        }

        private string SetVirtualNetworkGatewayConnectionSharedKey()
        {
            var vnetGatewayConnectionSharedKey = new PSConnectionSharedKey();
            vnetGatewayConnectionSharedKey.Value = Value;

            // Map to the sdk object
            var vnetGatewayConnectionSharedKeyModel = Mapper.Map<MNM.ConnectionSharedKey>(vnetGatewayConnectionSharedKey);

            // Execute the Set VirtualNetworkConnectionSharedKey call
            this.VirtualNetworkGatewayConnectionClient.SetSharedKey(this.ResourceGroupName, this.Name, vnetGatewayConnectionSharedKeyModel);

            var getVirtualNetworkGatewayConnectionSharedKey = this.GetVirtualNetworkGatewayConnectionSharedKey(this.ResourceGroupName, this.Name);

            return getVirtualNetworkGatewayConnectionSharedKey;
        }
    }
}


text:
@interface PodsDummy_Pods_MantleExtension : NSObject
@end
@implementation PodsDummy_Pods_MantleExtension
@end


text:
<?php

namespace Google\Service\DisplayVideo;

class InventorySourceFilter extends \Google\Collection
{
  protected $collection_key = 'inventorySourceIds';
  /**
   * @var string[]
   */
  public $inventorySourceIds;

  /**
   * @param string[]
   */
  public function setInventorySourceIds($inventorySourceIds)
  {
    $this->inventorySourceIds = $inventorySourceIds;
  }
  /**
   * @return string[]
   */
  public function getInventorySourceIds()
  {
    return $this->inventorySourceIds;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(InventorySourceFilter::class, 'Google_Service_DisplayVideo_InventorySourceFilter');


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ApiPassword',
            fields=[
                ('apiID', models.AutoField(primary_key=True, serialize=False)),
                ('apiName', models.TextField()),
                ('apiPassword', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='QuesSet_v2',
            fields=[
                ('questionID', models.AutoField(primary_key=True, serialize=False)),
                ('questionDate', models.DateTimeField()),
                ('questionSet', models.TextField()),
                ('questionTimeStamp', models.IntegerField()),
                ('questionEndStamp', models.IntegerField()),
                ('questionBoutEndStamp', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='rankingSet',
            fields=[
                ('resultNumber', models.AutoField(primary_key=True, serialize=False)),
                ('questionID', models.IntegerField()),
                ('userName', models.CharField(max_length=255)),
                ('userScore', models.FloatField()),
                ('correctans', models.IntegerField(blank=True, null=True)),
                ('wrongans', models.IntegerField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Top10Model',
            fields=[
                ('rID', models.AutoField(primary_key=True, serialize=False)),
                ('questionID', models.IntegerField()),
                ('top10User', models.TextField()),
            ],
        ),
    ]


text:
{-# LANGUAGE DeriveGeneric, ScopedTypeVariables, OverloadedStrings #-}
module Main(main) where

import qualified Criterion.Main as C
import GHC.Generics (Generic)
import qualified Data.Text as S
import qualified Data.Text.Lazy.Builder as B
import qualified Data.Text.Lazy as T
import qualified Data.Text.Serialize as T
import Data.Typeable

import Debug.Trace
import Test.QuickCheck.Arbitrary(Arbitrary(..))
import Test.QuickCheck.Gen(Gen(..))
import System.Random

import Data.Monoid

severalBufSize = 10^3
size = 10^3
__ = undefined
seed = 0

{-# INLINABLE customBench #-}
customBench :: (Typeable a, T.Show a, Show a) => a -> C.Benchmark
customBench value = C.bgroup (show (typeOf value)) [
  C.bgroup "single" [
     C.bench "String" $ C.nf (T.pack . show) value,
     C.bench "Builder" $ C.nf (B.toLazyText . T.show) value
     ],
  C.bgroup "many" [
    C.bench "String" $ C.nf (T.pack . showMany n) value,
    C.bench "Builder" $ C.nf (B.toLazyText . showManyT n) value
    ]
  ]
  where n = severalBufSize `div` length (show value) + 1 :: Int

showMany 0 val = ""
showMany n val = shows val (showMany (n-1) val)
{-# INLINABLE showMany #-}

showManyT 0 val = mempty
showManyT n val = T.show val <> showManyT (n-1) val
{-# INLINABLE showManyT #-}

{-# INLINABLE bench #-}
bench :: forall a. (Arbitrary a, Typeable a, T.Show a, Show a) => a -> C.Benchmark
bench _ = customBench (unGen arbitrary (mkStdGen seed) size :: a)

main = C.defaultMain [
  bench (__ :: Double),
  bench (__ :: Int),
  customBench ("123456" :: String),
  bench (__ :: Bool),
  bench (__ :: [Bool]),
  bench (__ :: [Double]),
  bench (__ :: [Int]),
  bench (__ :: Char),
  bench (["123456","789012"] :: [String]),
  customBench ("123456" :: T.Text),
  customBench ("123456" :: S.Text),
  bench (__ :: Either Int Int),
  bench (__ :: ()),
  bench (__ :: [()]),
  bench (__ :: ((),())),
  bench (__ :: (Int, Int)),
  bench (__ :: [(Int, Int)])
  ]


text:
@interface DopeLock : UIView <UITableViewDelegate, UITableViewDataSource>
{
    UIView *_topView;
    UILabel *_h1;
    UILabel *_h2;
    UILabel *_ncToday;
    UILabel *_ncTomorrow;
    UIView *_todayTomorrowView;
    UILabel *_todayTomorrow;
    UILabel *_todayDate;
    UILabel *_calendarLabel;
    UIView *_separator;
    UIVisualEffectView *_blurEffectView1;
    UIVisualEffectView *_blurEffectView2;
    NSString *_todayNCText;
    NSString *_todayAltNCText;
    NSString *_tomorrowNCText;
    UIView *_eventView;
    UIView *_eventViewDay0;
    UIView *_eventViewDay1;
    UIView *_eventViewDay2;
    UIView *_eventViewDay3;
    UIView *_eventViewDay4;
    UIView *_eventViewDay5;
    UIView *_eventViewDay6;
    UILabel *_eventDescription;
    UIView *_eventBlocView;
    UILabel *_eventBlockName;
    UIBlurEffect *_effect1;
    UIBlurEffect *_effect2;
    UIBlurEffect *_effect3;
    NSMutableArray *_events0;
    NSMutableArray *_events1;
    NSMutableArray *_events2;
    NSMutableArray *_events3;
    NSMutableArray *_events4;
    NSMutableArray *_events5;
    NSMutableArray *_events6;
    NSString *_user;
}
@property(nonatomic) BOOL militaryTime;
@property(nonatomic) BOOL fullBlur;
@property(nonatomic) BOOL textColor;
@property(retain, nonatomic) UIView *topView;
@property(copy, nonatomic) NSString *user;
@property(retain, nonatomic) UILabel *h1;
@property(retain, nonatomic) UILabel *h2;
@property(retain, nonatomic) UILabel *ncToday;
@property(retain, nonatomic) UILabel *ncTomorrow;
@property(retain, nonatomic) UIView *todayTomorrowView;
@property(retain, nonatomic) UILabel *todayTomorrow;
@property(retain, nonatomic) UILabel *todayDate;
@property(retain, nonatomic) UILabel *calendarLabel;
@property(retain, nonatomic) UIView *separator;
@property(retain, nonatomic) UIVisualEffectView *blurEffectView1;
@property(retain, nonatomic) UIVisualEffectView *blurEffectView2;
@property(copy, nonatomic) NSString *todayNCText;
@property(copy, nonatomic) NSString *todayAltNCText;
@property(copy, nonatomic) NSString *tomorrowNCText;
@property(retain, nonatomic) UIView *eventView;
@property(retain, nonatomic) UIView *eventViewDay0;
@property(retain, nonatomic) UIView *eventViewDay1;
@property(retain, nonatomic) UIView *eventViewDay2;
@property(retain, nonatomic) UIView *eventViewDay3;
@property(retain, nonatomic) UIView *eventViewDay4;
@property(retain, nonatomic) UIView *eventViewDay5;
@property(retain, nonatomic) UIView *eventViewDay6;
@property(retain, nonatomic) UIScrollView *eventDescription0;
@property(retain, nonatomic) UIScrollView *eventDescription1;
@property(retain, nonatomic) UIScrollView *eventDescription2;
@property(retain, nonatomic) UIScrollView *eventDescription3;
@property(retain, nonatomic) UIScrollView *eventDescription4;
@property(retain, nonatomic) UIScrollView *eventDescription5;
@property(retain, nonatomic) UIScrollView *eventDescription6;
@property(retain, nonatomic) UIView *eventBlocView;
@property(retain, nonatomic) UILabel *eventBlockName;
@property(retain, nonatomic) UIBlurEffect *effect1;
@property(retain, nonatomic) UIBlurEffect *effect2;
@property(retain, nonatomic) UIBlurEffect *effect3;

-(void)addBasicsToView;
-(void)updateView;
-(void)rotateView;
-(void)updateTodayTomorrow:(NSMutableArray *)arg1;
-(void)randomGreeting;
-(void)drawBackgroundForEvents:(int)dayNumber date:(NSDate *)dateToDraw view:(UIView **)eventView;
-(UIView *)drawGridView;

@end


text:
import React from "react"
import ReactDOM from "react-dom"
import { App } from "./App"
import { buildClientApp } from "v2/Artsy/Router/client"
import { routes } from "./routes"

const { pathname } = window.location

if (pathname === "/ssr-experiments/router") {
  buildClientApp({ routes })
    .then(({ ClientApp }) => {
      ReactDOM.hydrate(<ClientApp />, document.getElementById("react-root"))
    })
    .catch(error => {
      console.error(error)
    })
} else if (pathname === "/ssr-experiments/all") {
  buildClientApp({ routes })
    .then(({ ClientApp }) => {
      ReactDOM.hydrate(<ClientApp />, document.getElementById("react-root"))
    })
    .catch(error => {
      console.error(error)
    })
} else {
  ReactDOM.hydrate(<App />, document.getElementById("react-root"))
}