text:
import ioc_et

def make_dnsentryitem_recordname(dns_name, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for DnsEntryItem/RecordName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'DnsEntryItem'
    search = 'DnsEntryItem/RecordName'
    content_type = 'string'
    content = dns_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_driveritem_deviceitem_devicename(device_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for DriverItem/DeviceItem/DeviceName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'DriverItem'
    search = 'DriverItem/DeviceItem/DeviceName'
    content_type = 'string'
    content = device_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_driveritem_drivername(driver_name, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for DriverItem/DriverName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'DriverItem'
    search = 'DriverItem/DriverName'
    content_type = 'string'
    content = driver_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_eventlogitem_eid(eid, condition='is', negate=False):
    '''
    Create a node for EventLogItem/EID

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'EventLogItem'
    search = 'EventLogItem/EID'
    content_type = 'int'
    content = eid
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_eventlogitem_log(log, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for EventLogItem/log

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'EventLogItem'
    search = 'EventLogItem/log'
    content_type = 'string'
    content = log
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_eventlogitem_message(message, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for EventLogItem/message

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'EventLogItem'
    search = 'EventLogItem/message'
    content_type = 'string'
    content = message
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_fileattributes(attributes, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/FileAttributes

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/FileAttributes'
    content_type = 'string'
    content = attributes
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_fileextension(extension, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/FileExtension

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/FileExtension'
    content_type = 'string'
    content = extension
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_filename(filename, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/FileName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/FileName'
    content_type = 'string'
    content = filename
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_filepath(filepath, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/FilePath

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/FilePath'
    content_type = 'string'
    content = filepath
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_fullpath(fullpath, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/FullPath

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/FullPath'
    content_type = 'string'
    content = fullpath
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_md5sum(md5, condition='is', negate=False):
    '''
    Create a node for FileItem/Md5sum

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/Md5sum'
    content_type = 'md5'
    content = md5
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_peinfo_detectedanomalies_string(anomaly, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/DetectedAnomalies/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/DetectedAnomalies/string'
    content_type = 'string'
    content = anomaly
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_detectedentrypointsignature_name(entrypoint_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/DetectedEntryPointSignature/Name'
    content_type = 'string'
    content = entrypoint_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_digitalsignature_signatureexists(sig_exists, condition='is', negate=False):
    '''
    Create a node for FileItem/PEInfo/DigitalSignature/SignatureExists

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/DigitalSignature/SignatureExists'
    content_type = 'bool'
    content = sig_exists
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_peinfo_digitalsignature_signatureverified(sig_verified, condition='is', negate=False):
    '''
    Create a node for FileItem/PEInfo/DigitalSignature/SignatureVerified

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/DigitalSignature/SignatureVerified'
    content_type = 'bool'
    content = sig_verified
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_peinfo_exports_dllname(dll_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/Exports/DllName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/Exports/DllName'
    content_type = 'string'
    content = dll_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_exports_exportedfunctions_string(export_function, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/Exports/ExportedFunctions/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/Exports/ExportedFunctions/string'
    content_type = 'string'
    content = export_function
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_exports_numberoffunctions(function_count, condition='is', negate=False):
    '''
    Create a node for FileItem/PEInfo/Exports/NumberOfFunctions

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/Exports/NumberOfFunctions'
    content_type = 'int'
    content = function_count
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_peinfo_importedmodules_module_importedfunctions_string(imported_function, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string'
    content_type = 'string'
    content = imported_function
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_importedmodules_module_name(imported_module, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/ImportedModules/Module/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/ImportedModules/Module/Name'
    content_type = 'string'
    content = imported_module
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_petimestamp(compile_time, condition='is', negate=False):
    '''
    Create a node for FileItem/PEInfo/PETimeStamp

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/PETimeStamp'
    content_type = 'date'
    content = compile_time
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_peinfo_resourceinfolist_resourceinfoitem_name(resource_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/ResourceInfoList/ResourceInfoItem/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/ResourceInfoList/ResourceInfoItem/Name'
    content_type = 'string'
    content = resource_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_sections_section_name(section_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/Sections/Section/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/Sections/Section/Name'
    content_type = 'string'
    content = section_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_type(type, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/Type

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/Type'
    content_type = 'string'
    content = type
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_sizeinbytes(filesize, condition='is', negate=False):
    '''
    Create a node for FileItem/SizeInBytes

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/SizeInBytes'
    content_type = 'int'
    content = filesize
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_fileitem_streamlist_stream_name(stream_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/StreamList/Stream/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/StreamList/Stream/Name'
    content_type = 'string'
    content = stream_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_stringlist_string(file_string, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/StringList/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/StringList/string'
    content_type = 'string'
    content = file_string
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_username(file_owner, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for FileItem/Username

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/Username'
    content_type = 'string'
    content = file_owner
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_hookitem_hookedfunction(hooked_function, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for HookItem/HookedFunction

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'HookItem'
    search = 'HookItem/HookedFunction'
    content_type = 'string'
    content = hooked_function
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_hookitem_hookingmodule(hooking_module, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for HookItem/HookingModule

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'HookItem'
    search = 'HookItem/HookingModule'
    content_type = 'string'
    content = hooking_module
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_portitem_remoteip(remote_ip, condition='is', negate=False):
    '''
    Create a node for PortItem/remoteIP

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'PortItem'
    search = 'PortItem/remoteIP'
    content_type = 'IP'
    content = remote_ip
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_portitem_remoteport(remote_port, condition='is', negate=False):
    '''
    Create a node for PortItem/remotePort

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'PortItem'
    search = 'PortItem/remotePort'
    content_type = 'int'
    content = remote_port
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_prefetchitem_accessedfilelist_accessedfile(accessed_file, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for PrefetchItem/AccessedFileList/AccessedFile

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'PrefetchItem'
    search = 'PrefetchItem/AccessedFileList/AccessedFile'
    content_type = 'string'
    content = accessed_file
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_prefetchitem_applicationfilename(application_filename, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for PrefetchItem/ApplicationFileName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'PrefetchItem'
    search = 'PrefetchItem/ApplicationFileName'
    content_type = 'string'
    content = application_filename
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_prefetchitem_applicationfullpath(application_fullpath, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for PrefetchItem/ApplicationFullPath

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'PrefetchItem'
    search = 'PrefetchItem/ApplicationFullPath'
    content_type = 'string'
    content = application_fullpath
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_handlelist_handle_name(handle_name, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/HandleList/Handle/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/HandleList/Handle/Name'
    content_type = 'string'
    content = handle_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_portlist_portitem_remoteip(remote_ip, condition='is', negate=False):
    '''
    Create a node for ProcessItem/PortList/PortItem/remoteIP

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/PortList/PortItem/remoteIP'
    content_type = 'IP'
    content = remote_ip
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_processitem_sectionlist_memorysection_name(section_name, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/SectionList/MemorySection/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/SectionList/MemorySection/Name'
    content_type = 'string'
    content = section_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_sectionlist_memorysection_peinfo_exports_exportedfunctions_string(export_function, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string'
    content_type = 'string'
    content = export_function
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_stringlist_string(string, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/StringList/string

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/StringList/string'
    content_type = 'string'
    content = string
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_username(username, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/Username

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/Username'
    content_type = 'string'
    content = username
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_arguments(arguments, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/arguments

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/arguments'
    content_type = 'string'
    content = arguments
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_name(name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/name'
    content_type = 'string'
    content = name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_processitem_path(path, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ProcessItem/path

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ProcessItem'
    search = 'ProcessItem/path'
    content_type = 'string'
    content = path
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_registryitem_keypath(keypath, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for RegistryItem/KeyPath

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'RegistryItem'
    search = 'RegistryItem/KeyPath'
    content_type = 'string'
    content = keypath
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_registryitem_path(path, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for RegistryItem/Path

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'RegistryItem'
    search = 'RegistryItem/Path'
    content_type = 'string'
    content = path
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_registryitem_text(text, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for RegistryItem/Text

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'RegistryItem'
    search = 'RegistryItem/Text'
    content_type = 'string'
    content = text
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_registryitem_valuename(valuename, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for RegistryItem/ValueName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'RegistryItem'
    search = 'RegistryItem/ValueName'
    content_type = 'string'
    content = valuename
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_description(description, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ServiceItem/description

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/description'
    content_type = 'string'
    content = description
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_descriptivename(descriptive_name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for ServiceItem/descriptiveName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/descriptiveName'
    content_type = 'string'
    content = descriptive_name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_name(name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for ServiceItem/name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/name'
    content_type = 'string'
    content = name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_path(path, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ServiceItem/path

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/path'
    content_type = 'string'
    content = path
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_pathmd5sum(path_md5, condition='is', negate=False):
    '''
    Create a node for ServiceItem/pathmd5sum

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/pathmd5sum'
    content_type = 'md5'
    content = path_md5
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for ServiceItem/serviceDLL

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/serviceDLL'
    content_type = 'string'
    content = servicedll
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_serviceitem_servicedllsignatureexists(dll_sig_exists, condition='is', negate=False):
    '''
    Create a node for ServiceItem/serviceDLLSignatureExists

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/serviceDLLSignatureExists'
    content_type = 'bool'
    content = dll_sig_exists
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_serviceitem_servicedllsignatureverified(dll_sig_verified, condition='is', negate=False):
    '''
    Create a node for ServiceItem/serviceDLLSignatureVerified

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/serviceDLLSignatureVerified'
    content_type = 'bool'
    content = dll_sig_verified
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_serviceitem_servicedllmd5sum(servicedll_md5, condition='is', negate=False):
    '''
    Create a node for ServiceItem/serviceDLLmd5sum

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'ServiceItem'
    search = 'ServiceItem/serviceDLLmd5sum'
    content_type = 'md5'
    content = servicedll_md5
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate)
    return IndicatorItem_node

def make_systeminfoitem_hostname(hostname, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for SystemInfoItem/hostname

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'SystemInfoItem'
    search = 'SystemInfoItem/hostname'
    content_type = 'string'
    content = hostname
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_systemrestoreitem_originalfilename(original_filename, condition='contains', negate=False, preserve_case = False):
    '''
    Create a node for SystemRestoreItem/OriginalFileName

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'SystemRestoreItem'
    search = 'SystemRestoreItem/OriginalFileName'
    content_type = 'string'
    content = original_filename
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_taskitem_name(name, condition='is', negate=False, preserve_case = False):
    '''
    Create a node for TaskItem/Name

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'TaskItem'
    search = 'TaskItem/Name'
    content_type = 'string'
    content = name
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node

def make_fileitem_peinfo_versioninfoitem(key, value, condition = 'is', negate = False, preserve_case = False):
    '''
    Create a node for FileItem/PEInfo/VersionInfoList/VersionInfoItem/ + key name

    No validation of the key is performed.

    Returns a IndicatorItem represented as an Element node
    '''
    document = 'FileItem'
    search = 'FileItem/PEInfo/VersionInfoList/VersionInfoItem/' + key #XXX: No validation of key done.
    content_type = 'string'
    content = value
    IndicatorItem_node = ioc_et.make_IndicatorItem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case)
    return IndicatorItem_node


text:
import { Bonfire } from './../../lib/Index'
import { Errors } from './../../lib/utils/Errors'
import { ITask } from '../../lib/descriptors/ITask'
import { ShadowFirebase } from './../resources/shadows/firebase/ShadowFirebase'
import * as Chai from 'chai'
import * as ChaiPromise from 'chai-as-promised'
import * as Firebase from 'firebase-admin'

describe('Bonfire Test Suite:', () => {

    // Attach ChaiPromise to the global scope.
    Chai.use(ChaiPromise)
    const expect: Chai.ExpectStatic = Chai.expect

    beforeAll(() => {
        const FirebaseApp = new ShadowFirebase()
        this.ShadowFirebase = FirebaseApp
    })

    /**
     * Validate the Job implementation of the ITask interface.
     */
    describe('Job Validation:', () => {

        describe('Instantiating a new Bonfire Job object:', () => {
            it('should raise an error when a null or empty key is provided', () => {

                // Validate a null key.
                expect(() => {
                    new Bonfire.Job(
                        null,
                        null,
                        null
                    )
                }).to.throw(Error, Errors.INVALID_TASK_KEY)

                // Validate an empty string
                expect(() => {
                    new Bonfire.Job(
                        '',
                        null,
                        null
                    )
                }).to.throw(Error, Errors.INVALID_TASK_KEY)
            })
            it('should raise an error when a null or empty type is provided', () => {

                // Validate a null type.
                expect(() => {
                    new Bonfire.Job(
                        'test_key',
                        null,
                        null
                    )
                }).to.throw(Error, Errors.INVALID_TASK_TYPE)

                // Validate a empty string.
                expect(() => {
                    new Bonfire.Job(
                        'test_key',
                        '',
                        null
                    )
                }).to.throw(Error, Errors.INVALID_TASK_TYPE)
            })
            it('should raise an error when a null date is provided', () => {
                expect(() => {
                    new Bonfire.Job(
                        'test_key',
                        'TAG_SIMPLE_JOB',
                        null
                    )
                }).to.throw(Error, Errors.INVALID_TASK_DATE)
            })
        })

        describe('Instantiating a Bonfire Job from a JSON object:', () => {
            it('should assign the key, type, and scheduled date', () => {
                const date: number = new Date(Date.now() + 60000).getTime()

                const jobData: any = {
                    'id': 'test_key',
                    'tag': 'TAG_SIMPLE_JOB',
                    'scheduled_date_time': date
                }

                let job: Bonfire.Job = null

                expect(() => {
                    job = Bonfire.Job.fromJson(jobData)
                }).to.not.throw()

                expect(job).to.not.be.null

                expect(job.getKey()).to.equal('test_key')
                expect(job.getType()).to.equal(Bonfire.Job.TASK_TYPE)
                expect(job.getTag()).to.equal('TAG_SIMPLE_JOB')
                expect(job.getScheduledDateTime().getTime()).to.equal(date)
                expect(job.getPayload()).to.be.undefined
            })
            it('and also assign a payload if one is provided', () => {
                const date: number = new Date(Date.now() + 60000).getTime()

                const jobData: any = {
                    'id': 'test_key',
                    'tag': 'TAG_SIMPLE_JOB',
                    'type': Bonfire.Job.TASK_TYPE,
                    'scheduled_date_time': date,
                    'payload': {
                        'test': 'hello_world'
                    }
                }

                let job: Bonfire.Job = null

                expect(() => {
                    job = Bonfire.Job.fromJson(jobData)
                }).to.not.throw()

                expect(job).to.not.be.null

                expect(job.getKey()).to.equal('test_key')
                expect(job.getType()).to.equal(Bonfire.Job.TASK_TYPE)
                expect(job.getTag()).to.equal('TAG_SIMPLE_JOB')
                expect(job.getScheduledDateTime().getTime()).to.equal(date)
                expect(JSON.stringify(job.getPayload())).to.equal(JSON.stringify({
                    'test': 'hello_world'
                }))
            })
        })

    })

    describe('Scheduler:', () => {

        describe('Creating a scheduler:', () => {
            it('should complete gracefully when a valid database ref is provided.', () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase

                expect(() => {
                    new Bonfire.Scheduler(FirebaseApp.database().ref('jobs'), (key: string, job: Bonfire.Job) => { })
                }).not.to.throw()
            })
            it('should raise an error when an invalid ref is provided.', () => {
                expect(() => {
                    // Null is not a valid geofire ref.
                    new Bonfire.Scheduler(null, (key: string, job: Bonfire.Job) => { })
                }).to.throw()
            })
            it('should queue any jobs that already exist as children in the ref provided.', async (done) => {

                const FirebaseApp: ShadowFirebase = this.ShadowFirebase

                await FirebaseApp.database().ref('jobs').set({
                    'test_key': {
                        'id': 'test_key_1',
                        'tag': 'TAG_SIMPLE_JOB',
                        'type': Bonfire.Job.TASK_TYPE,
                        'scheduled_date_time': new Date(Date.now() + 360000).getTime()
                    }
                }, () => { })

                const scheduler: Bonfire.Scheduler = new Bonfire.Scheduler(FirebaseApp.database().ref('jobs'), (key: string, job: Bonfire.Job) => { })

                await new Promise<any>(resolve => setTimeout(resolve, 2000))

                expect(scheduler.getPendingCount()).to.equal(1)

                done()
            })
        })

        describe('Scheduling a job:', () => {
            beforeEach(() => {
                const FirebaseApp: ShadowFirebase = new ShadowFirebase()
                this.ShadowFirebase = FirebaseApp
                this.Scheduler = new Bonfire.Scheduler(FirebaseApp.database().ref('jobs'), (key: string, job: Bonfire.Job) => { })
            })

            it('should raise an error when a jobitem with an date/time in the past is provided', () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = this.Scheduler

                return expect(Scheduler.schedule(new Bonfire.Job(
                    'test_key',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() - 360000)
                ))).to.eventually.be.rejectedWith(Errors.SCHEDULED_IN_PAST)
            })
            it('should create, queue and return the same BonfireJob if there was no existing key', async () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = this.Scheduler

                const job: Bonfire.Job = new Bonfire.Job(
                    'test_key_1',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() + 360000)
                )

                expect(Scheduler.getPendingCount()).to.equal(0)

                let jobRes: ITask = await Scheduler.schedule(job)
                expect(jobRes).to.be.an.instanceOf(Bonfire.Job)
                expect(jobRes).to.equal(job)

                expect(Scheduler.getPendingCount()).to.equal(1)
            })
            it('should return the existing job if the job already exists within the firebase RD', async () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = this.Scheduler

                const job: Bonfire.Job = new Bonfire.Job(
                    'test_key_1',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() + 360000)
                )

                const jobTwo: Bonfire.Job = new Bonfire.Job(
                    'test_key_1',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() + 720000)
                )

                expect(Scheduler.getPendingCount()).to.equal(0)

                let jobRes: ITask = await Scheduler.schedule(job)
                expect(jobRes).to.be.an.instanceOf(Bonfire.Job)
                expect(jobRes).to.equal(job)
                expect(Scheduler.getPendingCount()).to.equal(1)

                let jobResTwo: ITask = await Scheduler.schedule(jobTwo)
                expect(jobResTwo).to.be.an.instanceOf(Bonfire.Job)
                expect(jobResTwo).to.not.equal(jobTwo)
                expect(Scheduler.getPendingCount()).to.equal(1)
            })
        })

        describe('Cancelling a job:', () => {

            beforeEach(() => {
                const FirebaseApp: ShadowFirebase = new ShadowFirebase()
                this.ShadowFirebase = FirebaseApp
                this.Scheduler = new Bonfire.Scheduler(FirebaseApp.database().ref('jobs'), (key: string, job: Bonfire.Job) => { })
            })

            it('should complete gracefully if the key does not exist.', () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = this.Scheduler

                return expect(Scheduler.cancel('test_key')).to.eventually.be.fulfilled
            })
            it('remove and cancel an existing job when provided a key that exists', async () => {
                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = this.Scheduler

                const job: Bonfire.Job = new Bonfire.Job(
                    'test_key',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() + 360000)
                )

                expect(Scheduler.getPendingCount()).to.equal(0)

                let jobRes: ITask = await Scheduler.schedule(job)
                expect(jobRes).to.be.an.instanceOf(Bonfire.Job)
                expect(jobRes).to.equal(job)

                expect(Scheduler.getPendingCount()).to.equal(1)

                await Scheduler.cancel('test_key')

                expect(Scheduler.getPendingCount()).to.equal(0)
            })
        })

        describe('Job completion handler:', () => {
            beforeEach(() => {
                const FirebaseApp: ShadowFirebase = new ShadowFirebase()
                this.ShadowFirebase = FirebaseApp
            })

            it('should be invoked when a one-time job is executed', async () => {

                const queue: Array<string> = new Array<string>()

                const FirebaseApp: ShadowFirebase = this.ShadowFirebase
                const Scheduler: Bonfire.Scheduler = new Bonfire.Scheduler(FirebaseApp.database().ref('jobs'), (key: string, job: Bonfire.Job) => {
                    queue.push(key)
                })

                expect(queue).to.have.length(0)

                await Scheduler.schedule(new Bonfire.Job(
                    'test_key',
                    'TAG_SIMPLE_JOB',
                    new Date(Date.now() + 1000)
                ))

                await new Promise<any>(resolve => setTimeout(resolve, 2000))

                expect(queue).to.have.length(1)
                expect(queue[0]).to.equal('test_key')
            })
        })
    })

})

redpajama_set_name: RedPajamaGithub


text:
const scroll = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  (callback => window.setTimeout(callback, 1000 / 60));

/**
 * The `ScrollListener` class sets up a listener that handles window scroll
 * events.
 */
export default class ScrollListener {
  /**
   * @param {Function} callback The callback to run when the scroll position
   *     changes.
   * @public
   */
  constructor(callback) {
    this.callback = callback;
    this.lastTop = -1;
  }

  /**
   * On each animation frame, as long as the listener is active, run the
   * `update` method.
   *
   * @protected
   */
  loop() {
    if (!this.active) return;

    this.update();

    scroll(this.loop.bind(this));
  }

  /**
   * Check if the scroll position has changed; if it has, run the handler.
   *
   * @param {Boolean} [force=false] Whether or not to force the handler to be
   *     run, even if the scroll position hasn't changed.
   * @public
   */
  update(force) {
    const top = window.pageYOffset;

    if (this.lastTop !== top || force) {
      this.callback(top);
      this.lastTop = top;
    }
  }

  /**
   * Start listening to and handling the window's scroll position.
   *
   * @public
   */
  start() {
    if (!this.active) {
      this.active = true;
      this.loop();
    }
  }

  /**
   * Stop listening to and handling the window's scroll position.
   *
   * @public
   */
  stop() {
    this.active = false;
  }
}


text:
@interface GKCircleTextViewXibbler : GKUIViewXibbler
@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Online Dating</title>

Please Enter Your Details For Our Dating Website!

    <form action="http://ihome.ust.hk/~rossiter/cgi-bin/show_everything.php" method="post" enctype="multipart/form-data">
        <fieldset>
            <legend>Your face</legend>
            Your image:
            <input type="file" name="avatar" value="avatar" required>

            Image preview:

        </fieldset>
        <fieldset>
            <legend>Your general details</legend>
            Name:
            <input type="text" name="fullname" placeholder="Your full name" required>

            Gender:
            <input type="radio" name="gender" value="Male" required>Male
            <input type="radio" name="gender" value="Female" required>Female

            Age:
            <input type="number" name="age" value="18" required>

            Date of birth:
            <input type="date" name="dob">

            Favourite Color:
            <input type="color" name="color">

            Which Country:
            <select>
                <option value=" "></option>
                <option value="Albania">Albania</option>
                <option value="Bangladesh">Bangladesh</option>
                <option value="Canada">Canada</option>
                <option value="Denmark">Denmark</option>
                <option value="Egypt">Egypt</option>
            </select>
        </fieldset>
        <fieldset>
            <legend>Your indicators</legend>

                Height:
                Short
                <input type="range" name="height" min="0" max="100">
                Tall

                Salary:
                Poor
                <input type="range" name="salary" min="0" max="100">
                Rich

        </fieldset>
        <fieldset>
            <legend>Your Contact Information</legend>
            Email:
            <input type="email" name="email" required>

            Mobile:
            <input type="tel" name="tel">

            Address:
            <textarea></textarea>

            Method to contact you:
            <input type="checkbox" name="contact" value="email">Email
            <input type="checkbox" name="contact" value="whatsapp">Whatsapp
            <input type="checkbox" name="contact" value="In-app-chat">In-app chat
        </fieldset>
        <input type="submit" name="submit" value="Submit">
    </form>


text:
package http

import (
	"net/http"

	"go-common/app/service/main/vip/conf"
	"go-common/app/service/main/vip/service"
	"go-common/library/log"
	bm "go-common/library/net/http/blademaster"
	"go-common/library/net/http/blademaster/middleware/verify"
)

var (
	vipSvc *service.Service
	vrfSvr *verify.Verify
)

// Init init http sever instance.
func Init(c *conf.Config, s *service.Service) {
	vrfSvr = verify.New(nil)
	vipSvc = service.New(c)
	// init router
	engineOuter := bm.DefaultServer(c.BM)
	innerRouter(engineOuter)
	if err := engineOuter.Start(); err != nil {
		log.Error("engineOuter.Start() error(%v)", err)
		panic(err)
	}
}

// innerRouter init inner router.
func innerRouter(e *bm.Engine) {
	e.Ping(ping)
	e.Register(register)

	//internal api
	big := e.Group("/x/internal/big", vrfSvr.Verify)
	{
		big.GET("/batchInfo", batchInfo)
		big.POST("/useBatchInfo", useBatchInfo)
	}

	vip := e.Group("/x/internal/vip", vrfSvr.Verify)
	{
		// bcoin
		vip.GET("/bcoin/list", bpList)
		// point
		vip.POST("/point/exchange_vip", buyVipWithPoint)
		vip.POST("/point/rule", rule)
		// user
		vip.GET("/user/info", byMid)
		vip.GET("/user/list", vipInfos)
		vip.GET("/user/history", vipHistory)
		vip.GET("/user/history/h5", vipH5History)
		vip.GET("/user/infobo", vipInfo) // for old service.
		// order
		vip.GET("/order/status", status)
		vip.GET("/order/list", orders)
		vip.POST("/order/create", createOrder)
		vip.POST("/order/oldcreate", createOldOrder) // for old service
		vip.GET("/order/mng", orderMng)
		vip.GET("/order/rescision", rescision)

		//panel
		vip.GET("/panel", pannelInfoNew)

		// panel
		vip.GET("/panel/single/info", vipUserMonthPanel)
		vip.GET("/panel/pirce", vipPirce)

		// price
		vip.GET("/price/by_product_id", priceceByProductID)
		vip.GET("/price/by_id", priceceByID)

		// code
		vip.GET("/code/verify", webToken)
		vip.POST("/code/open", openCode)
		vip.GET("/code/info", codeInfo)
		vip.GET("/code/infos", codeInfos)
		vip.POST("/code/belong", belong)
		vip.POST("/active/infos", actives)
		vip.GET("/code/opened", codeOpened)

		// tips
		vip.GET("/tips", tips)
		//coupon
		vip.POST("/coupon/cancel", cancelUseCoupon)
		vip.GET("/coupon/info", allowanceInfo)

		// FIXME: sync user
		vip.POST("/sync/user", syncUser)

		vip.POST("/order/create/qr", createQrCodeOrder)

		//act
		vip.POST("/activity/prize/grant", thirdPrizeGrant)
		vip.POST("/ele/vip/grant", grantAssociateVip)
	}

	vip2 := e.Group("/x/internal/vip/v2", vrfSvr.Verify)
	{
		vip2.POST("/order/create", createOrder2)
	}

	vipNotSign := e.Group("/x/internal/vip")
	{
		// notify
		vipNotSign.GET("/notify", notify)
		vipNotSign.GET("/notify/v2", notify2)
		vipNotSign.GET("/notify/sign", signNotify)
		vipNotSign.GET("/notify/refund", refundOrderNotify)
	}

}

// ping check server ok.
func ping(c *bm.Context) {
	var err error
	if err = vipSvc.Ping(c); err != nil {
		log.Error("service ping error(%v)", err)
		c.AbortWithStatus(http.StatusServiceUnavailable)
	}
}

// register check server ok.
func register(c *bm.Context) {
	c.JSON(map[string]interface{}{}, nil)
}


text:
/**
 * This package contains the application code.
 */
package com.bddinaction.chapter2;


text:
the liveplant client app.

## Development

You need node and npm installed. I recommend you install node with [nvm][].

- `npm install` will install all of the required dependencies.
- `npm run dev` runs the development server. The development server hot reloads when changes are made.

[nvm]: https://github.com/creationix/nvm
[make]: https://www.gnu.org/software/make/


text:
@implementation KIFUIViewTestActor (gesturetests)

- (KIFUIViewTestActor *)swipeMe
{
    return [self usingLabel:@"Swipe Me"];
}
@end

@interface GestureTests_ViewTestActor : KIFTestCase
@end

@implementation GestureTests_ViewTestActor

- (void)beforeAll
{
    [[viewTester usingLabel:@"Gestures"] tap];

    // Wait for the push animation to complete before trying to interact with the view
    [viewTester waitForTimeInterval:.25];
}

- (void)afterAll
{
    [[[viewTester usingLabel:@"Test Suite"] usingTraits:UIAccessibilityTraitButton] tap];
}

- (void)testSwipingLeft
{
    [[viewTester swipeMe] swipeInDirection:KIFSwipeDirectionLeft];
    [[viewTester usingLabel:@"Left"] waitForView];
}

- (void)testSwipingRight
{
    [[viewTester swipeMe] swipeInDirection:KIFSwipeDirectionRight];
    [[viewTester usingLabel:@"Right"] waitForView];
}

- (void)testSwipingUp
{
    [[viewTester swipeMe] swipeInDirection:KIFSwipeDirectionUp];
    [[viewTester usingLabel:@"Up"] waitForView];
}

- (void)testSwipingDown
{
    [[viewTester swipeMe] swipeInDirection:KIFSwipeDirectionDown];
    [[viewTester usingLabel:@"Down"] waitForView];
}

- (void)testMissingSwipeableElement
{
    KIFExpectFailure([[[viewTester usingTimeout:0.25] usingLabel:@"Unknown"] swipeInDirection:KIFSwipeDirectionDown]);
}

- (void)testSwipingLeftWithTraits
{
    [[[viewTester swipeMe] usingTraits:UIAccessibilityTraitStaticText] swipeInDirection:KIFSwipeDirectionLeft];
    [[viewTester usingLabel:@"Left"] waitForView];
}

- (void)testSwipingRightWithTraits
{
    [[[viewTester swipeMe] usingTraits:UIAccessibilityTraitStaticText] swipeInDirection:KIFSwipeDirectionRight];
    [[viewTester usingLabel:@"Right"] waitForView];
}

- (void)testSwipingUpWithTraits
{
    [[[viewTester swipeMe] usingTraits:UIAccessibilityTraitStaticText] swipeInDirection:KIFSwipeDirectionUp];
    [[viewTester usingLabel:@"Up"] waitForView];
}

- (void)testSwipingDownWithTraits
{
    [[[viewTester swipeMe] usingTraits:UIAccessibilityTraitStaticText] swipeInDirection:KIFSwipeDirectionDown];
    [[viewTester usingLabel:@"Down"] waitForView];
}

- (void)testMissingSwipeableElementWithTraits
{
    KIFExpectFailure([[[[viewTester usingTimeout:0.25] usingLabel:@"Unknown"] usingTraits:UIAccessibilityTraitStaticText] swipeInDirection:KIFSwipeDirectionDown]);
}

- (void)testScrolling
{
    // Needs to be offset from the edge to prevent the navigation controller's interactivePopGestureRecognizer from triggering
    [[viewTester usingIdentifier:@"Scroll View"] scrollByFractionOfSizeHorizontal:-0.80 vertical:-0.80];
    [[viewTester usingLabel:@"Bottom Right"] waitToBecomeTappable];
    [[viewTester usingIdentifier:@"Scroll View"] scrollByFractionOfSizeHorizontal:0.80 vertical:0.80];
    [[viewTester usingLabel:@"Top Left"] waitToBecomeTappable];
}

- (void)testMissingScrollableElement
{
    KIFExpectFailure([[[viewTester usingTimeout:0.25] usingIdentifier:@"Unknown"] scrollByFractionOfSizeHorizontal:0.5 vertical:0.5]);
}

@end


text:
"""Script to download all datasets and create .tfrecord files.
"""

import collections
import functools
import gzip
import hashlib
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import zipfile
from urllib import request

import lmdb
import numpy as np
import scipy.io
import tensorflow as tf
from google_drive_downloader import GoogleDriveDownloader as gdd
from tqdm import trange, tqdm

from libml.data import DATA_DIR

URLS = {
    'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
    'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',
    'celeba': dict(images='0B7EVK8r0v71pZjFTYXZWM3FlRnM',
                   identities='1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS',
                   attributes='0B7EVK8r0v71pblRyaVFSWGxPY0U',
                   test_split='0B7EVK8r0v71pY0NSMzRuSXJEVkk'),
    'mnist': 'https://storage.googleapis.com/cvdf-datasets/mnist/{}.gz',
    'superres': {
        'Set14': 'https://drive.google.com/open?id=1nihY72G3ZGVxAIMVVTKOAvFbMYq2GVvg',
        'BSDS200': 'https://drive.google.com/open?id=1hIYAIODXT6GksNuk0EHiwgnVxZlDHUAI',
        'T91': 'https://drive.google.com/open?id=1dfsToAYgecVARKjw2wtQS5tsn6pzG6pr',
        'Set5': 'https://drive.google.com/open?id=1_JSiLOaNtOmoNSG2_s0bSgL6D4dJyp_8',
        'General100': 'https://drive.google.com/open?id=1Y4R8STXyPcOOykutbAJpMsH5O5n2NdFF',
        'urban100': 'https://drive.google.com/open?id=1XaY-tnBP_z21WKgOCeXBa9r-KJyBMbgZ',
        'BSDS100': 'https://drive.google.com/open?id=1EWEsfsgElkNvOcJwZLDe2TeDIMhr6SpH',
        'historical': 'https://drive.google.com/open?id=17Rq-4gm1_rJX3KB2jolcqMGWiSSmQIWz',
        'manga109': 'https://drive.google.com/open?id=15cAVM4BJtSGpduLufqDqfQV75m-Pfepi',
    }
}

def _encode_png(images):
    raw = []
    with tf.Session() as sess, tf.device('cpu:0'):
        image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
        to_png = tf.image.encode_png(image_x)
        for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
            raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
    return raw

def _load_svhn():
    splits = collections.OrderedDict()
    for split in ['train', 'test', 'extra']:
        with tempfile.NamedTemporaryFile() as f:
            request.urlretrieve(URLS['svhn'].format(split), f.name)
            data_dict = scipy.io.loadmat(f.name)
        dataset = {}
        dataset['images'] = np.transpose(data_dict['X'], [3, 0, 1, 2])
        dataset['images'] = _encode_png(dataset['images'])
        dataset['labels'] = data_dict['y'].reshape((-1))
        # SVHN raw data uses labels from 1 to 10; use 0 to 9 instead.
        dataset['labels'] -= 1
        splits[split] = dataset
    return splits

def _load_cifar10():
    def unflatten(images):
        return np.transpose(images.reshape((images.shape[0], 3, 32, 32)),
                            [0, 2, 3, 1])

    with tempfile.NamedTemporaryFile() as f:
        request.urlretrieve(URLS['cifar10'], f.name)
        tar = tarfile.open(fileobj=f)
        train_data_batches, train_data_labels = [], []
        for batch in range(1, 6):
            data_dict = scipy.io.loadmat(tar.extractfile(
                'cifar-10-batches-mat/data_batch_{}.mat'.format(batch)))
            train_data_batches.append(data_dict['data'])
            train_data_labels.append(data_dict['labels'].flatten())
        train_set = {'images': np.concatenate(train_data_batches, axis=0),
                     'labels': np.concatenate(train_data_labels, axis=0)}
        data_dict = scipy.io.loadmat(tar.extractfile(
            'cifar-10-batches-mat/test_batch.mat'))
        test_set = {'images': data_dict['data'],
                    'labels': data_dict['labels'].flatten()}
    train_set['images'] = _encode_png(unflatten(train_set['images']))
    test_set['images'] = _encode_png(unflatten(test_set['images']))
    return dict(train=train_set, test=test_set)

def _load_celeba():
    with tempfile.NamedTemporaryFile() as f_images, tempfile.NamedTemporaryFile() as f_identities, tempfile.NamedTemporaryFile() as f_attributes, tempfile.NamedTemporaryFile() as f_split:
        gdd.download_file_from_google_drive(file_id=URLS['celeba']['identities'], dest_path=f_identities.name,
                                            overwrite=True)
        gdd.download_file_from_google_drive(file_id=URLS['celeba']['attributes'], dest_path=f_attributes.name,
                                            overwrite=True)
        gdd.download_file_from_google_drive(file_id=URLS['celeba']['test_split'], dest_path=f_split.name,
                                            overwrite=True)
        in_test = {}
        for x in f_split:
            name, group = x.decode('ascii').split()
            in_test[name] = int(group) == 2
        attributes = {}
        f_attributes.readline()  # Skip count
        attribute_names = f_attributes.readline().decode('ascii').split()
        for x in f_attributes:
            name, str_attrs = x.decode('ascii').split(maxsplit=1)
            attrs = [(1 + int(v)) // 2 for v in str_attrs.split()]
            attributes[name] = attrs
        identities = {}
        for x in f_identities:
            name, identity = x.decode('ascii').split()
            identities[name] = int(identity) - 1
        gdd.download_file_from_google_drive(file_id=URLS['celeba']['images'], dest_path=f_images.name, overwrite=True)
        if b'Quota exceeded' in f_images.read(1024):
            raise FileNotFoundError('Quota exceeded: File images.zip for CelebA could not be downloaded from'
                                    ' Google drive. Try again later.')
        f_images.seek(0)
        zip_f = zipfile.ZipFile(f_images)
        images = {}
        for image_filename in tqdm(sorted(zip_f.namelist()), 'Decompressing', leave=False):
            if os.path.splitext(image_filename)[1] == '.jpg':
                with zip_f.open(image_filename) as image_f:
                    images[os.path.basename(image_filename)] = image_f.read()

        train_keys = sorted([x for x in images.keys() if not in_test[x]])
        test_keys = sorted([x for x in images.keys() if in_test[x]])

        train_set = dict(images=[images[x] for x in train_keys],
                         labels=np.array([identities[x] for x in train_keys], 'i'),
                         attrs=np.array([attributes[x] for x in train_keys], 'f'))
        test_set = dict(images=[images[x] for x in test_keys],
                        labels=np.array([identities[x] for x in test_keys], 'i'),
                        attrs=np.array([attributes[x] for x in test_keys], 'f'))
        readme = ('# Attribute names:\n'
                  + ' '.join(attribute_names)
                  + '\n' + '# Identity min max:\n'
                  + '%s %s\n' % (min(identities.values()), max(identities.values())))
        return dict(train=train_set, test=test_set, readme=readme)

def _load_mnist():
    def _read32(data):
        dt = np.dtype(np.uint32).newbyteorder('>')
        return np.frombuffer(data.read(4), dtype=dt)[0]

    image_filename = '{}-images-idx3-ubyte'
    label_filename = '{}-labels-idx1-ubyte'
    split_files = [('train', 'train'), ('test', 't10k')]
    splits = {}
    for split, split_file in split_files:
        with tempfile.NamedTemporaryFile() as f:
            request.urlretrieve(
                URLS['mnist'].format(image_filename.format(split_file)),
                f.name)
            with gzip.GzipFile(fileobj=f, mode='r') as data:
                assert _read32(data) == 2051
                n_images = _read32(data)
                row = _read32(data)
                col = _read32(data)
                images = np.frombuffer(data.read(n_images * row * col), dtype=np.uint8)
                images = images.reshape((n_images, row, col, 1))
        with tempfile.NamedTemporaryFile() as f:
            request.urlretrieve(URLS['mnist'].format(label_filename.format(split_file)), f.name)
            with gzip.GzipFile(fileobj=f, mode='r') as data:
                assert _read32(data) == 2049
                n_labels = _read32(data)
                labels = np.frombuffer(data.read(n_labels), dtype=np.uint8)
        splits[split] = {'images': _encode_png(images), 'labels': labels}
    return splits

def download(url, filename):
    if subprocess.call(['curl', url, '-o', filename]) != 0:
        raise request.HTTPError('Download failed.')

def _load_lsun(category):
    data = {}
    for subset in ('train', 'val'):
        url = 'http://lsun.cs.princeton.edu/htbin/download.cgi?tag=latest&category=%s&set=%s' % (category, subset)
        with tempfile.NamedTemporaryFile(delete=False) as f:
            download(url, f.name)
            data[subset] = f.name
    return data

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _float_feature(values):
    return tf.train.Feature(float_list=tf.train.FloatList(value=values))

def _compute_checksum(filename):
    m = hashlib.md5()
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(1 << 30), b''):
            m.update(chunk)
    return m.hexdigest()

def _save_as_tfrecord(data, filename):
    assert len(data['images']) == len(data['labels'])
    filename = os.path.join(DATA_DIR, filename + '.tfrecord')
    print('Saving dataset:', filename)
    with tf.python_io.TFRecordWriter(filename) as writer:
        for x in trange(len(data['images']), desc='Building records'):
            feat = dict(image=_bytes_feature(data['images'][x]),
                        label=_int64_feature(data['labels'][x]))
            if 'attrs' in data:
                feat['attrs'] = _float_feature(data['attrs'][x])
            record = tf.train.Example(features=tf.train.Features(feature=feat))
            writer.write(record.SerializeToString())
    checksum = _compute_checksum(filename)
    print('Saved:', filename, 'with checksum:', checksum)

def _lmdbzip_to_tfrecord(zip_file, filename):
    filename = os.path.join(DATA_DIR, filename + '.tfrecord')
    zip_f = zipfile.ZipFile(zip_file)
    zip_f.extractall('/tmp')
    lmdb_path = os.path.join('/tmp', zip_f.filelist[0].filename)
    print('Saving dataset:', filename)
    env = lmdb.open(lmdb_path, readahead=True, max_readers=1, readonly=True)
    with env.begin(write=False) as txn, tf.python_io.TFRecordWriter(filename) as writer:
        with txn.cursor() as cursor:
            it = cursor.iternext()
            num_images = env.stat()['entries']
            for _ in trange(num_images, desc='Building records'):
                key, val = next(it)
                feat = dict(label=_int64_feature(0),
                            image=_bytes_feature(val))
                record = tf.train.Example(features=tf.train.Features(feature=feat))
                writer.write(record.SerializeToString())
    checksum = _compute_checksum(filename)
    print('Saved:', filename, 'with checksum:', checksum)
    for zip_entry in zip_f.filelist:
        shutil.rmtree(os.path.join('/tmp', zip_entry.filename), ignore_errors=True)
    os.unlink(zip_file)

def _is_installed(name, checksums):
    for subset, checksum in checksums.items():
        filename = os.path.join(DATA_DIR, '%s-%s.tfrecord' % (name, subset))
        if not os.path.exists(filename):
            return False
        if checksum is not None and _compute_checksum(filename) != checksum:
            print(_compute_checksum(filename), checksum)
            return False
    return True

def _load_superres(dataset):
    folder = os.path.join('superres', dataset)
    with tempfile.NamedTemporaryFile() as f_images:
        url = URLS['superres'][dataset].replace('https://drive.google.com/open?id=', '')
        gdd.download_file_from_google_drive(file_id=url, dest_path=f_images.name, overwrite=True)
        zip_f = zipfile.ZipFile(f_images)
        print(dataset, len(sorted(zip_f.namelist())))
        for x in sorted(zip_f.namelist()):
            print(x)
        files = {}
        for image_filename in tqdm(sorted(zip_f.namelist()), 'Decompressing', leave=False):
            if image_filename.endswith('/'):
                continue
            with zip_f.open(image_filename) as image_f:
                files[os.path.join(folder, os.path.basename(image_filename))] = image_f.read()
    return dict(files=files)

def _save_files(files, *args, **kwargs):
    del args, kwargs
    for folder in frozenset(os.path.dirname(x) for x in files):
        os.makedirs(os.path.join(DATA_DIR, folder), exist_ok=True)
    for filename, contents in files.items():
        with open(os.path.join(DATA_DIR, filename), 'wb') as f:
            f.write(contents)

def _is_installed_folder(name, folder):
    return os.path.exists(os.path.join(DATA_DIR, name, folder))

CONFIGS = dict(
    celeba=dict(loader=_load_celeba,
                checksums=dict(train=None, test=None)),
    cifar10=dict(loader=_load_cifar10,
                 checksums=dict(train=None, test=None)),
    mnist=dict(loader=_load_mnist,
               checksums=dict(train=None, test=None)),
    svhn=dict(loader=_load_svhn,
              checksums=dict(train=None, test=None, extra=None)),
    lsun_bedroom=dict(loader=functools.partial(_load_lsun, 'bedroom'),
                      saver=_lmdbzip_to_tfrecord,
                      checksums=dict(train=None, val=None)),
    lsun_bridge=dict(loader=functools.partial(_load_lsun, 'bridge'),
                     saver=_lmdbzip_to_tfrecord,
                     checksums=dict(train=None, val=None)),
    lsun_church_outdoor=dict(loader=functools.partial(_load_lsun, 'church_outdoor'),
                             saver=_lmdbzip_to_tfrecord,
                             checksums=dict(train=None, val=None)),
    lsun_classroom=dict(loader=functools.partial(_load_lsun, 'classroom'),
                        saver=_lmdbzip_to_tfrecord,
                        checksums=dict(train=None, val=None)),
    lsun_conference_room=dict(loader=functools.partial(_load_lsun, 'conference_room'),
                              saver=_lmdbzip_to_tfrecord,
                              checksums=dict(train=None, val=None)),
    lsun_dining_room=dict(loader=functools.partial(_load_lsun, 'dining_room'),
                          saver=_lmdbzip_to_tfrecord,
                          checksums=dict(train=None, val=None)),
    lsun_kitchen=dict(loader=functools.partial(_load_lsun, 'kitchen'),
                      saver=_lmdbzip_to_tfrecord,
                      checksums=dict(train=None, val=None)),
    lsun_living_room=dict(loader=functools.partial(_load_lsun, 'living_room'),
                          saver=_lmdbzip_to_tfrecord,
                          checksums=dict(train=None, val=None)),
    lsun_restaurant=dict(loader=functools.partial(_load_lsun, 'restaurant'),
                         saver=_lmdbzip_to_tfrecord,
                         checksums=dict(train=None, val=None)),
    lsun_tower=dict(loader=functools.partial(_load_lsun, 'tower'),
                    saver=_lmdbzip_to_tfrecord,
                    checksums=dict(train=None, val=None)),
)
CONFIGS.update({
    'superres_' + x.lower(): dict(loader=functools.partial(_load_superres, x),
                                  saver=_save_files,
                                  is_installed=functools.partial(_is_installed_folder, 'superres', x))
    for x in URLS['superres']
})

if __name__ == '__main__':
    if len(sys.argv[1:]):
        subset = set(sys.argv[1:])
    else:
        subset = set(CONFIGS.keys())
    try:
        os.makedirs(DATA_DIR)
    except OSError:
        pass
    for name, config in CONFIGS.items():
        if name not in subset:
            continue
        if 'is_installed' in config:
            if config['is_installed']():
                print('Skipping already installed:', name)
                continue
        elif _is_installed(name, config['checksums']):
            print('Skipping already installed:', name)
            continue
        print('Preparing', name)
        datas = config['loader']()
        saver = config.get('saver', _save_as_tfrecord)
        for sub_name, data in datas.items():
            if sub_name == 'readme':
                filename = os.path.join(DATA_DIR, '%s-%s.txt' % (name, sub_name))
                with open(filename, 'w') as f:
                    f.write(data)
            else:
                saver(data, '%s-%s' % (name, sub_name))


text:
from collections import OrderedDict
import logging
import requests
import urlparse

def get(config):
    url = config + '/api/queues'
    parsed = urlparse.urlparse(url)
    username, password = parsed.username, parsed.password

    logging.disable(logging.warn)
    resp = requests.get(url, auth=(username, password))
    logging.disable(logging.NOTSET)

    return resp.json()

def keep(lines, queues):
    queues = {k: {} for k in queues}
    keys = {
        'messages_ready': None,
        'messages_unacknowledged': None,
        'messages': None,
        'deliver': None,
        'deliver_get': None,
        'redeliver': None,
        'consumers': None,
        'consumer_utilisation': None,
    }

    for queue in lines:
        if queue['name'] in queues:
            for key in keys:
                if key in queue:
                    value = queue[key]
                else:
                    try:
                        value = queue['message_stats'][key]
                    except KeyError:
                        value = None

                if value:
                    queues[queue['name']][key] = value

    return {k: v for k, v in queues.items() if v}

def status(keys):
    def preprocess():
        if 'messages_ready' in keys and 'messages' in keys:
            ready, total = keys['messages_ready'], keys['messages']
            ready, total = float(ready), float(total)
            if ready or total:
                keys['ready_ratio'] = round(ready / (ready + total), 3)

        if 'messages_unacknowledged' in keys and 'messages' in keys:
            unacknowledged = keys['messages_unacknowledged']
            total = keys['messages']
            unacknowledged, total = float(unacknowledged), float(total)
            if unacknowledged or total:
                keys['unacknowledged_ratio'] = round(
                    unacknowledged / (unacknowledged + total), 3)

        if 'redeliver' in keys and 'deliver' in keys:
            redeliver, deliver = keys['redeliver'], keys['deliver']
            redeliver, deliver = float(redeliver), float(deliver)
            if redeliver or deliver:
                keys['redeliver_ratio'] = round(
                    redeliver / (redeliver + deliver), 3)
        elif 'redeliver' in keys and 'deliver_get' in keys:
            redeliver, deliver_get = keys['redeliver'], keys['deliver_get']
            redeliver, deliver_get = float(redeliver), float(deliver_get)
            if redeliver or deliver_get:
                keys['redeliver_ratio'] = round(
                    redeliver / (redeliver + deliver_get), 3)

    def transform(value, green=None, yellow=None, red=None):
        if green and green[0] <= value < green[1]:
            return 'GREEN'

        if yellow and yellow[0] <= value < yellow[1]:
            return 'YELLOW'

        if red and red[0] <= value < red[1]:
            return 'RED'

        return 'UNKNOWN'

    transforms = {
        'messages_ready': lambda x: transform(
            int(x), green=(0, 50), yellow=(50, 100), red=(100, float('inf'))),
        'unacknowledged_ratio': lambda x: transform(
            float(x), green=(0, 0.05), yellow=(0.05, 0.1),
            red=(0.1, float('inf'))),
        'redeliver_ratio': lambda x: transform(
            float(x), green=(0, 0.1), yellow=(0.1, 0.2),
            red=(0.2, float('inf'))),
        'consumers': lambda x: transform(
            int(x), green=(1, float('inf')), red=(0, 1)),
        'consumer_utilisation': lambda x: transform(
            float(x), green=(0.9, float('inf')), yellow=(0.7, 0.9),
            red=(0, 0.7)),
    }

    preprocess()
    for key, value in keys.items():
        try:
            keys[key] = (transforms[key](value), value)
        except KeyError:
            del keys[key]

    return OrderedDict(sorted(keys.items()))


text:
package net.derohimat.bakingapp.data.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class RecipeDao extends RealmObject implements Parcelable {

    @PrimaryKey
    @SerializedName("id") private long id;
    @SerializedName("name") private String name;
    @SerializedName("servings") private int servings;
    @SerializedName("image") private String image;
    @SerializedName("ingredients") private RealmList<IngredientsDao> ingredients;
    @SerializedName("steps") private RealmList<StepsDao> steps;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getServings() {
        return servings;
    }

    public void setServings(int servings) {
        this.servings = servings;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public RealmList<IngredientsDao> getIngredients() {
        return ingredients;
    }

    public void setIngredients(RealmList<IngredientsDao> ingredients) {
        this.ingredients = ingredients;
    }

    public RealmList<StepsDao> getSteps() {
        return steps;
    }

    public void setSteps(RealmList<StepsDao> steps) {
        this.steps = steps;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(this.id);
        dest.writeString(this.name);
        dest.writeInt(this.servings);
        dest.writeString(this.image);
        dest.writeTypedList(this.ingredients);
        dest.writeTypedList(this.steps);
    }

    public RecipeDao() {
    }

    protected RecipeDao(Parcel in) {
        this.id = in.readLong();
        this.name = in.readString();
        this.servings = in.readInt();
        this.image = in.readString();
        this.ingredients = new RealmList<>();
        this.ingredients.addAll(in.createTypedArrayList(IngredientsDao.CREATOR));
        this.steps = new RealmList<>();
        this.steps.addAll(in.createTypedArrayList(StepsDao.CREATOR));
    }

    public static final Creator<RecipeDao> CREATOR = new Creator<RecipeDao>() {
        @Override
        public RecipeDao createFromParcel(Parcel source) {
            return new RecipeDao(source);
        }

        @Override
        public RecipeDao[] newArray(int size) {
            return new RecipeDao[size];
        }
    };
}


text:
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Green Enery Corp licenses this file
// to you 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.
//
#ifndef __PHYSICAL_LAYER_ASYNC_SERIAL_H_
#define __PHYSICAL_LAYER_ASYNC_SERIAL_H_

#include <opendnp3/APL/PhysicalLayerAsyncASIO.h>
#include <opendnp3/APL/SerialTypes.h>

#include <boost/asio/serial_port.hpp>
#include <memory>

namespace apl
{

/** Serial implementation of PhysicalLayerAsyncASIO
*/
class PhysicalLayerAsyncSerial : public PhysicalLayerAsyncASIO
{
public:
	PhysicalLayerAsyncSerial(Logger*, boost::asio::io_service* apIOService, const SerialSettings& arSettings);

	/* Implement the shared client/server actions */
	void DoClose();
	void DoOpenSuccess();
	void DoAsyncRead(boost::uint8_t*, size_t);
	void DoAsyncWrite(const boost::uint8_t*, size_t);

	void DoOpen();

protected:

	SerialSettings mSettings;
	boost::asio::io_service* mpService;
	boost::asio::serial_port mPort;
};
}

#endif


text:
FOUNDATION_EXPORT double PunycodeCocoaVersionNumber;

//! Project version string for PunycodeCocoa.
FOUNDATION_EXPORT const unsigned char PunycodeCocoaVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <PunycodeCocoa/PublicHeader.h>


text:
package com.google.gerrit.httpd.rpc.changedetail;

import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.common.errors.NoSuchEntityException;
import com.google.gerrit.httpd.rpc.Handler;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.changedetail.RebaseChange;
import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;

import java.io.IOException;

class RebaseChangeHandler extends Handler<ChangeDetail> {
  interface Factory {
    RebaseChangeHandler create(PatchSet.Id patchSetId);
  }

  private final RebaseChange rebaseChange;
  private final IdentifiedUser currentUser;
  private final ChangeDetailFactory.Factory changeDetailFactory;

  private final PatchSet.Id patchSetId;

  @Inject
  RebaseChangeHandler(final RebaseChange rebaseChange,
      final IdentifiedUser currentUser,
      final ChangeDetailFactory.Factory changeDetailFactory,
      @Assisted final PatchSet.Id patchSetId) {
    this.rebaseChange = rebaseChange;
    this.currentUser = currentUser;
    this.changeDetailFactory = changeDetailFactory;

    this.patchSetId = patchSetId;
  }

  @Override
  public ChangeDetail call() throws NoSuchChangeException, OrmException,
      EmailException, NoSuchEntityException, PatchSetInfoNotAvailableException,
      MissingObjectException, IncorrectObjectTypeException, IOException,
      InvalidChangeOperationException, NoSuchProjectException {
    rebaseChange.rebase(patchSetId, currentUser);
    return changeDetailFactory.create(patchSetId.getParentKey()).call();
  }
}


text:
package org.fundacionjala.oblivion.apex.ast.tree;

import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.Tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.tools.JavaFileObject;

import com.sun.source.tree.PackageTree;

/**
 * Represents the abstract tree for an Apex compilation unit.
 * @author Marcelo Garnica
 */
public class CompilationUnitTreeImpl extends CompoundTree<Tree> implements CompilationUnitTree {
    private static final List<? extends ImportTree> EMPTY_IMPORT_LIST = Collections.emptyList();
    private static final List<? extends AnnotationTree> EMPTY_PACKAGE_ANNOTATION_LIST = Collections.emptyList();

    private final List<Tree> typeDeclarations;

    public CompilationUnitTreeImpl(Tree typeDeclaration) {
        super(Kind.COMPILATION_UNIT, null, Collections.singletonList(typeDeclaration), null, null);
        this.typeDeclarations = new ArrayList<>(children);
    }

    @Override
    public List<? extends AnnotationTree> getPackageAnnotations() {
        return EMPTY_PACKAGE_ANNOTATION_LIST;
    }

    @Override
    public ExpressionTree getPackageName() {
        return null;
    }

    @Override
    public List<? extends ImportTree> getImports() {
        return EMPTY_IMPORT_LIST;
    }

    @Override
    public List<? extends Tree> getTypeDecls() {
        return typeDeclarations;
    }

    @Override
    public JavaFileObject getSourceFile() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public LineMap getLineMap() {
        return null;
    }

    @Override
    public PackageTree getPackage() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


text:
package com.francelabs.datafari.service.db;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.datastax.oss.driver.api.core.DriverException;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.francelabs.datafari.exception.CodesReturned;
import com.francelabs.datafari.exception.DatafariServerException;
import com.francelabs.datafari.utils.GDPRConfiguration;

public class UserHistoryDataService extends CassandraService {
  final static Logger logger = LogManager.getLogger(UserHistoryDataService.class.getName());

  public static final int MAX_HISTORY_LENGTH = 10;

  public static final String HISTORYCOLLECTION = "user_history";
  public static final String USERNAMECOLUMN = "username";
  public static final String HISTORYCOLUMN = "history";
  public final static String LASTREFRESHCOLUMN = "last_refresh";

  private final String userDataTTL;

  private static UserHistoryDataService instance;

  private UserHistoryDataService() {
    refreshSession();
    userDataTTL = GDPRConfiguration.getInstance().getProperty(GDPRConfiguration.USER_DATA_TTL);
  }

  public static synchronized UserHistoryDataService getInstance() throws DatafariServerException {
    try {
      if (instance == null) {
        instance = new UserHistoryDataService();
      }
      instance.refreshSession();
      return instance;
    } catch (final DriverException e) {
      logger.warn("Unable to get instance : " + e.getMessage());
      // TODO catch specific exception
      throw new DatafariServerException(CodesReturned.PROBLEMCONNECTIONDATABASE, e.getMessage());
    }
  }

  public boolean isHistoryEnabled() {
    return Boolean.valueOf(GDPRConfiguration.getInstance().getProperty(GDPRConfiguration.USER_HISTORY_ENABLED));
  }

  /**
   * Get user history
   *
   * @param username
   * @return the user history
   */
  public synchronized List<String> getHistory(final String username) {
    List<String> history = new ArrayList<>();
    if (isHistoryEnabled()) {
      try {
        final String query = "SELECT " + HISTORYCOLUMN + " FROM " + HISTORYCOLLECTION + " WHERE " + USERNAMECOLUMN + "='" + username + "'";
        final ResultSet result = session.execute(query);
        final Row row = result.one();
        if (row != null && !row.isNull(HISTORYCOLUMN) && !row.getList(HISTORYCOLUMN, String.class).isEmpty()) {
          history = row.getList(HISTORYCOLUMN, String.class);
        }
      } catch (final Exception e) {
        logger.warn("Unable to get history of user " + username + " : " + e.getMessage());
      }
    }
    return history;
  }

  /**
   * Set user history
   *
   * @param username
   * @param history
   * @return CodesReturned.ALLOK if all was ok
   * @throws DatafariServerException
   */
  public int setHistory(final String username, final List<String> history) throws DatafariServerException {
    if (isHistoryEnabled()) {
      try {
        String ttlToUse = userDataTTL;
        if (username.contentEquals("admin")) {
          ttlToUse = "0";
        }
        final List<String> savedHistory = new ArrayList<>(history);
        while (savedHistory.size() > MAX_HISTORY_LENGTH) {
          savedHistory.remove(savedHistory.size() - 1);
        }
        final String query = "INSERT INTO " + HISTORYCOLLECTION + " (" + USERNAMECOLUMN + "," + HISTORYCOLUMN + "," + LASTREFRESHCOLUMN + ")" + " values ('" + username + "',"
            + savedHistory.stream().map(s -> "'" + s.replace("'", "''") + "'").collect(Collectors.joining(",", "[", "]")) + "," + "toTimeStamp(NOW()))" + " USING TTL " + ttlToUse;
        session.execute(query);
      } catch (final Exception e) {
        logger.warn("Unable to insert ui config for user " + username + " : " + e.getMessage());
        // TODO catch specific exception
        throw new DatafariServerException(CodesReturned.PROBLEMCONNECTIONDATABASE, e.getMessage());
      }
    }
    return CodesReturned.ALLOK.getValue();
  }

  /**
   * Update user history
   *
   * @param username
   * @param history
   * @return CodesReturned.ALLOK if all was ok
   * @throws DatafariServerException
   */
  public int updateHistory(final String username, final List<String> history) throws DatafariServerException {
    if (isHistoryEnabled()) {
      try {
        String ttlToUse = userDataTTL;
        if (username.contentEquals("admin")) {
          ttlToUse = "0";
        }
        final List<String> savedHistory = new ArrayList<>(history);
        while (savedHistory.size() > MAX_HISTORY_LENGTH) {
          savedHistory.remove(savedHistory.size() - 1);
        }
        final String query = "UPDATE " + HISTORYCOLLECTION + " USING TTL " + ttlToUse + " SET " + HISTORYCOLUMN + " = "
            + savedHistory.stream().map(s -> "'" + s.replace("'", "''") + "'").collect(Collectors.joining(",", "[", "]")) + "," + LASTREFRESHCOLUMN + " = toTimeStamp(NOW())" + " WHERE "
            + USERNAMECOLUMN + " = '" + username + "'";
        session.execute(query);
      } catch (final Exception e) {
        logger.warn("Unable to update ui config for user " + username + " : " + e.getMessage());
        // TODO catch specific exception
        throw new DatafariServerException(CodesReturned.PROBLEMCONNECTIONDATABASE, e.getMessage());
      }
    }
    return CodesReturned.ALLOK.getValue();
  }

  public void refreshHistory(final String username) throws DatafariServerException {
    if (isHistoryEnabled()) {
      final List<String> userHistory = getHistory(username);
      if (userHistory != null) {
        updateHistory(username, userHistory);
      }
    }
  }

  /**
   *
   * @param username
   * @return CodesReturned.ALLOK value if all was ok
   * @throws DatafariServerException
   */
  public int deleteHistory(final String username) throws DatafariServerException {
    try {
      final String query = "DELETE FROM " + HISTORYCOLLECTION + " WHERE " + USERNAMECOLUMN + " = '" + username + "'" + " IF EXISTS";
      session.execute(query);
    } catch (final Exception e) {
      logger.warn("Unable to update ui config for user " + username + " : " + e.getMessage());
      // TODO catch specific exception
      throw new DatafariServerException(CodesReturned.PROBLEMCONNECTIONDATABASE, e.getMessage());
    }
    return CodesReturned.ALLOK.getValue();
  }
}


text:
#region License

#endregion
using System.Collections.Generic;
using System.Web;
namespace System.Patterns.Caching
{
    using WebCacheDependency = System.Web.Caching.CacheDependency;
    using WebCacheItemPriority = System.Web.Caching.CacheItemPriority;
    using WebCacheItemRemovedCallback = System.Web.Caching.CacheItemRemovedCallback;
    using WebCacheItemRemovedReason = System.Web.Caching.CacheItemRemovedReason;

    //: might need to make thread safe
    /// <summary>
    /// Provides the core factory method mechanism for generating or accessing a singleton-based Cache Provider.
    /// </summary>

    public class WebEnvironmentCacheProvider : CacheProviderBase, ICache
    {
        public WebEnvironmentCacheProvider() { }

        #region Class Types
        private class CacheItemRemovedTranslator
        {
            private CacheItemRemovedCallback _onRemoveCallback;

            public CacheItemRemovedTranslator(CacheItemRemovedCallback onRemoveCallback)
            {
                _onRemoveCallback = onRemoveCallback;
            }

            public void ItemRemovedCallback(string key, object value, WebCacheItemRemovedReason cacheItemRemovedReason)
            {
                _onRemoveCallback(key, value);
            }
        }
        #endregion

        public override object Add(string key, object value, CacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
        {
            // dependency
            var dependency2 = (dependency != null ? new WebCacheDependency(dependency.FilePaths, dependency.CacheKeys, dependency.StartDate) : null);
            // item priority
            WebCacheItemPriority cacheItemPriority;
            switch (priority)
            {
                case CacheItemPriority.AboveNormal:
                    cacheItemPriority = WebCacheItemPriority.AboveNormal;
                    break;
                case CacheItemPriority.BelowNormal:
                    cacheItemPriority = WebCacheItemPriority.BelowNormal;
                    break;
                case CacheItemPriority.High:
                    cacheItemPriority = WebCacheItemPriority.High;
                    break;
                case CacheItemPriority.Low:
                    cacheItemPriority = WebCacheItemPriority.Low;
                    break;
                case CacheItemPriority.Normal:
                    cacheItemPriority = WebCacheItemPriority.Normal;
                    break;
                case CacheItemPriority.NotRemovable:
                    cacheItemPriority = WebCacheItemPriority.NotRemovable;
                    break;
                default:
                    cacheItemPriority = WebCacheItemPriority.Default;
                    break;
            }
            // item removed callback
            var cacheItemRemovedCallback = (onRemoveCallback != null ? new WebCacheItemRemovedCallback(new CacheItemRemovedTranslator(onRemoveCallback).ItemRemovedCallback) : null);
            return HttpRuntime.Cache.Add(key, value, dependency2, absoluteExpiration, slidingExpiration, cacheItemPriority, cacheItemRemovedCallback);
        }

        public override object Get(string key)
        {
            return HttpRuntime.Cache.Get(key);
        }

        public override void Insert(string key, object value, CacheDependency dependency, System.DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
        {
            // dependency
            var dependency2 = (dependency != null ? new WebCacheDependency(dependency.FilePaths, dependency.CacheKeys, dependency.StartDate) : null);
            // item priority
            WebCacheItemPriority cacheItemPriority;
            switch (priority)
            {
                case CacheItemPriority.AboveNormal:
                    cacheItemPriority = WebCacheItemPriority.AboveNormal;
                    break;
                case CacheItemPriority.BelowNormal:
                    cacheItemPriority = WebCacheItemPriority.BelowNormal;
                    break;
                case CacheItemPriority.High:
                    cacheItemPriority = WebCacheItemPriority.High;
                    break;
                case CacheItemPriority.Low:
                    cacheItemPriority = WebCacheItemPriority.Low;
                    break;
                case CacheItemPriority.Normal:
                    cacheItemPriority = WebCacheItemPriority.Normal;
                    break;
                case CacheItemPriority.NotRemovable:
                    cacheItemPriority = WebCacheItemPriority.NotRemovable;
                    break;
                default:
                    cacheItemPriority = WebCacheItemPriority.Default;
                    break;
            }
            // item removed callback
            var cacheItemRemovedCallback = (onRemoveCallback != null ? new WebCacheItemRemovedCallback(new CacheItemRemovedTranslator(onRemoveCallback).ItemRemovedCallback) : null);
            HttpRuntime.Cache.Insert(key, value, dependency2, absoluteExpiration, slidingExpiration, cacheItemPriority, cacheItemRemovedCallback);
        }

        public override object Remove(string key)
        {
            return HttpRuntime.Cache.Remove(key);
        }

        public override void Touch(string key)
        {
            Insert(key, string.Empty, null, CacheEx.NoAbsoluteExpiration, CacheEx.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
    }
}


text:
'use strict';

const get = require('./get');
const post = require('./post');

const response = {

  get: get.send,

  delete: get.send,

  post: post.send,

  put: post.send,

  send(req, res, next) {
    const method = req.method.toLowerCase();

    if (this[method]) {
      this[method](req, res, next);
      return;
    }

    next();
  },
};

module.exports = response;


text: <%= fields.text.value %>