text:
import thingspeak #library for accessing ThingSpeak.com
import json #library used to interpret the json response from ThingSpeak
from datetime import datetime #library used to manipulte time stamps
import time
import smtplib #library used to send emails
import Private #stores all sensitive information
from requests.exceptions import ConnectionError
import logging
import logging.handlers
import os, inspect

ch = thingspeak.Channel(234851, api_key='V9E6SE1V7ZY60S8C')
LOG_FILENAME = 'ThingSpeak2.out'

def getLogFolderPath():
    script_filename = inspect.getframeinfo(inspect.currentframe()).filename
    script_path = '/home/pi/FumeHoodMonitor'
    directory = os.path.join(script_path, "Eventlogs")
    if not os.path.exists(directory):
        os.makedirs(directory)
    return directory

def initLogger():
    logger = logging.getLogger()
    if(logger.handlers is None or len(logger.handlers)==0): #don't want to register handlers more than once
        logger.setLevel(logging.WARNING)

    #create console handler and set level to info
    handler = logging.StreamHandler()
    handler.setLevel(logging.WARNING)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logging.warning('stdout logging initialized')

    #create rotating file handler
    LOG_PATH = os.path.join(getLogFolderPath(), LOG_FILENAME)
    handler = logging.handlers.RotatingFileHandler(LOG_PATH, maxBytes = 1048576, backupCount=4)
    handler.setLevel(logging.WARNING)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logging.warning('File logging initialized')

    # logging.getLogger('requests').setLevel(logging.ERROR)

def sendEmail(subject, message, severity):
    SMTP_SERVER = 'smtp.gmail.com'
    SMTP_PORT = 587
    GMAIL_USERNAME = Private.gmailUsername
    GMAIL_PASSWORD = Private.gmailPassword

    if severity == 0:
        recipient = Private.warningRecipient
        recipients = Private.warningRecipients
    elif severity == 1:
        recipient = Private.alarmRecipient
        recipients = Private.alarmRecipients

    emailText = "" + message + ""
    headers = ["From: " + GMAIL_USERNAME,
               "Subject: " + subject,
               "To: " + recipient,
               "MIME-Version: 1.0",
               "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo

    session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

    session.sendmail(GMAIL_USERNAME, recipients, headers + "\r\n\r\n" + emailText)
    session.quit()

def getThingSpeakData():
    results = ch.get({'results': 1, 'status': 'true'})
    parsed_results = json.loads(results)
    return parsed_results

def wasRebooted(data):
    status = data['feeds'][0]['status']
    return status.find('Rebooted') > -1

def getFireStatus(data):
    status = data['feeds'][0]['status']
    return status.find('Fire') > -1

def getAirStatus(data):
    status = data['feeds'][0]['status']
    return status.find('Air Temp High') > -1

def getOilStatus(data):
    status = data['feeds'][0]['status']
    return status.find('Oil Temp High') > -1

def getElapsedTime(data):
    date_string = data['feeds'][0]['created_at']
    date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ')
    currentDate = datetime.utcnow()
    elapsedTime = (currentDate - date).total_seconds()
    return elapsedTime

def getCurrentDateTimeString():
    currentTime = datetime.utcnow()
    formatedTime = currentTime.strftime("%d-%b-%Y %H:%M:%S UTC")
    return formatedTime

def getDataForEmail(data):
    # str = "

"
    # date_string = data['feeds'][0]['created_at']
    # date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ')
    # str = "
%s UTC
" % date
    str = "
Last Entry ID: %s
" % data['feeds'][0]['entry_id']
    str += "Status: %s
" % data['feeds'][0]['status']
    str += "Error States:"
    str += "
"
    str += "
On Fire: %s
" % getFireStatus(data)
    str += "
Air High: %s
" % getAirStatus(data)
    str += "
Oil High: %s
" % getOilStatus(data)
    str += "
"
    str += "Data:"
    str += "
"
    str += "
Air Temp: %s
" % data['feeds'][0]['field1']
    str += "
Oil Temp: %s
" % data['feeds'][0]['field2']
    str += "
Flame Sensor: %s
" % data['feeds'][0]['field3']
    str += "
"
    str += "

Note: All times are in UTC"
    return str

def assembleEmailMessage(msgString, data):
    message = "
" + msgString + "
"
    message += getDataForEmail(data)
    return message

oldFireStatus = False
oldAirStatus = False
oldOilStatus = False
fireEmailSent = False
airEmailSent = False
oilEmailSent = False
timeEmailSent = False
errorEmailSent = False

initLogger()

while True:
    # Gather the data to act on
    try:
        data = getThingSpeakData()
    except:# ConnectionError as err:
        # print 'Handling Connection Error:', err
        time.sleep(2)
    else:
        if wasRebooted(data):
            continue
        onFire = getFireStatus(data)
        airHigh = getAirStatus(data)
        oilHigh = getOilStatus(data)
        elapsedTime = getElapsedTime(data)
        if onFire:
            severity = 1
        else:
            severity = 0

        # Send an email if the time since the last data post is more than 5 minutes
        if elapsedTime > 300 and not(timeEmailSent):
            subject = "Error: Fume Hood Not Reporting"
            message = "There have been no posts to ThingSpeak from the fume hood in the last 5 minutes"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            timeEmailSent = True
            logging.warning("%s: Time Email Sent" % datetime.utcnow())
            print "Time Email sent at %s" % datetime.utcnow()
        elif elapsedTime <= 300 and timeEmailSent:
            subject = "Clear: Fume Hood Started Reporting"
            message = "The fume hood monitor has begun again to post to ThingSpeak"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            timeEmailSent = False
            logging.warning("%s: Time Email cleared sent" % datetime.utcnow())
            print "Time Email cleared sent at %s" % datetime.utcnow()

        # Send an email if there is a fire
        if (onFire) and not(fireEmailSent):
            subject = "Error: On Fire - %s" % getCurrentDateTimeString()
            message = "The Fume Hood is reporting a fire"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            fireEmailSent = True
            errorEmailSent = True
            logging.warning("%s: Fire Email Sent" % datetime.utcnow())
            print "Fire Email sent at %s" % datetime.utcnow()
        # Send an email when the fire state clears
        elif not(onFire) and fireEmailSent:
            # subject = "Clear: On Fire - %s" % getCurrentDateTimeString()
            # message = "Fire state has been cleared"
            # message = assembleEmailMessage(message, data)
            # sendEmail(subject, message, severity)
            fireEmailSent = False
            # print "Fire Cleared Email sent at %s" % datetime.utcnow()

        # Send an email if there is an air high alarm
        if (airHigh) and not(airEmailSent):
            subject = "Error: Air High Temp - %s" % getCurrentDateTimeString()
            message = "The Fume Hood is reporting that the air temperature is exceeding its max limit"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            airEmailSent = True
            errorEmailSent = True
            logging.warning("%s: Air Email Sent" % datetime.utcnow())
            print "Air Email sent at %s" % datetime.utcnow()
        # Send an email when the air high alarm clears
        elif not(airHigh) and airEmailSent:
            # subject = "Clear: Air High Temp - %s" % getCurrentDateTimeString()
            # message = "The air temperature has cooled sufficiently"
            # message = assembleEmailMessage(message, data)
            # sendEmail(subject, message, severity)
            airEmailSent = False
            # print "Air Cleared Email sent at %s" % datetime.utcnow()

        # Send an email if there is an oil high alarm
        if (oilHigh) and not(oilEmailSent):
            subject = "Error: Oil High Temp - %s" % getCurrentDateTimeString()
            message = "The Fume Hood is reporting that the oil temperature is exceeding its max limit"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            oilEmailSent = True
            errorEmailSent = True
            logging.warning("%s: Oil Email Sent" % datetime.utcnow())
            print "Oil Email sent at %s" % datetime.utcnow()
        # Send an email when the oil high alarm clears
        elif not(oilHigh) and oilEmailSent:
            # subject = "Clear: Oil High Temp - %s" % getCurrentDateTimeString()
            # message = "The oil temperature has cooled sufficiently"
            # message = assembleEmailMessage(message, data)
            # sendEmail(subject, message, severity)
            oilEmailSent = False
            # print "Oil Cleared Email sent at %s" % datetime.utcnow()

        if not(onFire) and not(airHigh) and not(oilHigh) and errorEmailSent:
            subject = "Clear: All system are normal - %s" % getCurrentDateTimeString()
            message = "All system errors have been cleared and power has been restored to the hot plate"
            message = assembleEmailMessage(message, data)
            sendEmail(subject, message, severity)
            errorEmailSent = False
            logging.warning("%s: All clear Email Sent" % datetime.utcnow())
            print "All clear email sent as %s" % datetime.utcnow()

        time.sleep(1.5)


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet title="XSL_formatting" type="text/xsl" href="/shared/bsp/xsl/rss/nolsol.xsl"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
    <channel>
        <title><![CDATA[BBC News - Home]]></title>
        <description><![CDATA[BBC News - Home]]></description>
        <link>http://www.bbc.co.uk/news/</link>
        <image>
            <url>http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif</url>
            <title>BBC News - Home</title>
            <link>http://www.bbc.co.uk/news/</link>
        </image>
        <generator>RSS for Node</generator>
        <lastBuildDate>Fri, 31 Mar 2017 14:20:51 GMT</lastBuildDate>
        <copyright><![CDATA[Copyright: (C) British Broadcasting Corporation, see http://news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse.]]></copyright>
        <language><![CDATA[en-gb]]></language>
        <ttl>15</ttl>
        <item>
            <title><![CDATA[EU sets out 'phased' Brexit strategy]]></title>
            <description><![CDATA[Talks on a trade deal may begin once progress in Brexit talks has been made, the bloc suggests.]]></description>
            <link>http://www.bbc.co.uk/news/world-europe-39453338</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-europe-39453338</guid>
            <pubDate>Fri, 31 Mar 2017 14:18:09 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/1F9A/production/_95409080_mediaitem95409079.jpg"/>
        </item>
        <item>
            <title><![CDATA[NHS operations: Waiting times to rise in 'trade-off', boss says]]></title>
            <description><![CDATA[Cancer care and A&E to be prioritised as health service leader in England says something has to give.]]></description>
            <link>http://www.bbc.co.uk/news/health-39420662</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/health-39420662</guid>
            <pubDate>Fri, 31 Mar 2017 10:01:22 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/178D0/production/_95346469_waitingroom.jpg"/>
        </item>
        <item>
            <title><![CDATA[Nicola Sturgeon: 'No rational reason' for Theresa May to block indyref2]]></title>
            <description><![CDATA[Nicola Sturgeon sends a letter to Theresa May seeking powers to hold an independence referendum.]]></description>
            <link>http://www.bbc.co.uk/news/uk-scotland-scotland-politics-39454457</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-scotland-scotland-politics-39454457</guid>
            <pubDate>Fri, 31 Mar 2017 12:53:20 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/17ECF/production/_95399979_c8l0mpcw4aam4hn.jpg"/>
        </item>
        <item>
            <title><![CDATA[Google reveals latest UK tax bill]]></title>
            <description><![CDATA[The search giant was charged £36.4m in UK corporation tax in the year to June 2016.]]></description>
            <link>http://www.bbc.co.uk/news/business-39456662</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/business-39456662</guid>
            <pubDate>Fri, 31 Mar 2017 14:19:00 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/6428/production/_95404652_googlehq.jpg"/>
        </item>
        <item>
            <title><![CDATA[Brexit: MPs angered by EU 'veto' over Gibraltar]]></title>
            <description><![CDATA[British sovereignty is non-negotiable, MPs say, as the EU suggests Spain has a say on future arrangements.]]></description>
            <link>http://www.bbc.co.uk/news/uk-politics-39453535</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-politics-39453535</guid>
            <pubDate>Fri, 31 Mar 2017 14:16:27 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/E6DD/production/_95410195_mediaitem95404515.jpg"/>
        </item>
        <item>
            <title><![CDATA[Meet the fish with the heroin-like bite]]></title>
            <description><![CDATA[Research reveals the toxic secret behind the fang blenny's pain-free bite.]]></description>
            <link>http://www.bbc.co.uk/news/science-environment-39457279</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/science-environment-39457279</guid>
            <pubDate>Fri, 31 Mar 2017 12:27:08 GMT</pubDate>
            <media:thumbnail width="640" height="360" url="http://c.files.bbci.co.uk/185C4/production/_95408799_mediaitem95395107.jpg"/>
        </item>
        <item>
            <title><![CDATA[Bin lorry deaths driver Harry Clarke banned from driving]]></title>
            <description><![CDATA[Harry Clarke was found behind the wheel nine months after the tragedy, despite being unfit to drive.]]></description>
            <link>http://www.bbc.co.uk/news/uk-scotland-glasgow-west-39453847</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-scotland-glasgow-west-39453847</guid>
            <pubDate>Fri, 31 Mar 2017 11:21:22 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/113FA/production/_95405607_harrypa.jpg"/>
        </item>
        <item>
            <title><![CDATA[British endurance cyclist Mike Hall killed in road race]]></title>
            <description><![CDATA[The Indian Pacific Wheel Race was cancelled shortly after Mike Hall died in a collision with a car.]]></description>
            <link>http://www.bbc.co.uk/news/uk-39452786</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-39452786</guid>
            <pubDate>Fri, 31 Mar 2017 09:41:59 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/C04E/production/_95403294_img_0311.jpg"/>
        </item>
        <item>
            <title><![CDATA[Kim Jong-nam: Body 'arrives in Pyongyang' in exchange deal]]></title>
            <description><![CDATA[Nine Malaysians also return home under a deal to end the diplomatic row that followed his death.]]></description>
            <link>http://www.bbc.co.uk/news/world-asia-39452470</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-asia-39452470</guid>
            <pubDate>Fri, 31 Mar 2017 11:52:18 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/DEC6/production/_95403075_mediaitem95403071.jpg"/>
        </item>
        <item>
            <title><![CDATA[Household savings ratio falls to record low, says ONS]]></title>
            <description><![CDATA[The economy was "robust" in late 2016, but economists warn of worrying signs as savings ratio falls.]]></description>
            <link>http://www.bbc.co.uk/news/business-39453844</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/business-39453844</guid>
            <pubDate>Fri, 31 Mar 2017 11:50:22 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/14AA0/production/_95404648_shoppingbagsafp.jpg"/>
        </item>
        <item>
            <title><![CDATA[Stourbridge stabbing Land Rover chase caught on dashcam]]></title>
            <description><![CDATA[The 4x4 was taken from the house in Stourbridge where a husband, wife and their son were attacked.]]></description>
            <link>http://www.bbc.co.uk/news/uk-england-birmingham-39450047</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-england-birmingham-39450047</guid>
            <pubDate>Fri, 31 Mar 2017 10:33:37 GMT</pubDate>
            <media:thumbnail width="464" height="261" url="http://c.files.bbci.co.uk/B734/production/_95400964_p04yk0jw.jpg"/>
        </item>
        <item>
            <title><![CDATA[Fallon and Mattis discussing Nato spending]]></title>
            <description><![CDATA[Defence secretary says other nations should be "shamed" into spending more as he meets US counterpart.]]></description>
            <link>http://www.bbc.co.uk/news/uk-politics-39453527</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-politics-39453527</guid>
            <pubDate>Fri, 31 Mar 2017 11:05:16 GMT</pubDate>
            <media:thumbnail width="1920" height="1080" url="http://c.files.bbci.co.uk/7B34/production/_95404513_mattisfallon.jpg"/>
        </item>
        <item>
            <title><![CDATA[Pamela Anderson's 'love' for Julian Assange]]></title>
            <description><![CDATA[Pamela Anderson says the Wikileaks founder "might be the most famous refugee of our time".]]></description>
            <link>http://www.bbc.co.uk/news/uk-39453297</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-39453297</guid>
            <pubDate>Fri, 31 Mar 2017 11:43:37 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/7256/production/_95407292_3f06abae-a00f-4d1e-b1b0-917a9a14cd29.jpg"/>
        </item>
        <item>
            <title><![CDATA[Quiz: Which airline stopped girls in leggings from flying?]]></title>
            <description><![CDATA[A weekly quiz of the news, 7 days 7 questions.]]></description>
            <link>http://www.bbc.co.uk/news/magazine-39432281</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/magazine-39432281</guid>
            <pubDate>Thu, 30 Mar 2017 23:52:21 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/131F9/production/_95392387_leggings.jpg"/>
        </item>
        <item>
            <title><![CDATA[James Van Der Beek and his awkward Dawson's Creek interview questions]]></title>
            <description><![CDATA[Why are chat show hosts putting the former Dawson's Creek star through such awkward interviews?]]></description>
            <link>http://www.bbc.co.uk/news/entertainment-arts-39453507</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/entertainment-arts-39453507</guid>
            <pubDate>Fri, 31 Mar 2017 12:13:55 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/9F38/production/_95406704_cryingface_tns.jpg"/>
        </item>
        <item>
            <title><![CDATA[The rapping hijabi lights up social media]]></title>
            <description><![CDATA[Find out what's buzzing in the social media world today.]]></description>
            <link>http://www.bbc.co.uk/news/blogs-trending-39453357</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/blogs-trending-39453357</guid>
            <pubDate>Fri, 31 Mar 2017 13:25:57 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/5DB6/production/_95409932_video.jpg"/>
        </item>
        <item>
            <title><![CDATA[What gifts has Theresa May been given?]]></title>
            <description><![CDATA[Like all prime ministers, Theresa May is showered with gifts but she does not keep many of them.]]></description>
            <link>http://www.bbc.co.uk/news/uk-politics-39453348</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-politics-39453348</guid>
            <pubDate>Fri, 31 Mar 2017 09:38:00 GMT</pubDate>
            <media:thumbnail width="768" height="432" url="http://c.files.bbci.co.uk/1A54/production/_95404760_mediaitem95404759.jpg"/>
        </item>
        <item>
            <title><![CDATA[Flying Scotsman marks Carlisle-to-Settle line reopening]]></title>
            <description><![CDATA[The Settle-to-Carlisle line was closed for 13 months after a 500,000-tonne landslip.]]></description>
            <link>http://www.bbc.co.uk/news/uk-england-39447835</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-england-39447835</guid>
            <pubDate>Fri, 31 Mar 2017 11:44:29 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/5FF0/production/_95406542_hi038779955.jpg"/>
        </item>
        <item>
            <title><![CDATA[Hedgehog-like critters arrive at Chester Zoo]]></title>
            <description><![CDATA[Its stripes are more like a bumblebee's.]]></description>
            <link>http://www.bbc.co.uk/news/uk-39450981</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-39450981</guid>
            <pubDate>Fri, 31 Mar 2017 05:25:23 GMT</pubDate>
            <media:thumbnail width="1024" height="576" url="http://c.files.bbci.co.uk/16A80/production/_95400829_p04yl72d.jpg"/>
        </item>
        <item>
            <title><![CDATA['Inspiring' ex-teacher helps disabled children]]></title>
            <description><![CDATA[The story of the former teacher who has set up a Facebook page for interviews with the children.]]></description>
            <link>http://www.bbc.co.uk/news/education-39387883</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/education-39387883</guid>
            <pubDate>Thu, 30 Mar 2017 23:53:19 GMT</pubDate>
            <media:thumbnail width="1024" height="579" url="http://c.files.bbci.co.uk/126AF/production/_95393457_p04yhg6n.jpg"/>
        </item>
        <item>
            <title><![CDATA[Africa's top shots: 24-30 March 2017]]></title>
            <description><![CDATA[A selection of the best photos from across Africa this week.]]></description>
            <link>http://www.bbc.co.uk/news/world-africa-39442192</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-africa-39442192</guid>
            <pubDate>Thu, 30 Mar 2017 23:46:14 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/DE25/production/_95396865_mediaitem95395499.jpg"/>
        </item>
        <item>
            <title><![CDATA[Ivanka Trump steps into White House ethics minefield]]></title>
            <description><![CDATA[Donald Trump's daughter has to circumvent conflicts of interest laws in her new job.]]></description>
            <link>http://www.bbc.co.uk/news/world-us-canada-32022516</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-us-canada-32022516</guid>
            <pubDate>Thu, 30 Mar 2017 22:36:43 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://c.files.bbci.co.uk/0C1C/production/_95400130_hi038717283.jpg"/>
        </item>
        <item>
            <title><![CDATA[Cat ownership rise driven by men, survey suggests]]></title>
            <description><![CDATA[There are now eight million pet cats in the UK - 500,000 more than in 2016, a survey suggests.]]></description>
            <link>http://www.bbc.co.uk/news/uk-39440934</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-39440934</guid>
            <pubDate>Thu, 30 Mar 2017 10:18:11 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/ECB6/production/_95389506_hughwithnigel.jpg"/>
        </item>
        <item>
            <title><![CDATA[Is 'luxury co-living' a solution to loneliness in big cities?]]></title>
            <description><![CDATA[Could student hall-style accommodation for young professionals tackle loneliness in big cities?]]></description>
            <link>http://www.bbc.co.uk/news/magazine-39381920</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/magazine-39381920</guid>
            <pubDate>Wed, 29 Mar 2017 23:31:45 GMT</pubDate>
            <media:thumbnail width="1920" height="1080" url="http://c.files.bbci.co.uk/13AD5/production/_95379508_womenlaughingcut.jpg"/>
        </item>
        <item>
            <title><![CDATA[Thirsty snake drinks from water bottle]]></title>
            <description><![CDATA[A cobra in a drought-hit village in India has been filmed drinking water from a bottle.]]></description>
            <link>http://www.bbc.co.uk/news/world-asia-39444601</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-asia-39444601</guid>
            <pubDate>Thu, 30 Mar 2017 12:26:18 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/1011B/production/_95391856_p04yh96f.jpg"/>
        </item>
        <item>
            <title><![CDATA[BBC News Channel]]></title>
            <description><![CDATA[BBC coverage of latest developments]]></description>
            <link>http://www.bbc.co.uk/news/10318089</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/10318089</guid>
            <pubDate>Fri, 17 Feb 2017 09:41:12 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://news.bbcimg.co.uk/media/images/83122000/png/_83122356_globe_2048x1152.png"/>
        </item>
        <item>
            <title><![CDATA[Peter Taylor: How has terror changed in 50 years?]]></title>
            <description><![CDATA[The threat from terrorism is always evolving, but some things are constant, writes Peter Taylor.]]></description>
            <link>http://www.bbc.co.uk/news/uk-39432041</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/uk-39432041</guid>
            <pubDate>Thu, 30 Mar 2017 23:54:44 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/7403/production/_95399692_car_bbc_976.jpg"/>
        </item>
        <item>
            <title><![CDATA[Meet the Hunter Troop: Norway's tough-as-nails female soldiers]]></title>
            <description><![CDATA[Meet the Norwegian women going through gruelling special forces training.]]></description>
            <link>http://www.bbc.co.uk/news/world-europe-39434655</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-europe-39434655</guid>
            <pubDate>Thu, 30 Mar 2017 23:17:14 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/13EDD/production/_95392618_screenshot2017-03-28at12.09.02.png"/>
        </item>
        <item>
            <title><![CDATA[Inside France's young far-right]]></title>
            <description><![CDATA[A new generation of far-right activists have found a home in the Front National.]]></description>
            <link>http://www.bbc.co.uk/news/world-europe-39448615</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-europe-39448615</guid>
            <pubDate>Fri, 31 Mar 2017 02:32:02 GMT</pubDate>
            <media:thumbnail width="1024" height="576" url="http://c.files.bbci.co.uk/A51E/production/_95407224_p04ymgvl.jpg"/>
        </item>
        <item>
            <title><![CDATA[Prince's Sign O' The Times, 30 years on]]></title>
            <description><![CDATA[A look at the making of Prince's masterpiece, by the people who were there.]]></description>
            <link>http://www.bbc.co.uk/news/entertainment-arts-39441461</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/entertainment-arts-39441461</guid>
            <pubDate>Thu, 30 Mar 2017 23:56:02 GMT</pubDate>
            <media:thumbnail width="1024" height="576" url="http://c.files.bbci.co.uk/1764/production/_95388950_prince-sign-wanrers.jpg"/>
        </item>
        <item>
            <title><![CDATA[Masters 2017: Danny Willett - inside the ropes with a Masters winner]]></title>
            <description><![CDATA[Masters champion Danny Willett and his caddie Jonathan Swift talk us through their sensational back nine at Augusta to win the 2016 title.]]></description>
            <link>http://www.bbc.co.uk/sport/golf/39420176</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/sport/golf/39420176</guid>
            <pubDate>Fri, 31 Mar 2017 05:50:42 GMT</pubDate>
            <media:thumbnail width="624" height="351" url="http://c.files.bbci.co.uk/16198/production/_95402509_willett_green.jpg"/>
        </item>
        <item>
            <title><![CDATA[Information warfare: Is Russia really interfering in European states?]]></title>
            <description><![CDATA[How Russia became an expert at information warfare - and the risks that poses for Europe.]]></description>
            <link>http://www.bbc.co.uk/news/world-europe-39401637</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-europe-39401637</guid>
            <pubDate>Thu, 30 Mar 2017 23:53:30 GMT</pubDate>
            <media:thumbnail width="976" height="549" url="http://c.files.bbci.co.uk/9218/production/_95400473_038660798-1.jpg"/>
        </item>
        <item>
            <title><![CDATA[Can China's ivory trade ban save elephants?]]></title>
            <description><![CDATA[China begins closing down its legal ivory trade, but will consumer attitudes to prized artwork change?]]></description>
            <link>http://www.bbc.co.uk/news/world-asia-china-39440486</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-asia-china-39440486</guid>
            <pubDate>Thu, 30 Mar 2017 23:27:04 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://c.files.bbci.co.uk/16B15/production/_95394929_gettyimages-141628727.jpg"/>
        </item>
        <item>
            <title><![CDATA[Three words to set alarm bells off for every firm]]></title>
            <description><![CDATA[Incidents of fraudsters posing as the boss and demanding staff make payments is on the rise.]]></description>
            <link>http://www.bbc.co.uk/news/business-39429819</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/business-39429819</guid>
            <pubDate>Thu, 30 Mar 2017 23:05:39 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://c.files.bbci.co.uk/1520C/production/_95404568_womanheadinhandsgetty.jpg"/>
        </item>
        <item>
            <title><![CDATA[The joy and sadness of returning to Mosul]]></title>
            <description><![CDATA[BBC Arabic's Basheer Al Zaidi returns to his hometown of Mosul to find out how life has changed after the end of occupation by so-called Islamic State.]]></description>
            <link>http://www.bbc.co.uk/news/world-middle-east-39437227</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/news/world-middle-east-39437227</guid>
            <pubDate>Thu, 30 Mar 2017 23:21:32 GMT</pubDate>
            <media:thumbnail width="1920" height="1080" url="http://c.files.bbci.co.uk/14F95/production/_95390958_mosul2.jpg"/>
        </item>
        <item>
            <title><![CDATA[Man Utd: Chris Smalling & Phil Jones suffered 'long term' injuries]]></title>
            <description><![CDATA[The injuries suffered by defenders Chris Smalling and Phil Jones on England duty are "long term", says their Manchester United manager Jose Mourinho.]]></description>
            <link>http://www.bbc.co.uk/sport/football/39454470</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/sport/football/39454470</guid>
            <pubDate>Fri, 31 Mar 2017 14:03:48 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://c.files.bbci.co.uk/373C/production/_95404141_jones_smalling_empics.jpg"/>
        </item>
        <item>
            <title><![CDATA[Saido Berahino: Drugs ban from a spiked drink, says Stoke striker]]></title>
            <description><![CDATA[Stoke striker Saido Berahino tells Football Focus the eight-week drugs ban he served this season came after his drink was spiked.]]></description>
            <link>http://www.bbc.co.uk/sport/football/39450446</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/sport/football/39450446</guid>
            <pubDate>Thu, 30 Mar 2017 20:33:06 GMT</pubDate>
            <media:thumbnail width="624" height="351" url="http://c.files.bbci.co.uk/A6CC/production/_95400724_saidoberahino.jpg"/>
        </item>
        <item>
            <title><![CDATA[PFA Player of the Year: BBC pundits pick the Premier League's best player]]></title>
            <description><![CDATA[With voting for the PFA Player of the Year award about to close, 15 BBC pundits reveal who they think should land the prize.]]></description>
            <link>http://www.bbc.co.uk/sport/football/39429946</link>
            <guid isPermaLink="true">http://www.bbc.co.uk/sport/football/39429946</guid>
            <pubDate>Thu, 30 Mar 2017 23:04:42 GMT</pubDate>
            <media:thumbnail width="2048" height="1152" url="http://c.files.bbci.co.uk/C47C/production/_95400305_kantezlatanhazard.jpg"/>
        </item>
    </channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\View;

/**
 * The navigation element
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class NavigationElement
{
    /**
     * @var string
     */
    protected $label;

    /**
     * @var string
     */
    protected $routeName;

    /**
     * @var array
     */
    protected $routeParams;

    /**
     * @var string
     */
    protected $icon;

    /**
     * @var string[]
     */
    protected $requiredPermissions;

    /**
     * @var bool
     */
    protected $requiresAnyFromGroups;

    /**
     * NavigationElement constructor.
     *
     * @param string   $label
     * @param string   $routeName
     * @param array    $routeParams
     * @param string   $icon
     * @param string[] $requiredPermissionNames
     * @param bool     $requiresAnyFromGroups
     */
    public function __construct(
        string $label,
        string $routeName,
        array $routeParams,
        string $icon,
        array $requiredPermissionNames = [],
        bool $requiresAnyFromGroups = false
    ) {
        $this->label                 = $label;
        $this->routeName             = $routeName;
        $this->routeParams           = $routeParams;
        $this->icon                  = $icon;
        $this->requiredPermissions   = $requiredPermissionNames;
        $this->requiresAnyFromGroups = $requiresAnyFromGroups;
    }

    /**
     * @return string
     */
    public function getLabel() : string
    {
        return $this->label;
    }

    /**
     * @return string
     */
    public function getIcon() : string
    {
        return $this->icon;
    }

    /**
     * @return string
     */
    public function getUrl() : string
    {
        return route($this->routeName, $this->routeParams);
    }

    /**
     * @param array $usersPermissionNames
     *
     * @return bool
     */
    public function shouldDisplay(array $usersPermissionNames) : bool
    {
        if ($this->requiresAnyFromGroups) {
            foreach ($this->requiredPermissions as $group) {
                if (count(array_diff($group, $usersPermissionNames)) === 0) {
                    return true;
                }
            }

            return false;
        } else {
            return count(array_diff($this->requiredPermissions, $usersPermissionNames)) === 0;
        }
    }
}


text:
#import <iWorkImport/KNAnimationEffect.h>

#import "KNTransitionAnimator-Protocol.h"

@class KNAnimParameterGroup;

// Not exported
@interface KNTransitionDoorway : KNAnimationEffect <KNTransitionAnimator>
{
    KNAnimParameterGroup *_parameterGroup;
}

+ (id)thumbnailImageNameForType:(int)arg1;
+ (id)defaultAttributes;
+ (void)fillLocalizedDirectionMenu:(id)arg1 forType:(int)arg2;
+ (unsigned long long)directionType;
+ (id)localizedMenuString:(int)arg1;
+ (id)supportedTypes;
+ (id)animationFilter;
+ (int)animationCategory;
+ (id)animationName;
- (id)animationsWithContext:(id)arg1;
- (void)dealloc;
- (id)initWithAnimationContext:(id)arg1;

@end


text:
package io.moquette.server;

import java.io.IOException;

import io.moquette.server.config.IConfig;
import io.moquette.spi.impl.ProtocolProcessor;
import io.moquette.spi.security.ISslContextCreator;

/**
 *
 * @author andrea
 */
public interface ServerAcceptor {

    void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator) throws IOException;

    void close();
}


text:
from __future__ import absolute_import, print_function, unicode_literals

from .base import BasePlatform

class FriendCodePlatform(BasePlatform):
    DOMAINS = ('friendco.de',)
    PATTERNS = {
        'https': r'https://(?P<domain>.+)/(?P<owner>.+)@user/(?P<repo>.+).git',
    }
    FORMATS = {
        'https': r'https://%(domain)s/%(owner)s@user/%(repo)s.git',
    }


text:
<?php

namespace system\http;

/**
 * Simple cookie class
 * @author Jhobanny Morillo <geomorillo@yahoo.com>
 * @date June 10, 2015
 */
class Cookie {

    public static function exists($key) {
        if (isset($_COOKIE[$key])) {
            return true;
        } else {
            return false;
        }
    }

    public static function set($key, $value, $expiry = 126144000, $path = "/", $domain = false) {
        $retval = false;
        if (!headers_sent()) {
            if ($domain === false)
                $domain = $_SERVER['HTTP_HOST'];

            if ($expiry === -1)
                $expiry = 1893456000; // Lifetime = 2030-01-01 00:00:00
            elseif (is_numeric($expiry))
                $expiry += time();
            else
                $expiry = strtotime($expiry);

            $retval = @setcookie($key, $value, $expiry, $path, $domain);
            if ($retval)
                $_COOKIE[$key] = $value;
        }
        return $retval;
    }

    public static function get($key, $default = '') {
        return (isset($_COOKIE[$key]) ? $_COOKIE[$key] : $default);
    }

    public static function display() {
        return $_COOKIE;
    }

    public static function destroy($key, $value = '', $path = "/",$domain=".test.geo") {
        if (isset($_COOKIE[$key])) {
            $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
            unset($_COOKIE[$key]);
            setcookie($key, $value, time() - 3600, $path,$domain);
        }
    }

}


text:
namespace SampleFramework12
{

// == DescriptorHeap ==============================================================================

DescriptorHeap::~DescriptorHeap()
{
    Assert_(Heap == nullptr);
}

void DescriptorHeap::Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible)
{
    Shutdown();
    Assert_(numDescriptors > 0);

    NumDescriptors = numDescriptors;
    HeapType = heapType;
    ShaderVisible = shaderVisible;
    if(heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV)
        ShaderVisible = false;

    DeadList.Init(numDescriptors);
    for(uint64 i = 0; i < numDescriptors; ++i)
        DeadList[i] = uint32(i);

    D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { };
    heapDesc.NumDescriptors = uint32(numDescriptors);
    heapDesc.Type = heapType;
    heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    if(ShaderVisible)
        heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;

    DXCall(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&Heap)));

    CPUStart = Heap->GetCPUDescriptorHandleForHeapStart();
    if(ShaderVisible)
        GPUStart = Heap->GetGPUDescriptorHandleForHeapStart();

    DescriptorSize = device->GetDescriptorHandleIncrementSize(heapType);
}

void DescriptorHeap::Shutdown()
{
    Assert_(Allocated == 0);
    DX12::Release(Heap);
}

DescriptorHandle DescriptorHeap::Allocate()
{
    Assert_(Heap != nullptr);

    AcquireSRWLockExclusive(&Lock);

    Assert_(Allocated < NumDescriptors);
    uint64 idx = DeadList[Allocated];
    ++Allocated;

    ReleaseSRWLockExclusive(&Lock);

    DescriptorHandle handle;
    handle.CPUHandle = CPUStart;
    handle.CPUHandle.ptr += idx * DescriptorSize;
    if(ShaderVisible)
    {
        handle.GPUHandle = GPUStart;
        handle.GPUHandle.ptr += idx * DescriptorSize;
    }

    #if UseAsserts_
        handle.ParentHeap = reinterpret_cast<const void*>(this);
    #endif

    return handle;
}

void DescriptorHeap::Free(DescriptorHandle& handle)
{
    if(handle.IsValid() == false)
        return;

    #if UseAsserts_
        Assert_(reinterpret_cast<const void*>(this) == handle.ParentHeap);
    #endif

    Assert_(Heap != nullptr);
    Assert_(handle.CPUHandle.ptr >= CPUStart.ptr);
    uint64 heapIdx = (handle.CPUHandle.ptr - CPUStart.ptr) / DescriptorSize;
    Assert_(heapIdx < NumDescriptors);

    AcquireSRWLockExclusive(&Lock);

    Assert_(Allocated > 0);
    DeadList[Allocated - 1] = uint32(heapIdx);
    --Allocated;

    ReleaseSRWLockExclusive(&Lock);

    handle = DescriptorHandle();
}

// == LinearDescriptorHeap ========================================================================

LinearDescriptorHeap::~LinearDescriptorHeap()
{
    Assert_(Heap == nullptr);
}

void LinearDescriptorHeap::Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible)
{
    Shutdown();

    Assert_(numDescriptors > 0);

    Allocated = 0;
    NumDescriptors = numDescriptors;
    HeapType = heapType;
    ShaderVisible = shaderVisible;
    if (heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV)
        ShaderVisible = false;

    D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { };
    heapDesc.NumDescriptors = uint32(numDescriptors);
    heapDesc.Type = heapType;
    heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    if(ShaderVisible)
        heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;

    DXCall(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&Heap)));

    CPUStart = Heap->GetCPUDescriptorHandleForHeapStart();
    if(ShaderVisible)
        GPUStart = Heap->GetGPUDescriptorHandleForHeapStart();

    DescriptorSize = device->GetDescriptorHandleIncrementSize(heapType);
}

void LinearDescriptorHeap::Shutdown()
{
    DX12::Release(Heap);
}

DescriptorHandle LinearDescriptorHeap::Allocate(uint64 count)
{
    Assert_(Heap != nullptr);
    Assert_(count > 0);

    int64 idx = InterlockedAdd64(&Allocated, count) - count;
    Assert_(uint64(idx) < NumDescriptors);

    DescriptorHandle handle;
    handle.CPUHandle = CPUStart;
    handle.CPUHandle.ptr += idx * DescriptorSize;
    if(ShaderVisible)
    {
        handle.GPUHandle = GPUStart;
        handle.GPUHandle.ptr += idx * DescriptorSize;
    }

    Allocated += count;

    return handle;
}

void LinearDescriptorHeap::Reset()
{
    Allocated = 0;
}

// == Buffer ======================================================================================

Buffer::Buffer()
{
}

Buffer::~Buffer()
{
    Assert_(Resource == nullptr);
}

void Buffer::Initialize(uint64 size, uint64 alignment, bool32 dynamic, BufferLifetime lifetime, bool32 allowUAV,
                        const void* initData, D3D12_RESOURCE_STATES initialState, ID3D12Heap* heap, uint64 heapOffset,
                        const wchar* name)
{
    Assert_(size > 0);
    Assert_(alignment > 0);

    Size = AlignTo(size, alignment);
    Alignment = alignment;
    Lifetime = lifetime;
    Dynamic = dynamic;
    CurrBuffer = 0;
    CPUAddress = nullptr;
    GPUAddress = 0;
    Heap = nullptr;
    HeapOffset = 0;

    Assert_(Lifetime == BufferLifetime::Persistent || dynamic);
    Assert_(allowUAV == false || dynamic == false);

    if(Lifetime == BufferLifetime::Persistent)
    {
        D3D12_RESOURCE_DESC resourceDesc = { };
        resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
        resourceDesc.Width = dynamic ? Size * DX12::RenderLatency : Size;
        resourceDesc.Height = 1;
        resourceDesc.DepthOrArraySize = 1;
        resourceDesc.MipLevels = 1;
        resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
        resourceDesc.Flags = allowUAV ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE;
        resourceDesc.SampleDesc.Count = 1;
        resourceDesc.SampleDesc.Quality = 0;
        resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
        resourceDesc.Alignment = 0;

        const D3D12_HEAP_PROPERTIES* heapProps = dynamic ? DX12::GetUploadHeapProps() : DX12::GetDefaultHeapProps();
        D3D12_RESOURCE_STATES resourceState = initialState;
        if(initData && dynamic == false)
            resourceState = D3D12_RESOURCE_STATE_COPY_DEST;

        if(heap)
        {
            Heap = heap;
            HeapOffset = heapOffset;
            DXCall(DX12::Device->CreatePlacedResource(heap, heapOffset, &resourceDesc, resourceState,
                                                      nullptr, IID_PPV_ARGS(&Resource)));
        }
        else
        {
            DXCall(DX12::Device->CreateCommittedResource(heapProps, D3D12_HEAP_FLAG_NONE, &resourceDesc,
                                                         resourceState, nullptr, IID_PPV_ARGS(&Resource)));
        }

        if(name)
            Resource->SetName(name);

        GPUAddress = Resource->GetGPUVirtualAddress();

        if(dynamic)
        {
            D3D12_RANGE readRange = { };
            DXCall(Resource->Map(0, &readRange, reinterpret_cast<void**>(&CPUAddress)));
        }

        if(initData && dynamic)
        {
            for(uint64 i = 0; i < DX12::RenderLatency; ++i)
            {
                uint8* dstMem = CPUAddress + Size * i;
                memcpy(dstMem, initData, size);
            }

        }
        else if(initData)
        {
            UploadContext uploadContext = DX12::ResourceUploadBegin(resourceDesc.Width);

            memcpy(uploadContext.CPUAddress, initData, size);

            uploadContext.CmdList->CopyBufferRegion(Resource, 0, uploadContext.Resource, uploadContext.ResourceOffset, size);

            DX12::ResourceUploadEnd(uploadContext);
        }
    }
}

void Buffer::Shutdown()
{
    DX12::DeferredRelease(Resource);
}

MapResult Buffer::Map()
{
    Assert_(Initialized());
    Assert_(Dynamic);

    if(Lifetime == BufferLifetime::Persistent)
    {
        #if UseAsserts_
            // Make sure that we onlt do this at most once per frame
            Assert_(UploadFrame != DX12::CurrentCPUFrame);
            UploadFrame = DX12::CurrentCPUFrame;
        #endif
        CurrBuffer = (CurrBuffer + 1) % DX12::RenderLatency;

        MapResult result;
        result.ResourceOffset = CurrBuffer * Size;
        result.CPUAddress = CPUAddress + CurrBuffer * Size;
        result.GPUAddress = GPUAddress + CurrBuffer * Size;
        result.Resource = Resource;
        return result;
    }
    else
    {
        Assert_(Lifetime == BufferLifetime::Temporary);

        #if UseAsserts_
            UploadFrame = DX12::CurrentCPUFrame;
        #endif

        return DX12::AcquireTempBufferMem(Size, Alignment);
    }
}

MapResult Buffer::MapAndSetData(const void* data, uint64 dataSize)
{
    Assert_(dataSize <= Size);
    MapResult result = Map();
    memcpy(result.CPUAddress, data, dataSize);
    return result;
}

void Buffer::UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset)
{
    Assert_(Dynamic == false);
    Assert_(dstOffset + srcSize <= Size);

    UploadContext uploadContext = DX12::ResourceUploadBegin(srcSize);

    memcpy(uploadContext.CPUAddress, srcData, srcSize);

    uploadContext.CmdList->CopyBufferRegion(Resource, dstOffset, uploadContext.Resource, uploadContext.ResourceOffset, srcSize);

    DX12::ResourceUploadEnd(uploadContext);
}

void Buffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const
{
    Assert_(Resource != nullptr);
    DX12::TransitionResource(cmdList, Resource, before, after);
}

void Buffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const
{
    Assert_(Resource != nullptr);
    DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_GENERIC_READ);
}

void Buffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const
{
    Assert_(Resource != nullptr);
    DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
}

void Buffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const
{
    Assert_(Resource != nullptr);
    D3D12_RESOURCE_BARRIER barrier = { };
    barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
    barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
    barrier.UAV.pResource = Resource;
    cmdList->ResourceBarrier(1, &barrier);
}

#if UseAsserts_

bool Buffer::ReadyForBinding() const
{
    if(Dynamic && Lifetime == BufferLifetime::Temporary)
        return UploadFrame == DX12::CurrentCPUFrame;
    else
        return Initialized();
}

#endif

// == StructuredBuffer ============================================================================

StructuredBuffer::StructuredBuffer()
{

}

StructuredBuffer::~StructuredBuffer()
{
    Assert_(NumElements == 0);
    Shutdown();
}

void StructuredBuffer::Initialize(const StructuredBufferInit& init)
{
    Shutdown();

    Assert_(init.Stride > 0);
    Assert_(init.NumElements > 0);
    Stride = init.Stride;
    NumElements = init.NumElements;

    InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV,
                              init.InitData, init.InitialState, init.Heap, init.HeapOffset, init.Name);
    GPUAddress = InternalBuffer.GPUAddress;

    if(init.Lifetime == BufferLifetime::Persistent)
    {
        const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1;
        for(uint64 i = 0; i < numSRVs; ++i)
        {
            SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate();

            D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
            srvDesc.Format = DXGI_FORMAT_UNKNOWN;
            srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
            srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
            srvDesc.Buffer.FirstElement = uint32(NumElements * i);
            srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
            srvDesc.Buffer.NumElements = uint32(NumElements);
            srvDesc.Buffer.StructureByteStride = uint32(Stride);
            DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle);
        }
    }
    else if(init.Lifetime == BufferLifetime::Temporary)
    {
        SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate();
    }

    if(init.CreateUAV)
    {
        Assert_(init.Dynamic == false);

        ID3D12Resource* counterRes = nullptr;
        if(init.UseCounter)
        {
            D3D12_RESOURCE_DESC resourceDesc = { };
            resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
            resourceDesc.Width = sizeof(uint32);
            resourceDesc.Height = 1;
            resourceDesc.DepthOrArraySize = 1;
            resourceDesc.MipLevels = 1;
            resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
            resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
            resourceDesc.SampleDesc.Count = 1;
            resourceDesc.SampleDesc.Quality = 0;
            resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
            resourceDesc.Alignment = 0;
            DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc,
                                                         D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&CounterResource)));

            counterRes = CounterResource;

            CounterUAV = DX12::SRVDescriptorHeap.Allocate();

            D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
            uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
            uavDesc.Format = DXGI_FORMAT_UNKNOWN;
            uavDesc.Buffer.CounterOffsetInBytes = 0;
            uavDesc.Buffer.FirstElement = 0;
            uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
            uavDesc.Buffer.NumElements = 1;
            uavDesc.Buffer.StructureByteStride = sizeof(uint32);

            DX12::Device->CreateUnorderedAccessView(counterRes, nullptr, &uavDesc, CounterUAV.CPUHandle);
        }

        UAVHandle = DX12::SRVDescriptorHeap.Allocate();

        D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { };
        uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
        uavDesc.Format = DXGI_FORMAT_UNKNOWN;
        uavDesc.Buffer.CounterOffsetInBytes = 0;
        uavDesc.Buffer.FirstElement = 0;
        uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
        uavDesc.Buffer.NumElements = uint32(NumElements);
        uavDesc.Buffer.StructureByteStride = uint32(Stride);

        DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, counterRes, &uavDesc, UAVHandle.CPUHandle);
    }
}

void StructuredBuffer::Shutdown()
{
    for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i)
        DX12::SRVDescriptorHeap.Free(SRVHandles[i]);
    DX12::SRVDescriptorHeap.Free(UAVHandle);
    DX12::SRVDescriptorHeap.Free(CounterUAV);
    InternalBuffer.Shutdown();
    DX12::DeferredRelease(CounterResource);
    Stride = 0;
    NumElements = 0;
}

D3D12_CPU_DESCRIPTOR_HANDLE StructuredBuffer::SRV() const
{
    Assert_(InternalBuffer.ReadyForBinding());
    Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid());
    return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle;
}

D3D12_CPU_DESCRIPTOR_HANDLE StructuredBuffer::UAV() const
{
    Assert_(UAVHandle.IsValid());
    return UAVHandle.CPUHandle;
}

D3D12_VERTEX_BUFFER_VIEW StructuredBuffer::VBView() const
{
    Assert_(InternalBuffer.ReadyForBinding());
    D3D12_VERTEX_BUFFER_VIEW vbView = { };
    vbView.BufferLocation = GPUAddress;
    vbView.StrideInBytes = uint32(Stride);
    vbView.SizeInBytes = uint32(InternalBuffer.Size);
    return vbView;
}

void* StructuredBuffer::Map()
{
    MapResult mapResult = InternalBuffer.Map();
    if(InternalBuffer.Lifetime == BufferLifetime::Temporary)
    {
        Assert_(SRVHandles[0].IsValid());
        Assert_(mapResult.ResourceOffset % Stride == 0);

        D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
        srvDesc.Format = DXGI_FORMAT_UNKNOWN;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
        srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride);
        srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
        srvDesc.Buffer.NumElements = uint32(NumElements);
        srvDesc.Buffer.StructureByteStride = uint32(Stride);
        DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle);
    }

    GPUAddress = mapResult.GPUAddress;

    return mapResult.CPUAddress;
}

void StructuredBuffer::MapAndSetData(const void* data, uint64 numElements)
{
    Assert_(numElements <= NumElements);
    void* cpuAddr = Map();
    memcpy(cpuAddr, data, numElements * Stride);
}

void StructuredBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset)
{
    InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride);
}

void StructuredBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const
{
    InternalBuffer.Transition(cmdList, before, after);
}

void StructuredBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeReadable(cmdList);
}

void StructuredBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeWritable(cmdList);
}

void StructuredBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.UAVBarrier(cmdList);
}

// == FormattedBuffer ============================================================================

FormattedBuffer::FormattedBuffer()
{
}

FormattedBuffer::~FormattedBuffer()
{
    Assert_(NumElements == 0);
    Shutdown();
}

void FormattedBuffer::Initialize(const FormattedBufferInit& init)
{
    Shutdown();

    Assert_(init.Format != DXGI_FORMAT_UNKNOWN);
    Assert_(init.NumElements > 0);
    Stride = DirectX::BitsPerPixel(init.Format) / 8;
    NumElements = init.NumElements;
    Format = init.Format;

    InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV,
                              init.InitData, init.InitialState, init.Heap, init.HeapOffset, init.Name);
    GPUAddress = InternalBuffer.GPUAddress;

    if(init.Lifetime == BufferLifetime::Persistent)
    {
        const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1;
        for(uint64 i = 0; i < numSRVs; ++i)
        {
            SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate();

            D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
            srvDesc.Format = Format;
            srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
            srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
            srvDesc.Buffer.FirstElement = uint32(NumElements * i);
            srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
            srvDesc.Buffer.NumElements = uint32(NumElements);
            DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle);
        }
    }
    else if(init.Lifetime == BufferLifetime::Temporary)
    {
        SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate();
    }

    if(init.CreateUAV)
    {
        Assert_(init.Dynamic == false);

        UAVHandle = DX12::SRVDescriptorHeap.Allocate();

        D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { };
        uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
        uavDesc.Format = Format;
        uavDesc.Buffer.CounterOffsetInBytes = 0;
        uavDesc.Buffer.FirstElement = 0;
        uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
        uavDesc.Buffer.NumElements = uint32(NumElements);

        DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAVHandle.CPUHandle);
    }
}

void FormattedBuffer::Shutdown()
{
    for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i)
        DX12::SRVDescriptorHeap.Free(SRVHandles[i]);
    DX12::SRVDescriptorHeap.Free(UAVHandle);
    InternalBuffer.Shutdown();
    Stride = 0;
    NumElements = 0;
}

D3D12_CPU_DESCRIPTOR_HANDLE FormattedBuffer::SRV() const
{
    Assert_(InternalBuffer.ReadyForBinding());
    Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid());
    return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle;
}

D3D12_CPU_DESCRIPTOR_HANDLE FormattedBuffer::UAV() const
{
    Assert_(UAVHandle.IsValid());
    return UAVHandle.CPUHandle;
}

D3D12_INDEX_BUFFER_VIEW FormattedBuffer::IBView() const
{
    Assert_(Format == DXGI_FORMAT_R16_UINT || Format == DXGI_FORMAT_R32_UINT);
    D3D12_INDEX_BUFFER_VIEW ibView = { };
    ibView.BufferLocation = GPUAddress;
    ibView.Format = Format;
    ibView.SizeInBytes = uint32(InternalBuffer.Size);
    return ibView;
}

void* FormattedBuffer::Map()
{
    MapResult mapResult = InternalBuffer.Map();
    if(InternalBuffer.Lifetime == BufferLifetime::Temporary)
    {
        Assert_(SRVHandles[0].IsValid());
        Assert_(mapResult.ResourceOffset % Stride == 0);

        D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
        srvDesc.Format = Format;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
        srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride);
        srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
        srvDesc.Buffer.NumElements = uint32(NumElements);
        DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle);
    }

    GPUAddress = mapResult.GPUAddress;
    return mapResult.CPUAddress;
}

void FormattedBuffer::MapAndSetData(const void* data, uint64 numElements)
{
    Assert_(numElements <= NumElements);
    void* cpuAddr = Map();
    memcpy(cpuAddr, data, numElements * Stride);
}

void FormattedBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset)
{
    InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride);
}

void FormattedBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const
{
    InternalBuffer.Transition(cmdList, before, after);
}

void FormattedBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeReadable(cmdList);
}

void FormattedBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeWritable(cmdList);
}

void FormattedBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.UAVBarrier(cmdList);
}

// == RawBuffer ============================================================================

RawBuffer::RawBuffer()
{
}

RawBuffer::~RawBuffer()
{
    Assert_(NumElements == 0);
    Shutdown();
}

void RawBuffer::Initialize(const RawBufferInit& init)
{
    Shutdown();

    Assert_(init.NumElements > 0);
    NumElements = init.NumElements;

    InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV, init.InitData,
                              init.InitialState, init.Heap, init.HeapOffset, init.Name);
    GPUAddress = InternalBuffer.GPUAddress;

    if(init.Lifetime == BufferLifetime::Persistent)
    {
        const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1;
        for(uint64 i = 0; i < numSRVs; ++i)
        {
            SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate();

            D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
            srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
            srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
            srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
            srvDesc.Buffer.FirstElement = uint32(NumElements * i);
            srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
            srvDesc.Buffer.NumElements = uint32(NumElements);
            DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle);
        }
    }
    else if(init.Lifetime == BufferLifetime::Temporary)
    {
        SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate();
    }

    if(init.CreateUAV)
    {
        Assert_(init.Dynamic == false);

        UAVHandle = DX12::SRVDescriptorHeap.Allocate();

        D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { };
        uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
        uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
        uavDesc.Buffer.CounterOffsetInBytes = 0;
        uavDesc.Buffer.FirstElement = 0;
        uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
        uavDesc.Buffer.NumElements = uint32(NumElements);

        DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAVHandle.CPUHandle);
    }
}

void RawBuffer::Shutdown()
{
    for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i)
        DX12::SRVDescriptorHeap.Free(SRVHandles[i]);
    DX12::SRVDescriptorHeap.Free(UAVHandle);
    InternalBuffer.Shutdown();
    NumElements = 0;
}

D3D12_CPU_DESCRIPTOR_HANDLE RawBuffer::SRV() const
{
    Assert_(InternalBuffer.ReadyForBinding());
    Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid());
    return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle;
}

D3D12_CPU_DESCRIPTOR_HANDLE RawBuffer::UAV() const
{
    Assert_(UAVHandle.IsValid());
    return UAVHandle.CPUHandle;
}

void* RawBuffer::Map()
{
    MapResult mapResult = InternalBuffer.Map();
    if(InternalBuffer.Lifetime == BufferLifetime::Temporary)
    {
        Assert_(SRVHandles[0].IsValid());
        Assert_(mapResult.ResourceOffset % Stride == 0);

        D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
        srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
        srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride);
        srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
        srvDesc.Buffer.NumElements = uint32(NumElements);
        DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle);
    }

    GPUAddress = mapResult.GPUAddress;
    return mapResult.CPUAddress;
}

void RawBuffer::MapAndSetData(const void* data, uint64 numElements)
{
    Assert_(numElements <= NumElements);
    void* cpuAddr = Map();
    memcpy(cpuAddr, data, numElements * Stride);
}

void RawBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset)
{
    InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride);
}

void RawBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const
{
    InternalBuffer.Transition(cmdList, before, after);
}

void RawBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeReadable(cmdList);
}

void RawBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.MakeWritable(cmdList);
}

void RawBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const
{
    InternalBuffer.UAVBarrier(cmdList);
}

// == ReadbackBuffer ==============================================================================

ReadbackBuffer::ReadbackBuffer()
{
}

ReadbackBuffer::~ReadbackBuffer()
{
    Assert_(Resource == nullptr);
}

void ReadbackBuffer::Initialize(uint64 size)
{
    Assert_(size > 0);
    Size = size;

    D3D12_RESOURCE_DESC resourceDesc = {};
    resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
    resourceDesc.Width = uint32(size);
    resourceDesc.Height = 1;
    resourceDesc.DepthOrArraySize = 1;
    resourceDesc.MipLevels = 1;
    resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
    resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
    resourceDesc.SampleDesc.Count = 1;
    resourceDesc.SampleDesc.Quality = 0;
    resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
    resourceDesc.Alignment = 0;

    DXCall(DX12::Device->CreateCommittedResource(DX12::GetReadbackHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc,
                                                 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&Resource)));
}

void ReadbackBuffer::Shutdown()
{
    DX12::DeferredRelease(Resource);
    Size = 0;
}

void* ReadbackBuffer::Map()
{
    Assert_(Resource != nullptr);
    void* data = nullptr;
    Resource->Map(0, nullptr, &data);
    return data;
}

void ReadbackBuffer::Unmap()
{
    Assert_(Resource != nullptr);
    Resource->Unmap(0, nullptr);
}

// == Fence =======================================================================================

Fence::~Fence()
{
    Assert_(D3DFence == nullptr);
    Shutdown();
}

void Fence::Init(uint64 initialValue)
{
    DXCall(DX12::Device->CreateFence(initialValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&D3DFence)));
    FenceEvent = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS);
    Win32Call(FenceEvent != 0);
}

void Fence::Shutdown()
{
    DX12::DeferredRelease(D3DFence);
}

void Fence::Signal(ID3D12CommandQueue* queue, uint64 fenceValue)
{
    Assert_(D3DFence != nullptr);
    DXCall(queue->Signal(D3DFence, fenceValue));
}

void Fence::Wait(uint64 fenceValue)
{
    Assert_(D3DFence != nullptr);
    if(D3DFence->GetCompletedValue() < fenceValue)
    {
        DXCall(D3DFence->SetEventOnCompletion(fenceValue, FenceEvent));
        WaitForSingleObject(FenceEvent, INFINITE);
    }
}

bool Fence::Signaled(uint64 fenceValue)
{
    Assert_(D3DFence != nullptr);
    return D3DFence->GetCompletedValue() >= fenceValue;
}

void Fence::Clear(uint64 fenceValue)
{
    Assert_(D3DFence != nullptr);
    D3DFence->Signal(fenceValue);
}

// == Texture ====================================================================================

Texture::Texture()
{
}

Texture::~Texture()
{
    Assert_(Resource == nullptr);
}

void Texture::Shutdown()
{
    DX12::SRVDescriptorHeap.Free(SRV);
    DX12::DeferredRelease(Resource);
}

// == RenderTexture ===============================================================================

RenderTexture::RenderTexture()
{
}

RenderTexture::~RenderTexture()
{
    Assert_(RTV.IsValid() == false);
}

void RenderTexture::Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples, uint64 arraySize, bool32 createUAV, D3D12_RESOURCE_STATES initialState)
{
    Shutdown();

    Assert_(width > 0);
    Assert_(height > 0);
    Assert_(msaaSamples > 0);

    D3D12_RESOURCE_DESC textureDesc = { };
    textureDesc.MipLevels = 1;
    textureDesc.Format = format;
    textureDesc.Width = uint32(width);
    textureDesc.Height = uint32(height);
    textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
    if(createUAV)
        textureDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
    if(msaaSamples == 1)
        textureDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
    textureDesc.DepthOrArraySize = uint16(arraySize);
    textureDesc.SampleDesc.Count = uint32(msaaSamples);
    textureDesc.SampleDesc.Quality = msaaSamples > 1 ? DX12::StandardMSAAPattern : 0;
    textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
    textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
    textureDesc.Alignment = 0;

    D3D12_CLEAR_VALUE clearValue = { };
    clearValue.Format = format;
    DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc,
                                                 initialState, &clearValue, IID_PPV_ARGS(&Texture.Resource)));

    Texture.SRV = DX12::SRVDescriptorHeap.Allocate();
    DX12::Device->CreateShaderResourceView(Texture.Resource,  nullptr, Texture.SRV.CPUHandle);

    Texture.Width = uint32(width);
    Texture.Height = uint32(height);
    Texture.Depth = 1;
    Texture.NumMips = 1;
    Texture.ArraySize = uint32(arraySize);
    Texture.Format = format;
    Texture.Cubemap = false;
    MSAASamples = uint32(msaaSamples);
    MSAAQuality = uint32(textureDesc.SampleDesc.Quality);

    RTV = DX12::RTVDescriptorHeap.Allocate();
    DX12::Device->CreateRenderTargetView(Texture.Resource, nullptr, RTV.CPUHandle);

    if(arraySize > 1)
    {
        ArrayRTVs.Init(arraySize);

        D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = { };
        rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
        rtvDesc.Format = format;
        if(msaaSamples > 1)
            rtvDesc.Texture2DMSArray.ArraySize = 1;
        else
            rtvDesc.Texture2DArray.ArraySize = 1;

        for(uint64 i = 0; i < arraySize; ++i)
        {
            if(msaaSamples > 1)
                rtvDesc.Texture2DMSArray.FirstArraySlice = uint32(i);
            else
                rtvDesc.Texture2DArray.FirstArraySlice = uint32(i);

            ArrayRTVs[i] = DX12::RTVDescriptorHeap.Allocate();
            DX12::Device->CreateRenderTargetView(Texture.Resource, &rtvDesc, ArrayRTVs[i].CPUHandle);
        }
    }

    if(createUAV)
    {
        UAV = DX12::SRVDescriptorHeap.Allocate();
        DX12::Device->CreateUnorderedAccessView(Texture.Resource, nullptr, nullptr, UAV.CPUHandle);
    }
}

void RenderTexture::Shutdown()
{
    DX12::RTVDescriptorHeap.Free(RTV);
    DX12::SRVDescriptorHeap.Free(UAV);
    for(uint64 i = 0; i < ArrayRTVs.Size(); ++i)
        DX12::RTVDescriptorHeap.Free(ArrayRTVs[i]);
    ArrayRTVs.Shutdown();
    Texture.Shutdown();
}

void RenderTexture::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 mipLevel, uint64 arraySlice) const
{
    uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES
                                                                               : uint32(SubResourceIndex(mipLevel, arraySlice));
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx);
}

void RenderTexture::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const
{
    uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES
                                                                               : uint32(SubResourceIndex(mipLevel, arraySlice));
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx);
}

void RenderTexture::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const
{
    uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES
                                                                               : uint32(SubResourceIndex(mipLevel, arraySlice));
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET, subResourceIdx);
}

// == DepthBuffer ===============================================================================

DepthBuffer::DepthBuffer()
{
}

DepthBuffer::~DepthBuffer()
{
    Assert_(DSVFormat == DXGI_FORMAT_UNKNOWN);
    Shutdown();
}

void DepthBuffer::Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples, uint64 arraySize, D3D12_RESOURCE_STATES initialState)
{
    Shutdown();

    Assert_(width > 0);
    Assert_(height > 0);
    Assert_(msaaSamples > 0);

    DXGI_FORMAT texFormat = format;
    DXGI_FORMAT srvFormat = format;
    if(format == DXGI_FORMAT_D16_UNORM)
    {
        texFormat = DXGI_FORMAT_R16_TYPELESS;
        srvFormat = DXGI_FORMAT_R16_UNORM;
    }
    else if(format == DXGI_FORMAT_D24_UNORM_S8_UINT)
    {
        texFormat = DXGI_FORMAT_R24G8_TYPELESS;
        srvFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
    }
    else if(format == DXGI_FORMAT_D32_FLOAT)
    {
        texFormat = DXGI_FORMAT_R32_TYPELESS;
        srvFormat = DXGI_FORMAT_R32_FLOAT;
    }
    else if(format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT)
    {
        texFormat = DXGI_FORMAT_R32G8X24_TYPELESS;
        srvFormat = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
    }
    else
    {
        AssertFail_("Invalid depth buffer format!");
    }

    D3D12_RESOURCE_DESC textureDesc = { };
    textureDesc.MipLevels = 1;
    textureDesc.Format = texFormat;
    textureDesc.Width = uint32(width);
    textureDesc.Height = uint32(height);
    textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
    textureDesc.DepthOrArraySize = uint16(arraySize);
    textureDesc.SampleDesc.Count = uint32(msaaSamples);
    textureDesc.SampleDesc.Quality = msaaSamples > 1 ? DX12::StandardMSAAPattern : 0;
    textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
    textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
    textureDesc.Alignment = 0;

    D3D12_CLEAR_VALUE clearValue = { };
    clearValue.DepthStencil.Depth = 1.0f;
    clearValue.DepthStencil.Stencil = 0;
    clearValue.Format = format;

    DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc,
                                                 initialState, &clearValue, IID_PPV_ARGS(&Texture.Resource)));

    Texture.SRV = DX12::SRVDescriptorHeap.Allocate();

    D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { };
    srvDesc.Format = srvFormat;
    srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    if(msaaSamples == 1 && arraySize == 1)
    {
        srvDesc.Texture2D.MipLevels = 1;
        srvDesc.Texture2D.MostDetailedMip = 0;
        srvDesc.Texture2D.PlaneSlice = 0;
        srvDesc.Texture2D.ResourceMinLODClamp = 0.0f;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
    }
    else if(msaaSamples == 1 && arraySize > 1)
    {
        srvDesc.Texture2DArray.ArraySize = uint32(arraySize);
        srvDesc.Texture2DArray.FirstArraySlice = 0;
        srvDesc.Texture2DArray.MipLevels = 1;
        srvDesc.Texture2DArray.MostDetailedMip = 0;
        srvDesc.Texture2DArray.PlaneSlice = 0;
        srvDesc.Texture2DArray.ResourceMinLODClamp = 0.0f;
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
    }
    else if(msaaSamples > 1 && arraySize == 1)
    {
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS;
    }
    else if(msaaSamples > 1 && arraySize > 1)
    {
        srvDesc.Texture2DMSArray.FirstArraySlice = 0;
        srvDesc.Texture2DMSArray.ArraySize = uint32(arraySize);
        srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
    }
    DX12::Device->CreateShaderResourceView(Texture.Resource,  &srvDesc, Texture.SRV.CPUHandle);

    Texture.Width = uint32(width);
    Texture.Height = uint32(height);
    Texture.Depth = 1;
    Texture.NumMips = 1;
    Texture.ArraySize = uint32(arraySize);
    Texture.Format = srvFormat;
    Texture.Cubemap = false;
    MSAASamples = uint32(msaaSamples);
    MSAAQuality = uint32(textureDesc.SampleDesc.Quality);

    DSV = DX12::DSVDescriptorHeap.Allocate();

    D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = { };
    dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
    dsvDesc.Format = format;

    if(msaaSamples == 1 && arraySize == 1)
    {
        dsvDesc.Texture2D.MipSlice = 0;
        dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
    }
    else if(msaaSamples == 1 && arraySize > 1)
    {
        dsvDesc.Texture2DArray.ArraySize = uint32(arraySize);
        dsvDesc.Texture2DArray.FirstArraySlice = 0;
        dsvDesc.Texture2DArray.MipSlice = 0;
        dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
    }
    else if(msaaSamples > 1 && arraySize == 1)
    {
        dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
    }
    else if(msaaSamples > 1 && arraySize > 1)
    {
        dsvDesc.Texture2DMSArray.ArraySize = uint32(arraySize);
        dsvDesc.Texture2DMSArray.FirstArraySlice = 0;
        dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
    }

    DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, DSV.CPUHandle);

    bool hasStencil = format == DXGI_FORMAT_D24_UNORM_S8_UINT || format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT;

    ReadOnlyDSV = DX12::DSVDescriptorHeap.Allocate();
    dsvDesc.Flags = D3D12_DSV_FLAG_READ_ONLY_DEPTH;
    if(hasStencil)
        dsvDesc.Flags |= D3D12_DSV_FLAG_READ_ONLY_STENCIL;
    DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ReadOnlyDSV.CPUHandle);

    if(arraySize > 1)
    {
        ArrayDSVs.Init(arraySize);

        dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
        if(msaaSamples > 1)
            dsvDesc.Texture2DMSArray.ArraySize = 1;
        else
            dsvDesc.Texture2DArray.ArraySize = 1;

        for(uint64 i = 0; i < arraySize; ++i)
        {
            if(msaaSamples > 1)
                dsvDesc.Texture2DMSArray.FirstArraySlice = uint32(i);
            else
                dsvDesc.Texture2DArray.FirstArraySlice = uint32(i);

            ArrayDSVs[i] = DX12::DSVDescriptorHeap.Allocate();
            DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ArrayDSVs[i].CPUHandle);
        }
    }

    DSVFormat = format;
}

void DepthBuffer::Shutdown()
{
    DX12::DSVDescriptorHeap.Free(DSV);
    DX12::DSVDescriptorHeap.Free(ReadOnlyDSV);
    for(uint64 i = 0; i < ArrayDSVs.Size(); ++i)
        DX12::DSVDescriptorHeap.Free(ArrayDSVs[i]);
    ArrayDSVs.Shutdown();
    Texture.Shutdown();
    DSVFormat = DXGI_FORMAT_UNKNOWN;
}

void DepthBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 arraySlice) const
{
    uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice);
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx);
}

void DepthBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const
{
    uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice);
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_WRITE,
                             D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx);
}

void DepthBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const
{
    uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice);
    Assert_(Texture.Resource != nullptr);
    DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
                             D3D12_RESOURCE_STATE_DEPTH_WRITE, subResourceIdx);
}

}


text:
package de.haw.vs.nameservice;

import java.io.Serializable;

public class ObjectReference implements Serializable {

    private String alias;
    private String hostname;
    private int port;
    private static final long serialVersionUID = 8233528997584469393L;

    public ObjectReference(String alias, String hostname, int port) {
        this.alias = alias;
        this.hostname = hostname;
        this.port = port;
    }

    public String getAlias() {
        return alias;
    }

    public String getHostname() {
        return hostname;
    }

    public int getPort() {
        return port;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ObjectReference that = (ObjectReference) o;

        if (getPort() != that.getPort()) return false;
        if (!getAlias().equals(that.getAlias())) return false;
        return getHostname().equals(that.getHostname());
    }

    @Override
    public int hashCode() {
        int result = getAlias().hashCode();
        result = 31 * result + getHostname().hashCode();
        result = 31 * result + getPort();
        return result;
    }

    @Override
    public String toString() {
        return "ObjectReference{" +
                "alias='" + alias + '\'' +
                ", hostname='" + hostname + '\'' +
                ", port=" + port +
                '}';
    }
}


text:
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from src.webservice.base import Base

db = SQLAlchemy()
Base.query = db.session.query_property()

class Notification(Base):
    __tablename__ = 'tbl_Notification'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    notification_type = db.Column(db.Integer, db.ForeignKey('tbl_Notification_Type.id'))
    message = db.Column(db.String(50))
    subject = db.Column(db.String(50))
    enabled = db.Column(db.Boolean)

    @staticmethod
    def get_notifications(notificationId):
        notification = db.session.query(Notification).filter(Notification.id.in_(notificationId)).all()
        db.session.commit()
        return notification

    @staticmethod
    def get_menu_fields_notifications():
        rows = db.session.query(Notification).all()
        output = []
        for row in rows:
            output.append({'id': row.id, 'name': row.name})
        db.session.close()
        return jsonify({'response': output})


text:
[![Build Status](https://travis-ci.org/kata-seeds/perl-seed.svg?branch=master)](https://travis-ci.org/kata-seeds/perl-seed)

## Getting Started

Clone this repo with `git`:

    git clone https://github.com/kata-seeds/perl-seed.git
    cd perl-seed

Install dependencies and run your tests with `make`:

    make

You should eventually see 2 tests ran and 0 failures. If `make` doesn't work for you, please open an issue.

Now you can start your kata! May we suggest the [Game of Life](http://en.wikipedia.org/wiki/Conway's_Game_of_Life)?


text:
/**
 *
 */
package cn.newcapec.function.ecardcity.om.biz;

import java.io.Serializable;

import cn.newcapec.framework.core.biz.BaseService;
import cn.newcapec.function.ecardcity.om.model.TermInfo;

/**
 * @author ocean
 * email: zhangjunfang0505@163.com
 * QQ: 419692181
 * date: 2014-3-14
 */
public interface TermInfoService extends   BaseService<TermInfo> ,Serializable {

	TermInfo UpdateKEK(TermInfo info );

}


text:
Essentially, you'll need the ability to get network traffic from the ports you want to monitor to the monitoring port on the IDS system. This can be done a few different ways, either with hardware or software (if your router has the ability).

With hardware, you can use a switch to span/mirror the port going to your WAN. This way, you're capturing all traffic that comes into and leaves your network. One downside to spanning the WAN is that you miss traffic that never crosses the WAN, but we still see most traffic including malware callbacks, C&C, etc (the things you want to spot).

With hardware, you can also build a network tap that goes between your LAN and WAN. I'm not using this method, so I don't have documentation for this approach. I personally don't like this approach, as it puts our system inbetween LAN and WAN traffic, and if it fails incorrectly, the network can be taken offline. I'll collect some network tap guides for a later update for those that want to try this approach.

With software (if your router hardware supports it), you could use iptables to mirror all traffic to another device on the network. I haven't tried this method yet, but I know people have successfully used this approach in the past. Currently, I don't have any documentation for this approach, but I'll collect some guides for a later update.

TL;DR - Get the traffic you want to see on the IDS to a network port on the IDS system. I'm currently using a Ubiquiti 8 port PoE switch, mirroring the WAN port to the second NIC of my IDS box. If your router supports iptables, you can also mirror the traffic using iptables rules. You can also use a hardware network tap.

# PC Hardware Configuration
You'll want a system that matches your network throughput. A key requirement is multiple NICs - one as the management interface, and one for traffic monitoring from your mirror port.

For a rough baseline, on a 200Mbs down/20Mbs up Internet connection, I'm using a Shuttle Mini PC with a Core i5 and 8GB of RAM, along with a 128GB SSD. Even while running a full Elastic stack along with Suricata, it's not struggling to keep up. The only real limitation you'll have to pay attention to is how long you'll want to retain PCAP files, as that's all about storage.

# OS Configuration

## OS Installation
I'm using Ubuntu 16.04 LTS Server for compatability with most tools available. Other flavors of Linux can be used, but I'll be writing this guide with Ubuntu 16.04 in mind.

## NIC Configuration
### Management Interface
Configure your management interface as you would any other server. Either leverage DHCP or static addresses, whichever your network calls for.

### Monitoring Port
Now we'll configure the other port to monitor traffic from.

#### What device?
Find the name of the device that you'll be monitoring from. In this example, we're concerned with enp8s0 (YAY SYSTEMD NAMING).

`root@grIDS:~# ip a`

```
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
  <SNIP>
2: enp4s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
  <SNIP>
3: enp7s0: <NO-CARRIER,BROADCAST,PROMISC,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
    link/ether 00:0a:cd:21:47:23 brd ff:ff:ff:ff:ff:ff
4: enp8s0: <BROADCAST,PROMISC,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0a:cd:21:47:24 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::20a:cdff:fe21:4724/64 scope link
       valid_lft forever preferred_lft forever
```

#### Disable multicast
```
ip link set enp8s0 multicast off
```

#### Enable promiscuous mode
```
root@grIDS:~# ip link set enp8s0 promisc on
```

#### Turn on the link
```
root@grIDS:~# ip link set enp8s0 up
```

#### Validate traffic
Validating traffic is difficult if you're not aware of what might be passing through the network. The best approach I've found to ensure you're not only seeing broadcast traffic is to use tcpdump to check that you're seeing common network traffic like HTTP/DNS/etc. Try navigating to a site that uses only HTTP (`ragu.com` is an option).

```
root@grIDS:~# tcpdump -i $INTERFACE port 80
```

#### Promisc on boot
Now that the configuration has been validated, save these settings to `/etc/network/interfaces` where `$INTERFACE` is the name of the interface you configured earlier:

```
up ip link set $INTERFACE multicast off
up ip link set $INTERFACE up
up ip link set $INTERFACE promisc on
```


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: Shaped Clock Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

Shaped Clock Example

Files:

widgets/shapedclock/shapedclock.cpp

widgets/shapedclock/shapedclock.h

widgets/shapedclock/main.cpp

The Shaped Clock example shows how to apply a widget mask to a top-level widget to produce a shaped window.

Widget masks are used to customize the shapes of top-level widgets by restricting the available area for painting. On some window systems, setting certain window flags will cause the window decoration (title bar, window frame, buttons) to be disabled, allowing specially-shaped windows to be created. In this example, we use this feature to create a circular window containing an analog clock.

Since this example's window does not provide a File menu or a close button, we provide a context menu with an Exit entry so that the example can be closed. Click the right mouse button over the window to open this menu.

ShapedClock Class Definition

The <tt>ShapedClock</tt> class is based on the <tt>AnalogClock</tt> class defined in the Analog Clock example. The whole class definition is presented below:

 class ShapedClock : public QWidget
 {
     Q_OBJECT

 public:
     ShapedClock(QWidget *parent = 0);
     QSize sizeHint() const;

 protected:
     void mouseMoveEvent(QMouseEvent *event);
     void mousePressEvent(QMouseEvent *event);
     void paintEvent(QPaintEvent *event);
     void resizeEvent(QResizeEvent *event);

 private:
     QPoint dragPosition;
 };

The paintEvent() implementation is the same as that found in the <tt>AnalogClock</tt> class. We implement sizeHint() so that we don't have to resize the widget explicitly. We also provide an event handler for resize events. This allows us to update the mask if the clock is resized.

Since the window containing the clock widget will have no title bar, we provide implementations for mouseMoveEvent() and mousePressEvent() to allow the clock to be dragged around the screen. The <tt>dragPosition</tt> variable lets us keep track of where the user last clicked on the widget.

ShapedClock Class Implementation

The <tt>ShapedClock</tt> constructor performs many of the same tasks as the <tt>AnalogClock</tt> constructor. We set up a timer and connect it to the widget's update() slot:

 ShapedClock::ShapedClock(QWidget *parent)
     : QWidget(parent, Qt::FramelessWindowHint)
 {
     QTimer *timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), this, SLOT(update()));
     timer->start(1000);

     QAction *quitAction = new QAction(tr("E&xit"), this);
     quitAction->setShortcut(tr("Ctrl+Q"));
     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
     addAction(quitAction);

     setContextMenuPolicy(Qt::ActionsContextMenu);
     setToolTip(tr("Drag the clock with the left mouse button.\n"
                   "Use the right mouse button to open a context menu."));
     setWindowTitle(tr("Shaped Analog Clock"));
 }

We inform the window manager that the widget is not to be decorated with a window frame by setting the Qt::FramelessWindowHint flag on the widget. As a result, we need to provide a way for the user to move the clock around the screen.

Mouse button events are delivered to the <tt>mousePressEvent()</tt> handler:

 void ShapedClock::mousePressEvent(QMouseEvent *event)
 {
     if (event->button() == Qt::LeftButton) {
         dragPosition = event->globalPos() - frameGeometry().topLeft();
         event->accept();
     }
 }

If the left mouse button is pressed over the widget, we record the displacement in global (screen) coordinates between the top-left position of the widget's frame (even when hidden) and the point where the mouse click occurred. This displacement will be used if the user moves the mouse while holding down the left button. Since we acted on the event, we accept it by calling its accept() function.

The <tt>mouseMoveEvent()</tt> handler is called if the mouse is moved over the widget.

 void ShapedClock::mouseMoveEvent(QMouseEvent *event)
 {
     if (event->buttons() & Qt::LeftButton) {
         move(event->globalPos() - dragPosition);
         event->accept();
     }
 }

If the left button is held down while the mouse is moved, the top-left corner of the widget is moved to the point given by subtracting the <tt>dragPosition</tt> from the current cursor position in global coordinates. If we drag the widget, we also accept the event.

The <tt>paintEvent()</tt> function is given for completeness. See the Analog Clock example for a description of the process used to render the clock.

 void ShapedClock::paintEvent(QPaintEvent *)
 {
     static const QPoint hourHand[3] = {
         QPoint(7, 8),
         QPoint(-7, 8),
         QPoint(0, -40)
     };
     static const QPoint minuteHand[3] = {
         QPoint(7, 8),
         QPoint(-7, 8),
         QPoint(0, -70)
     };

     QColor hourColor(127, 0, 127);
     QColor minuteColor(0, 127, 127, 191);

     int side = qMin(width(), height());
     QTime time = QTime::currentTime();

     QPainter painter(this);
     painter.setRenderHint(QPainter::Antialiasing);
     painter.translate(width() / 2, height() / 2);
     painter.scale(side / 200.0, side / 200.0);

     painter.setPen(Qt::NoPen);
     painter.setBrush(hourColor);

     painter.save();
     painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
     painter.drawConvexPolygon(hourHand, 3);
     painter.restore();

     painter.setPen(hourColor);

     for (int i = 0; i < 12; ++i) {
         painter.drawLine(88, 0, 96, 0);
         painter.rotate(30.0);
     }

     painter.setPen(Qt::NoPen);
     painter.setBrush(minuteColor);

     painter.save();
     painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
     painter.drawConvexPolygon(minuteHand, 3);
     painter.restore();

     painter.setPen(minuteColor);

     for (int j = 0; j < 60; ++j) {
         if ((j % 5) != 0)
             painter.drawLine(92, 0, 96, 0);
         painter.rotate(6.0);
     }
 }

In the <tt>resizeEvent()</tt> handler, we re-use some of the code from the <tt>paintEvent()</tt> to determine the region of the widget that is visible to the user:

 void ShapedClock::resizeEvent(QResizeEvent * /* event */)
 {
     int side = qMin(width(), height());
     QRegion maskedRegion(width() / 2 - side / 2, height() / 2 - side / 2, side,
                          side, QRegion::Ellipse);
     setMask(maskedRegion);
 }

Since the clock face is a circle drawn in the center of the widget, this is the region we use as the mask.

Although the lack of a window frame may make it difficult for the user to resize the widget on some platforms, it will not necessarily be impossible. The <tt>resizeEvent()</tt> function ensures that the widget mask will always be updated if the widget's dimensions change, and additionally ensures that it will be set up correctly when the widget is first displayed.

Finally, we implement the <tt>sizeHint()</tt> for the widget so that it is given a reasonable default size when it is first shown:

 QSize ShapedClock::sizeHint() const
 {
     return QSize(100, 100);
 }

Notes on Widget Masks

Since QRegion allows arbitrarily complex regions to be created, widget masks can be made to suit the most unconventionally-shaped windows, and even allow widgets to be displayed with holes in them.

Widget masks can also be constructed by using the contents of pixmap to define the opaque part of the widget. For a pixmap with an alpha channel, a suitable mask can be obtained with QPixmap::mask().

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
@charset "utf-8";
/* CSS Document */
.iconimg{ display:inline-block; *display:inline; *zoom:1; vertical-align:middle;}
.icon_lock{ background-image:url(icon/icon_lock-12.png); width:12px; height:12px; background-repeat:no-repeat; margin-right:3px;}
.icon_user{ background-image:url(icon/icon_user-12.png); width:12px; height:12px; background-repeat:no-repeat; margin-right:3px;}
.icon_exit{ background-image:url(icon/icon_exit-12.png); width:12px; height:12px; background-repeat:no-repeat; margin-right:3px;}
.icon_wz{ background-image:url(icon/icon_wz-12.png); width:16px; height:16px; background-repeat:no-repeat; margin-right:3px;}