text:
#include "common.h"

#if defined(__ARMCC_VERSION)

#include <cytypes.h>

__attribute__ ((section(".bootloaderruntype"), zero_init))
extern volatile uint8 appType;
__attribute__ ((section(".bootloaderruntype"), zero_init))
volatile uint32 CyReturnToBootloaddableAddress;
extern void Bootloader__main(void);
void InitializeBootloaderSRAM(void);
extern int main(void);
extern int $Super$$main(void);
extern void initialize_psoc(void);
#endif /*__ARMCC_VERSION*/

#if defined(__ARMCC_VERSION)
    /*******************************************************************************
    * Following code implements re-initialization of separate RAM segment containing
    * data that is required for BLE Stack operation.
    * This code is used in case of MDK compiler.
    *******************************************************************************/
    __attribute__ ((section(".bootloaderruntype"), zero_init))
    volatile uint32 CyReturnToBootloaddableAddress;
    extern void Bootloader__main(void);
    void InitializeBootloaderSRAM(void);
    extern int main(void);
    extern int $Super$$main(void);
    extern void initialize_psoc(void);

    /*******************************************************************************
    * Function Name: _platform_post_lib_init()
    ********************************************************************************
    *
    * Summary:
    *   This function is called by MDK compiler startup code.
    *
    * Parameters:
    *   None
    *
    *******************************************************************************/
    void _platform_post_lib_init()
    {
        initialize_psoc();
        InitializeBootloaderSRAM();
    }
#elif defined (__GNUC__)
    /*******************************************************************************
    * Following code implements re-initialization of separate RAM segment containing
    * data that is required for BLE Stack operation.
    * This code is used in case of GCC compiler
    *******************************************************************************/
    extern void Bootloader__libc_init_array(void);
    typedef unsigned char __cy_byte_align8 __attribute ((aligned (8)));
    struct __cy_region
    {
        __cy_byte_align8 *init; /* Initial contents of this region.  */
        __cy_byte_align8 *data; /* Start address of region.  */
        size_t init_size;       /* Size of initial data.  */
        size_t zero_size;       /* Additional size to be zeroed.  */
    };
    extern const struct __cy_region Bootloader__cy_regions[];
    extern const char Bootloader__cy_region_num __attribute__((weak));

    #define Bootloader__cy_region_num ((size_t)&Bootloader__cy_region_num)

    /*******************************************************************************
    * Function Name: Bootloader_Start_c()
    ********************************************************************************
    *
    * Summary:
    *   This function initializes bootloader RAM .bss section. It is required for
    *   BLE Stack operation.
    *
    * Parameters:
    *   None
    *
    *******************************************************************************/
    void Bootloader_Start_c(void)
    {
        unsigned regions = Bootloader__cy_region_num;
        const struct __cy_region *rptr = Bootloader__cy_regions;

        /* Initialize memory */
        for (regions = Bootloader__cy_region_num; regions != 0u; regions--)
        {
            uint32 *src = (uint32 *)rptr->init;
            uint32 *dst = (uint32 *)rptr->data;
            unsigned limit = rptr->init_size;
            unsigned count;

            for (count = 0u; count != limit; count += sizeof (uint32))
            {
                *dst = *src;
                dst++;
                src++;
            }
            limit = rptr->zero_size;
            for (count = 0u; count != limit; count += sizeof (uint32))
            {
                *dst = 0u;
                dst++;
            }

            rptr++;
        }

        /* Invoke static objects constructors using Bootloader__libc_init_array() function call here
         * if they are needed.
         */
}
#elif defined (__ICCARM__)
    /*******************************************************************************
    * Following code implements re-initialization of separate RAM segment containing
    * data that is required for BLE Stack operation.
    * This code is used in case of IAR compiler.
    *******************************************************************************/
    extern void Bootloader__iar_data_init3(void);
#endif  /* (__ARMCC_VERSION) */

/*******************************************************************************
* Function Name: Bootloader_Start_c()
********************************************************************************
*
* Summary:
*   This function triggers initialization of bootloader RAM .bss section.
*   It is required for BLE Stack operation. This function should be called from
*   main() prior BLE component start.
*
* Parameters:
*   None
*
*******************************************************************************/
void InitializeBootloaderSRAM()
{
#if defined(__ARMCC_VERSION)
    CyReturnToBootloaddableAddress = (uint32)$Super$$main;
    Bootloader__main();
#elif defined (__GNUC__)
    Bootloader_Start_c();
#elif defined (__ICCARM__)
    Bootloader__iar_data_init3();
#endif /* defined(__ARMCC_VERSION) */
}

/*******************************************************************************
* Function Name: ConfigureSharedPins()
********************************************************************************
*
* Summary:
*   This function configures shared pins.
*
* Parameters:
*   None
*
*******************************************************************************/
void ConfigureSharedPins()
{
                H_UART_UartPutString("ConfigureSharedPins");
    Bootloader_Service_Activation_SetDriveMode(LED_1_DM_RES_UP);
    Bootloader_Service_Activation_Write(1);
}

/*******************************************************************************
* Function Name: BootloaderSwitch()
********************************************************************************
*
* Summary:
*   This function polls SW2 button and if it is pressed - shedules bootloader
*   project launch. That action includes sotware reset.
*
* Parameters:
*   None
*
*******************************************************************************/
void BootloaderSwitch()
{
    if (Bootloader_Service_Activation_Read() == 0)
    {
        CyDelay(100);
        if (Bootloader_Service_Activation_Read() == 0)
        {
            CyDelay(500);

            CyBle_Shutdown(); /* stop all ongoing activities */
            CyBle_ProcessEvents(); /* process all pending events */
            CyBle_SetState(CYBLE_STATE_STOPPED);
            CySysWdtUnlock();
            CySysWdtDisable(WDT_COUNTER_MASK);
            CyGlobalIntDisable;
            Bootloadable_Load();
        }
    }

}

/*******************************************************************************
* Function Name: ConfigureServices()
********************************************************************************
*
* Summary:
*   This function configures BLE component services to match required
*   configuration.
*
* Parameters:
*   None
*
*******************************************************************************/
void ConfigureServices()
{
    CyBle_GattsDisableAttribute(CYBLE_BTS_SERVICE_HANDLE);

#if defined(__ICCARM__)
    CyBle_GattsEnableAttribute(CYBLE_HID_SERVICE_HANDLE);
    CyBle_GattsEnableAttribute(CYBLE_DIS_SERVICE_HANDLE);
    CyBle_GattsEnableAttribute(CYBLE_BAS_SERVICE_HANDLE);
    CyBle_GattsEnableAttribute(CYBLE_SCPS_SERVICE_HANDLE);
#endif /* defined(__ICCARM__) */
}

/* [] END OF FILE */


text:
// Authentication Constants:
const OAUTH_SCOPE = "https://www.googleapis.com/auth/sdm.service";
const SERVER_URI = "https://[GCP-Project-Id].web.app";
const REDIRECT_URI = SERVER_URI + "/auth";

// Partner Credentials:
var clientId = "";
var clientSecret = "";
var projectId = "";

// Authentication Variables:
var oauthCode = "[OAuth Code...]";
var accessToken = "[Access Token...]";
var refreshToken = "[Refresh Token...]";

// State Variables:
var isSignedIn = false;
var deviceId = "";

/// Primary Functions ///

/** init - Initializes the loaded javascript */
function init() {
  readStorage();          // Reads data from browser's local storage if available
  handleAuth();           // Checks incoming authorization code from /auth path
  exchangeCode();         // Exchanges authorization code to an access token
}

/** readStorage - Reads data from browser's local storage if available */
function readStorage() {
  if (localStorage["clientId"]) {
    updateClientId(localStorage["clientId"]);
  }
  if (localStorage["clientSecret"]) {
    updateClientSecret(localStorage["clientSecret"]);
  }
  if (localStorage["projectId"]) {
    updateProjectId(localStorage["projectId"]);
  }

  if (localStorage["oauthCode"]) {
    updateOAuthCode(localStorage["oauthCode"]);
  }
  if (localStorage["accessToken"]) {
    updateAccessToken(localStorage["accessToken"]);
  }
  if (localStorage["refreshToken"]) {
    updateRefreshToken(localStorage["refreshToken"]);
  }

  if (localStorage["isSignedIn"] === true || localStorage["isSignedIn"] === "true") {
    updateSignedIn(localStorage["isSignedIn"]);
  }
}

/** handleAuth - Detects and sends oauth response code to server */
function handleAuth () {

  // Check if the url is beginning with /auth.
  if (window.location.pathname.startsWith("/auth")) {
    console.log("/auth detected!");

    // Retreive query parameters from url.
    var queryparams = window.location.search.split("&");

    // Extract key-value pairs from parameters.
    for (var i = 0; i < queryparams.length; i++) {
      var key = queryparams[i].split("=")[0];
      var val = queryparams[i].split("=")[1];

      // Send oAuth Code to server if found.
      if (key === "code") {
        updateOAuthCode(val);
      }
    }

    // Prevent back button action by injecting a previous state.
    window.history.pushState("object or string", "Title", "/");
  }
}

/** exchangeCode - Exchanges OAuth Code to OAuth Tokens */
function exchangeCode() {
  if (oauthCode !== "[OAuth Code...]" && accessToken === "[Access Token...]" ) {
    var payload = {
      code: oauthCode,
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uri: REDIRECT_URI,
      grant_type: 'authorization_code'
    };

    var xhr = new XMLHttpRequest();
    xhr.open('POST', "https://www.googleapis.com/oauth2/v4/token");
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.onload = function () {
      var parsedResponse = JSON.parse(xhr.responseText);
      updateAccessToken(parsedResponse.access_token);
      updateRefreshToken(parsedResponse.refresh_token);
      updateSignedIn(true);
    };
    xhr.send(JSON.stringify(payload));
  }
}

/** oAuthSignIn - Handles the Sign-in button functionality */
function oauthSignIn() {

  // Google's OAuth 2.0 endpoint for requesting an access token:
  var oauthEndpoint = "https://nestservices.google.com/partnerconnections/" +
      projectId + "/auth";

  // Create <form> element to submit parameters to OAuth 2.0 endpoint.
  var form = document.createElement('form');
  form.setAttribute('method', 'GET');
  form.setAttribute('action', oauthEndpoint);

  // Parameters to pass to OAuth 2.0 endpoint.
  var params = {
    'access_type': 'offline',
    'client_id': clientId,
    'include_granted_scopes': 'true',
    'prompt' : 'consent',
    'redirect_uri': REDIRECT_URI,
    'response_type': 'code',
    'scope': OAUTH_SCOPE,
    'state': 'pass-through value'
  };

  // Add form parameters as hidden input values.
  for (var p in params) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', p);
    input.setAttribute('value', params[p]);
    form.appendChild(input);
  }

  // Add form to page and submit it to open the OAuth 2.0 endpoint.
  document.body.appendChild(form);
  form.submit();
}

/** oAuthSignIn - Handles the Sign-out button functionality */
function oauthSignOut() {
  // updateClientId("");
  // updateClientSecret("");
  // updateProjectId("");

  updateOAuthCode("[OAuth Code...]");
  updateAccessToken("[Access Token...]");
  updateRefreshToken("[Refresh Token...]");

  clearDevices();

  updateSignedIn(false);
}

/// Device Access Functions ///

function deviceAccessRequest(method, call, localpath, payload = null) {
    var xhr = new XMLHttpRequest();

    // We are doing our post request to device access endpoint:
    xhr.open(method, "https://smartdevicemanagement.googleapis.com/v1" + localpath);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.onload = function () {
      // Response is passed to deviceAccessResponse function:
      deviceAccessResponse(call, xhr.response)
    };

    if ('POST' === method && payload)
        xhr.send(JSON.stringify(payload));
    else
        xhr.send();
}

function deviceAccessResponse(call, response) {
  console.log(response);
  switch(call) {
    case 'listDevices':
      var data = JSON.parse(response);
      var devices = data.devices;

      clearDevices();

      for (let i = 0; i < devices.length; i++) {
        var str = data.devices[i].name;
        var n = str.lastIndexOf('/');
        var devName = str.substring(n + 1);
        addDevice(devName);
      }
      break;
    case 'thermostatMode':
      console.log("Thermostat Mode Set!");
      break;
    case 'temperatureSetpoint':
      console.log("Temperature Setpoint Set!");
      break;
    default:
      console.log("Unknown call!");
  }
}

/// Helper Functions ///

function addDevice(deviceName){
  // Create an Option object
  var opt = document.createElement("option");

  // Assign text and value to Option object
  opt.text = deviceName;
  opt.value = deviceName;

  // Add an Option object to Drop Down List Box
  id("sctDeviceSelect").options.add(opt);

  // If this is the first device added, choose it
  if(id("sctDeviceSelect").options.length == 1){
    deviceId = deviceName;
  }
}

function clearDevices(){
  var length = id("sctDeviceSelect").options.length;
  for (let i = length - 1; i >= 0; i--) {
    id("sctDeviceSelect").options[i] = null;
  }
}

/// UI Controller Functions ///

function signInOut() {
  if (isSignedIn) {
    oauthSignOut();
  } else {
    var gSignInMeta = document.createElement("meta");
    gSignInMeta.name = "google-signin-client_id";
    gSignInMeta.content = clientId;
    document.head.appendChild(gSignInMeta);

    oauthSignIn();
  }
}

function selectDevice() {
  console.log("Selected Device...");
  deviceId = id("sctDeviceSelect").value;
}

/// Device Access Functions ///

function listDevices() {

}

function postThermostatMode() {

}

function postTemperatureSetpoint() {

}

/// UI Update Functions ///

/** id - Short form to get UI elements by handle */
function id(id) {
    return document.getElementById(id);
}

function typeClientId() {
  updateClientId(id("clientId").value);
}

function typeClientSecret() {
  updateClientSecret(id("clientSecret").value);
}

function typeProjectId() {
  updateProjectId(id("projectId").value);
}

function updateClientId(value) {
  clientId = value;
  localStorage["clientId"] = clientId;
  id("clientId").value = clientId;
}

function updateClientSecret(value) {
  clientSecret = value;
  localStorage["clientSecret"] = clientSecret;
  id("clientSecret").value = clientSecret;
}

function updateProjectId(value) {
  projectId = value;
  localStorage["projectId"] = projectId;
  id("projectId").value = projectId;
}

function updateOAuthCode(value) {
  oauthCode = value;
  localStorage["oauthCode"] = oauthCode;
  id("oauthCode").innerText = oauthCode;
}

function updateAccessToken(value) {
  accessToken = value;
  localStorage["accessToken"] = accessToken;
  id("accessToken").innerText = accessToken;
}

function updateRefreshToken(value) {
  refreshToken = value;
  localStorage["refreshToken"] = refreshToken;
  id("refreshToken").innerText = refreshToken;
}

function updateSignedIn(value) {
  isSignedIn = value;
  localStorage["isSignedIn"] = isSignedIn;

  if (isSignedIn) {
    id("btnSignIn").innerText = "Sign Out";
  }
  else {
    id("btnSignIn").innerText = "Sign In";
  }
}

redpajama_set_name: RedPajamaGithub


text:
/// <reference path='fourslash.ts'/>

// @Filename: f1.ts
////declare module "q" {
////    export = Q;
////}
////declare function Q<T>(value: T): void;
////declare module Q {
////
////    interface Deferred<T> {
////        //		promise: Promise<T>;
////        resolve(value: T): void;
////        reject(reason: any): void;
////        notify(value: any): void;
////        makeNodeResolver(): (reason: any, value: T) => void;
////    }
////
////export function defer<T>(): Deferred<T>;
////}

// @Filename: f2.ts
///////<reference path='f1.ts'/>
////import q = require('q');
////Q.defer/**/();

goTo.marker();
verify.completionListContains('defer');
verify.numberOfErrorsInCurrentFile(0);


text:
/******************************************************************************
 *
 * Name: actbl3.h - ACPI Table Definitions
 *
 *****************************************************************************/

/******************************************************************************
 *
 * 1. Copyright Notice
 *
 * Some or all of this work - Copyright (c) 1999 - 2014, Intel Corp.
 * All rights reserved.
 *
 * 2. License
 *
 * 2.1. This is your license from Intel Corp. under its intellectual property
 * rights. You may have additional license terms from the party that provided
 * you this software, covering your right to use that party's intellectual
 * property rights.
 *
 * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
 * copy of the source code appearing in this file ("Covered Code") an
 * irrevocable, perpetual, worldwide license under Intel's copyrights in the
 * base code distributed originally by Intel ("Original Intel Code") to copy,
 * make derivatives, distribute, use and display any portion of the Covered
 * Code in any form, with the right to sublicense such rights; and
 *
 * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
 * license (with the right to sublicense), under only those claims of Intel
 * patents that are infringed by the Original Intel Code, to make, use, sell,
 * offer to sell, and import the Covered Code and derivative works thereof
 * solely to the minimum extent necessary to exercise the above copyright
 * license, and in no event shall the patent license extend to any additions
 * to or modifications of the Original Intel Code. No other license or right
 * is granted directly or by implication, estoppel or otherwise;
 *
 * The above copyright and patent license is granted only if the following
 * conditions are met:
 *
 * 3. Conditions
 *
 * 3.1. Redistribution of Source with Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification with rights to further distribute source must include
 * the above Copyright Notice, the above License, this list of Conditions,
 * and the following Disclaimer and Export Compliance provision. In addition,
 * Licensee must cause all Covered Code to which Licensee contributes to
 * contain a file documenting the changes Licensee made to create that Covered
 * Code and the date of any change. Licensee must include in that file the
 * documentation of any changes made by any predecessor Licensee. Licensee
 * must include a prominent statement that the modification is derived,
 * directly or indirectly, from Original Intel Code.
 *
 * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification without rights to further distribute source must
 * include the following Disclaimer and Export Compliance provision in the
 * documentation and/or other materials provided with distribution. In
 * addition, Licensee may not authorize further sublicense of source of any
 * portion of the Covered Code, and must include terms to the effect that the
 * license from Licensee to its licensee is limited to the intellectual
 * property embodied in the software Licensee provides to its licensee, and
 * not to intellectual property embodied in modifications its licensee may
 * make.
 *
 * 3.3. Redistribution of Executable. Redistribution in executable form of any
 * substantial portion of the Covered Code or modification must reproduce the
 * above Copyright Notice, and the following Disclaimer and Export Compliance
 * provision in the documentation and/or other materials provided with the
 * distribution.
 *
 * 3.4. Intel retains all right, title, and interest in and to the Original
 * Intel Code.
 *
 * 3.5. Neither the name Intel nor any other trademark owned or controlled by
 * Intel shall be used in advertising or otherwise to promote the sale, use or
 * other dealings in products derived from or relating to the Covered Code
 * without prior written authorization from Intel.
 *
 * 4. Disclaimer and Export Compliance
 *
 * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
 * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
 * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
 * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
 * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
 * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE.
 *
 * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
 * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
 * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
 * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
 * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
 * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
 * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
 * LIMITED REMEDY.
 *
 * 4.3. Licensee shall not export, either directly or indirectly, any of this
 * software or system incorporating such software without first obtaining any
 * required license or other approval from the U. S. Department of Commerce or
 * any other agency or department of the United States Government. In the
 * event Licensee exports any such software from the United States or
 * re-exports any such software from a foreign destination, Licensee shall
 * ensure that the distribution and export/re-export of the software is in
 * compliance with all laws, regulations, orders, or other restrictions of the
 * U.S. Export Administration Regulations. Licensee agrees that neither it nor
 * any of its subsidiaries will export/re-export any technical data, process,
 * software, or service, directly or indirectly, to any country for which the
 * United States government or any agency thereof requires an export license,
 * other governmental approval, or letter of assurance, without first obtaining
 * such license, approval or letter.
 *
 *****************************************************************************/

#ifndef __ACTBL3_H__
#define __ACTBL3_H__

/*******************************************************************************
 *
 * Additional ACPI Tables (3)
 *
 * These tables are not consumed directly by the ACPICA subsystem, but are
 * included here to support device drivers and the AML disassembler.
 *
 * The tables in this file are fully defined within the ACPI specification.
 *
 ******************************************************************************/

/*
 * Values for description table header signatures for tables defined in this
 * file. Useful because they make it more difficult to inadvertently type in
 * the wrong signature.
 */
#define ACPI_SIG_BGRT           "BGRT"      /* Boot Graphics Resource Table */
#define ACPI_SIG_DRTM           "DRTM"      /* Dynamic Root of Trust for Measurement table */
#define ACPI_SIG_FPDT           "FPDT"      /* Firmware Performance Data Table */
#define ACPI_SIG_GTDT           "GTDT"      /* Generic Timer Description Table */
#define ACPI_SIG_MPST           "MPST"      /* Memory Power State Table */
#define ACPI_SIG_PCCT           "PCCT"      /* Platform Communications Channel Table */
#define ACPI_SIG_PMTT           "PMTT"      /* Platform Memory Topology Table */
#define ACPI_SIG_RASF           "RASF"      /* RAS Feature table */
#define ACPI_SIG_TPM2           "TPM2"      /* Trusted Platform Module 2.0 H/W interface table */

#define ACPI_SIG_S3PT           "S3PT"      /* S3 Performance (sub)Table */
#define ACPI_SIG_PCCS           "PCC"       /* PCC Shared Memory Region */

/* Reserved table signatures */

#define ACPI_SIG_MATR           "MATR"      /* Memory Address Translation Table */
#define ACPI_SIG_MSDM           "MSDM"      /* Microsoft Data Management Table */
#define ACPI_SIG_WPBT           "WPBT"      /* Windows Platform Binary Table */

/*
 * All tables must be byte-packed to match the ACPI specification, since
 * the tables are provided by the system BIOS.
 */
#pragma pack(1)

/*
 * Note: C bitfields are not used for this reason:
 *
 * "Bitfields are great and easy to read, but unfortunately the C language
 * does not specify the layout of bitfields in memory, which means they are
 * essentially useless for dealing with packed data in on-disk formats or
 * binary wire protocols." (Or ACPI tables and buffers.) "If you ask me,
 * this decision was a design error in C. Ritchie could have picked an order
 * and stuck with it." Norman Ramsey.
 * See http://stackoverflow.com/a/1053662/41661
 */

/*******************************************************************************
 *
 * BGRT - Boot Graphics Resource Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_bgrt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT16                  Version;
    UINT8                   Status;
    UINT8                   ImageType;
    UINT64                  ImageAddress;
    UINT32                  ImageOffsetX;
    UINT32                  ImageOffsetY;

} ACPI_TABLE_BGRT;

/*******************************************************************************
 *
 * DRTM - Dynamic Root of Trust for Measurement table
 *
 ******************************************************************************/

typedef struct acpi_table_drtm
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT64                  EntryBaseAddress;
    UINT64                  EntryLength;
    UINT32                  EntryAddress32;
    UINT64                  EntryAddress64;
    UINT64                  ExitAddress;
    UINT64                  LogAreaAddress;
    UINT32                  LogAreaLength;
    UINT64                  ArchDependentAddress;
    UINT32                  Flags;

} ACPI_TABLE_DRTM;

/* 1) Validated Tables List */

typedef struct acpi_drtm_vtl_list
{
    UINT32                  ValidatedTableListCount;

} ACPI_DRTM_VTL_LIST;

/* 2) Resources List */

typedef struct acpi_drtm_resource_list
{
    UINT32                  ResourceListCount;

} ACPI_DRTM_RESOURCE_LIST;

/* 3) Platform-specific Identifiers List */

typedef struct acpi_drtm_id_list
{
    UINT32                  IdListCount;

} ACPI_DRTM_ID_LIST;

/*******************************************************************************
 *
 * FPDT - Firmware Performance Data Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_fpdt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */

} ACPI_TABLE_FPDT;

/* FPDT subtable header */

typedef struct acpi_fpdt_header
{
    UINT16                  Type;
    UINT8                   Length;
    UINT8                   Revision;

} ACPI_FPDT_HEADER;

/* Values for Type field above */

enum AcpiFpdtType
{
    ACPI_FPDT_TYPE_BOOT                 = 0,
    ACPI_FPDT_TYPE_S3PERF               = 1
};

/*
 * FPDT subtables
 */

/* 0: Firmware Basic Boot Performance Record */

typedef struct acpi_fpdt_boot
{
    ACPI_FPDT_HEADER        Header;
    UINT8                   Reserved[4];
    UINT64                  ResetEnd;
    UINT64                  LoadStart;
    UINT64                  StartupStart;
    UINT64                  ExitServicesEntry;
    UINT64                  ExitServicesExit;

} ACPI_FPDT_BOOT;

/* 1: S3 Performance Table Pointer Record */

typedef struct acpi_fpdt_s3pt_ptr
{
    ACPI_FPDT_HEADER        Header;
    UINT8                   Reserved[4];
    UINT64                  Address;

} ACPI_FPDT_S3PT_PTR;

/*
 * S3PT - S3 Performance Table. This table is pointed to by the
 * FPDT S3 Pointer Record above.
 */
typedef struct acpi_table_s3pt
{
    UINT8                   Signature[4]; /* "S3PT" */
    UINT32                  Length;

} ACPI_TABLE_S3PT;

/*
 * S3PT Subtables
 */
typedef struct acpi_s3pt_header
{
    UINT16                  Type;
    UINT8                   Length;
    UINT8                   Revision;

} ACPI_S3PT_HEADER;

/* Values for Type field above */

enum AcpiS3ptType
{
    ACPI_S3PT_TYPE_RESUME               = 0,
    ACPI_S3PT_TYPE_SUSPEND              = 1
};

typedef struct acpi_s3pt_resume
{
    ACPI_S3PT_HEADER        Header;
    UINT32                  ResumeCount;
    UINT64                  FullResume;
    UINT64                  AverageResume;

} ACPI_S3PT_RESUME;

typedef struct acpi_s3pt_suspend
{
    ACPI_S3PT_HEADER        Header;
    UINT64                  SuspendStart;
    UINT64                  SuspendEnd;

} ACPI_S3PT_SUSPEND;

/*******************************************************************************
 *
 * GTDT - Generic Timer Description Table (ACPI 5.1)
 *        Version 2
 *
 ******************************************************************************/

typedef struct acpi_table_gtdt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT64                  CounterBlockAddresss;
    UINT32                  Reserved;
    UINT32                  SecureEl1Interrupt;
    UINT32                  SecureEl1Flags;
    UINT32                  NonSecureEl1Interrupt;
    UINT32                  NonSecureEl1Flags;
    UINT32                  VirtualTimerInterrupt;
    UINT32                  VirtualTimerFlags;
    UINT32                  NonSecureEl2Interrupt;
    UINT32                  NonSecureEl2Flags;
    UINT64                  CounterReadBlockAddress;
    UINT32                  PlatformTimerCount;
    UINT32                  PlatformTimerOffset;

} ACPI_TABLE_GTDT;

/* Flag Definitions: Timer Block Physical Timers and Virtual timers */

#define ACPI_GTDT_INTERRUPT_MODE        (1)
#define ACPI_GTDT_INTERRUPT_POLARITY    (1<<1)
#define ACPI_GTDT_ALWAYS_ON             (1<<2)

/* Common GTDT subtable header */

typedef struct acpi_gtdt_header
{
    UINT8                   Type;
    UINT16                  Length;

} ACPI_GTDT_HEADER;

/* Values for GTDT subtable type above */

enum AcpiGtdtType
{
    ACPI_GTDT_TYPE_TIMER_BLOCK      = 0,
    ACPI_GTDT_TYPE_WATCHDOG         = 1,
    ACPI_GTDT_TYPE_RESERVED         = 2    /* 2 and greater are reserved */
};

/* GTDT Subtables, correspond to Type in acpi_gtdt_header */

/* 0: Generic Timer Block */

typedef struct acpi_gtdt_timer_block
{
    ACPI_GTDT_HEADER        Header;
    UINT8                   Reserved;
    UINT64                  BlockAddress;
    UINT32                  TimerCount;
    UINT32                  TimerOffset;

} ACPI_GTDT_TIMER_BLOCK;

/* Timer Sub-Structure, one per timer */

typedef struct acpi_gtdt_timer_entry
{
    UINT8                   FrameNumber;
    UINT8                   Reserved[3];
    UINT64                  BaseAddress;
    UINT64                  El0BaseAddress;
    UINT32                  TimerInterrupt;
    UINT32                  TimerFlags;
    UINT32                  VirtualTimerInterrupt;
    UINT32                  VirtualTimerFlags;
    UINT32                  CommonFlags;

} ACPI_GTDT_TIMER_ENTRY;

/* Flag Definitions: TimerFlags and VirtualTimerFlags above */

#define ACPI_GTDT_GT_IRQ_MODE               (1)
#define ACPI_GTDT_GT_IRQ_POLARITY           (1<<1)

/* Flag Definitions: CommonFlags above */

#define ACPI_GTDT_GT_IS_SECURE_TIMER        (1)
#define ACPI_GTDT_GT_ALWAYS_ON              (1<<1)

/* 1: SBSA Generic Watchdog Structure */

typedef struct acpi_gtdt_watchdog
{
    ACPI_GTDT_HEADER        Header;
    UINT8                   Reserved;
    UINT64                  RefreshFrameAddress;
    UINT64                  ControlFrameAddress;
    UINT32                  TimerInterrupt;
    UINT32                  TimerFlags;

} ACPI_GTDT_WATCHDOG;

/* Flag Definitions: TimerFlags above */

#define ACPI_GTDT_WATCHDOG_IRQ_MODE         (1)
#define ACPI_GTDT_WATCHDOG_IRQ_POLARITY     (1<<1)
#define ACPI_GTDT_WATCHDOG_SECURE           (1<<2)

/*******************************************************************************
 *
 * MPST - Memory Power State Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

#define ACPI_MPST_CHANNEL_INFO \
    UINT8                   ChannelId; \
    UINT8                   Reserved1[3]; \
    UINT16                  PowerNodeCount; \
    UINT16                  Reserved2;

/* Main table */

typedef struct acpi_table_mpst
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    ACPI_MPST_CHANNEL_INFO                      /* Platform Communication Channel */

} ACPI_TABLE_MPST;

/* Memory Platform Communication Channel Info */

typedef struct acpi_mpst_channel
{
    ACPI_MPST_CHANNEL_INFO                      /* Platform Communication Channel */

} ACPI_MPST_CHANNEL;

/* Memory Power Node Structure */

typedef struct acpi_mpst_power_node
{
    UINT8                   Flags;
    UINT8                   Reserved1;
    UINT16                  NodeId;
    UINT32                  Length;
    UINT64                  RangeAddress;
    UINT64                  RangeLength;
    UINT32                  NumPowerStates;
    UINT32                  NumPhysicalComponents;

} ACPI_MPST_POWER_NODE;

/* Values for Flags field above */

#define ACPI_MPST_ENABLED               1
#define ACPI_MPST_POWER_MANAGED         2
#define ACPI_MPST_HOT_PLUG_CAPABLE      4

/* Memory Power State Structure (follows POWER_NODE above) */

typedef struct acpi_mpst_power_state
{
    UINT8                   PowerState;
    UINT8                   InfoIndex;

} ACPI_MPST_POWER_STATE;

/* Physical Component ID Structure (follows POWER_STATE above) */

typedef struct acpi_mpst_component
{
    UINT16                  ComponentId;

} ACPI_MPST_COMPONENT;

/* Memory Power State Characteristics Structure (follows all POWER_NODEs) */

typedef struct acpi_mpst_data_hdr
{
    UINT16                  CharacteristicsCount;
    UINT16                  Reserved;

} ACPI_MPST_DATA_HDR;

typedef struct acpi_mpst_power_data
{
    UINT8                   StructureId;
    UINT8                   Flags;
    UINT16                  Reserved1;
    UINT32                  AveragePower;
    UINT32                  PowerSaving;
    UINT64                  ExitLatency;
    UINT64                  Reserved2;

} ACPI_MPST_POWER_DATA;

/* Values for Flags field above */

#define ACPI_MPST_PRESERVE              1
#define ACPI_MPST_AUTOENTRY             2
#define ACPI_MPST_AUTOEXIT              4

/* Shared Memory Region (not part of an ACPI table) */

typedef struct acpi_mpst_shared
{
    UINT32                  Signature;
    UINT16                  PccCommand;
    UINT16                  PccStatus;
    UINT32                  CommandRegister;
    UINT32                  StatusRegister;
    UINT32                  PowerStateId;
    UINT32                  PowerNodeId;
    UINT64                  EnergyConsumed;
    UINT64                  AveragePower;

} ACPI_MPST_SHARED;

/*******************************************************************************
 *
 * PCCT - Platform Communications Channel Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_pcct
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  Flags;
    UINT64                  Reserved;

} ACPI_TABLE_PCCT;

/* Values for Flags field above */

#define ACPI_PCCT_DOORBELL              1

/* Values for subtable type in ACPI_SUBTABLE_HEADER */

enum AcpiPcctType
{
    ACPI_PCCT_TYPE_GENERIC_SUBSPACE     = 0,
    ACPI_PCCT_TYPE_HW_REDUCED_SUBSPACE  = 1,
    ACPI_PCCT_TYPE_RESERVED             = 2     /* 2 and greater are reserved */
};

/*
 * PCCT Subtables, correspond to Type in ACPI_SUBTABLE_HEADER
 */

/* 0: Generic Communications Subspace */

typedef struct acpi_pcct_subspace
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT8                   Reserved[6];
    UINT64                  BaseAddress;
    UINT64                  Length;
    ACPI_GENERIC_ADDRESS    DoorbellRegister;
    UINT64                  PreserveMask;
    UINT64                  WriteMask;
    UINT32                  Latency;
    UINT32                  MaxAccessRate;
    UINT16                  MinTurnaroundTime;

} ACPI_PCCT_SUBSPACE;

/* 1: HW-reduced Communications Subspace (ACPI 5.1) */

typedef struct acpi_pcct_hw_reduced
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT32                  DoorbellInterrupt;
    UINT8                   Flags;
    UINT8                   Reserved;
    UINT64                  BaseAddress;
    UINT64                  Length;
    ACPI_GENERIC_ADDRESS    DoorbellRegister;
    UINT64                  PreserveMask;
    UINT64                  WriteMask;
    UINT32                  Latency;
    UINT32                  MaxAccessRate;
    UINT16                  MinTurnaroundTime;

} ACPI_PCCT_HW_REDUCED;

/* Values for doorbell flags above */

#define ACPI_PCCT_INTERRUPT_POLARITY    (1)
#define ACPI_PCCT_INTERRUPT_MODE        (1<<1)

/*
 * PCC memory structures (not part of the ACPI table)
 */

/* Shared Memory Region */

typedef struct acpi_pcct_shared_memory
{
    UINT32                  Signature;
    UINT16                  Command;
    UINT16                  Status;

} ACPI_PCCT_SHARED_MEMORY;

/*******************************************************************************
 *
 * PMTT - Platform Memory Topology Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_pmtt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  Reserved;

} ACPI_TABLE_PMTT;

/* Common header for PMTT subtables that follow main table */

typedef struct acpi_pmtt_header
{
    UINT8                   Type;
    UINT8                   Reserved1;
    UINT16                  Length;
    UINT16                  Flags;
    UINT16                  Reserved2;

} ACPI_PMTT_HEADER;

/* Values for Type field above */

#define ACPI_PMTT_TYPE_SOCKET           0
#define ACPI_PMTT_TYPE_CONTROLLER       1
#define ACPI_PMTT_TYPE_DIMM             2
#define ACPI_PMTT_TYPE_RESERVED         3 /* 0x03-0xFF are reserved */

/* Values for Flags field above */

#define ACPI_PMTT_TOP_LEVEL             0x0001
#define ACPI_PMTT_PHYSICAL              0x0002
#define ACPI_PMTT_MEMORY_TYPE           0x000C

/*
 * PMTT subtables, correspond to Type in acpi_pmtt_header
 */

/* 0: Socket Structure */

typedef struct acpi_pmtt_socket
{
    ACPI_PMTT_HEADER        Header;
    UINT16                  SocketId;
    UINT16                  Reserved;

} ACPI_PMTT_SOCKET;

/* 1: Memory Controller subtable */

typedef struct acpi_pmtt_controller
{
    ACPI_PMTT_HEADER        Header;
    UINT32                  ReadLatency;
    UINT32                  WriteLatency;
    UINT32                  ReadBandwidth;
    UINT32                  WriteBandwidth;
    UINT16                  AccessWidth;
    UINT16                  Alignment;
    UINT16                  Reserved;
    UINT16                  DomainCount;

} ACPI_PMTT_CONTROLLER;

/* 1a: Proximity Domain substructure */

typedef struct acpi_pmtt_domain
{
    UINT32                  ProximityDomain;

} ACPI_PMTT_DOMAIN;

/* 2: Physical Component Identifier (DIMM) */

typedef struct acpi_pmtt_physical_component
{
    ACPI_PMTT_HEADER        Header;
    UINT16                  ComponentId;
    UINT16                  Reserved;
    UINT32                  MemorySize;
    UINT32                  BiosHandle;

} ACPI_PMTT_PHYSICAL_COMPONENT;

/*******************************************************************************
 *
 * RASF - RAS Feature Table (ACPI 5.0)
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_rasf
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT8                   ChannelId[12];

} ACPI_TABLE_RASF;

/* RASF Platform Communication Channel Shared Memory Region */

typedef struct acpi_rasf_shared_memory
{
    UINT32                  Signature;
    UINT16                  Command;
    UINT16                  Status;
    UINT16                  Version;
    UINT8                   Capabilities[16];
    UINT8                   SetCapabilities[16];
    UINT16                  NumParameterBlocks;
    UINT32                  SetCapabilitiesStatus;

} ACPI_RASF_SHARED_MEMORY;

/* RASF Parameter Block Structure Header */

typedef struct acpi_rasf_parameter_block
{
    UINT16                  Type;
    UINT16                  Version;
    UINT16                  Length;

} ACPI_RASF_PARAMETER_BLOCK;

/* RASF Parameter Block Structure for PATROL_SCRUB */

typedef struct acpi_rasf_patrol_scrub_parameter
{
    ACPI_RASF_PARAMETER_BLOCK   Header;
    UINT16                      PatrolScrubCommand;
    UINT64                      RequestedAddressRange[2];
    UINT64                      ActualAddressRange[2];
    UINT16                      Flags;
    UINT8                       RequestedSpeed;

} ACPI_RASF_PATROL_SCRUB_PARAMETER;

/* Masks for Flags and Speed fields above */

#define ACPI_RASF_SCRUBBER_RUNNING      1
#define ACPI_RASF_SPEED                 (7<<1)
#define ACPI_RASF_SPEED_SLOW            (0<<1)
#define ACPI_RASF_SPEED_MEDIUM          (4<<1)
#define ACPI_RASF_SPEED_FAST            (7<<1)

/* Channel Commands */

enum AcpiRasfCommands
{
    ACPI_RASF_EXECUTE_RASF_COMMAND      = 1
};

/* Platform RAS Capabilities */

enum AcpiRasfCapabiliities
{
    ACPI_HW_PATROL_SCRUB_SUPPORTED      = 0,
    ACPI_SW_PATROL_SCRUB_EXPOSED        = 1
};

/* Patrol Scrub Commands */

enum AcpiRasfPatrolScrubCommands
{
    ACPI_RASF_GET_PATROL_PARAMETERS     = 1,
    ACPI_RASF_START_PATROL_SCRUBBER     = 2,
    ACPI_RASF_STOP_PATROL_SCRUBBER      = 3
};

/* Channel Command flags */

#define ACPI_RASF_GENERATE_SCI          (1<<15)

/* Status values */

enum AcpiRasfStatus
{
    ACPI_RASF_SUCCESS                   = 0,
    ACPI_RASF_NOT_VALID                 = 1,
    ACPI_RASF_NOT_SUPPORTED             = 2,
    ACPI_RASF_BUSY                      = 3,
    ACPI_RASF_FAILED                    = 4,
    ACPI_RASF_ABORTED                   = 5,
    ACPI_RASF_INVALID_DATA              = 6
};

/* Status flags */

#define ACPI_RASF_COMMAND_COMPLETE      (1)
#define ACPI_RASF_SCI_DOORBELL          (1<<1)
#define ACPI_RASF_ERROR                 (1<<2)
#define ACPI_RASF_STATUS                (0x1F<<3)

/*******************************************************************************
 *
 * TPM2 - Trusted Platform Module (TPM) 2.0 Hardware Interface Table
 *        Version 3
 *
 * Conforms to "TPM 2.0 Hardware Interface Table (TPM2)" 29 November 2011
 *
 ******************************************************************************/

typedef struct acpi_table_tpm2
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  Flags;
    UINT64                  ControlAddress;
    UINT32                  StartMethod;

} ACPI_TABLE_TPM2;

/* Control area structure (not part of table, pointed to by ControlAddress) */

typedef struct acpi_tpm2_control
{
    UINT32                  Reserved;
    UINT32                  Error;
    UINT32                  Cancel;
    UINT32                  Start;
    UINT64                  InterruptControl;
    UINT32                  CommandSize;
    UINT64                  CommandAddress;
    UINT32                  ResponseSize;
    UINT64                  ResponseAddress;

} ACPI_TPM2_CONTROL;

/* Reset to default packing */

#pragma pack()

#endif /* __ACTBL3_H__ */


text:
<?php
namespace Provenance\Ui
{
    use \Provenance\DOM\Element as Element;
    use \Provenance\DOM\Attr as Attr;

    class Image
    {
        private $target;
        private $text;
        private $class;
        private $id;

        public function __construct($text, $target = '#', $id = null, $class = null)
        {
            $this->create($text, $target, $id, $class);
        }

        public function create($text, $target = '#', $id = null, $class = null)
        {
            $attributes = array(new Attr('src', $target));
            if($id)
            {
                $attributes[] = new Attr('id', $id);
            }
            if($class)
            {
                $attributes[] = new Attr('class', $class);
            }
            return Element::create('img', $attributes, $text);
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Airion.Common.Collections
{
	public sealed class QueuedSet<T> : LinkedList<T>, ICloneable
	{
		#region Constructors

		public QueuedSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
			: base()
		{
			Comparer = comparer;
			foreach(T item in collection) {
				Enqueue(item);
			}
		}

		public QueuedSet(IEqualityComparer<T> comparer)
			: base()
		{
			Comparer = comparer;
		}

		public QueuedSet(IEnumerable<T> collection)
			: this(collection, EqualityComparer<T>.Default)
		{

		}

		private QueuedSet(QueuedSet<T> other)
		{
			Comparer = other.Comparer;
			foreach(T item in other) {
				AddLast(item);
			}
		}

		public QueuedSet()
			: this(EqualityComparer<T>.Default)
		{
		}

		#endregion Constructors

		#region Methods

		// Public Methods

		public object Clone()
		{
			return new QueuedSet<T>(this);
		}

		public T Dequeue()
		{
			T result = First.Value;
			this.RemoveFirst();
			return result;
		}

		public void Enqueue(T item)
		{
			LinkedListNode<T> node = Last;
			while(node != null && !Comparer.Equals(node.Value, item)) {
				node = node.Previous;
			}

			if(node == null) {
				this.AddLast(item);
			} else if(node != Last) {
				this.Remove(node);
				this.AddLast(item);
			}
		}

		#endregion Methods

		#region Properties

		public IEqualityComparer<T> Comparer
		{
			get;
			private set;
		}

		#endregion Properties
	}
}


text:
ClinvarUploadDialog::ClinvarUploadDialog(QWidget *parent)
    : QDialog(parent)
    , ui_()
{
	if (!LoginManager::active())
	{
		INFO(DatabaseException, "ClinVar Upload requires logging in into NGSD!");
	}

	LoginManager::checkRoleNotIn(QStringList{"user_restricted"});

    ui_.setupUi(this);

    initGui();
}

void ClinvarUploadDialog::setData(ClinvarUploadData data)
{
    // set variant data

    QByteArray chr = data.variant.chr().strNormalized(false);
    ui_.cb_chr->setEnabled(false);
    ui_.cb_chr->setCurrentText(chr);
	ui_.le_start->setEnabled(false);
	ui_.le_end->setEnabled(false);
	ui_.le_ref->setEnabled(false);
	ui_.le_obs->setEnabled(false);

	if (data.variant.isSNV())
	{
		ui_.le_start->setText(QString::number(data.variant.start()));
		ui_.le_end->setText(QString::number(data.variant.end()));
		ui_.le_ref->setText(data.variant.ref());
		ui_.le_obs->setText(data.variant.obs());
	}
	else
	{
		//convert indels to VCF format
		static FastaFileIndex genome_index(Settings::string("reference_genome"));
		VcfLine vcf_variant = data.variant.toVCF(genome_index);

		ui_.le_start->setText(QString::number(vcf_variant.start()));
		ui_.le_end->setText(QString::number(vcf_variant.end()));
		ui_.le_ref->setText(vcf_variant.ref());
		ui_.le_obs->setText(vcf_variant.altString());
	}

    // set genes
    ui_.le_gene->setText(data.genes.join(","));

    // set phenotypes
    ui_.phenos->setPhenotypes(data.phenos);

    // set disease info
    ui_.tw_disease_info->setRowCount(data.disease_info.length());
    int row_idx = 0;
    foreach (const SampleDiseaseInfo& disease, data.disease_info)
    {
        ui_.tw_disease_info->setItem(row_idx, 0, new QTableWidgetItem(disease.type));
        ui_.tw_disease_info->setItem(row_idx, 1, new QTableWidgetItem(disease.disease_info));
        row_idx++;
    }

    // set classification
    ui_.cb_clin_sig_desc->setEnabled(false);
    ui_.cb_clin_sig_desc->setCurrentText(convertClassification(data.report_variant_config.classification));

    // set inheritance mode (if available)
    ui_.cb_inheritance->setCurrentText(convertInheritance(data.report_variant_config.inheritance));

    // set genome assembly
    ui_.cb_assembly->setEnabled(false);
    ui_.cb_assembly->setCurrentText(buildToString(GSvarHelper::build(), true));

	// set allele origin for de novo variants
    if(data.report_variant_config.de_novo)
    {
        ui_.cb_allele_origin->setCurrentText("de novo");
    }

    // set affected status
    ui_.cb_affected_status->setCurrentText(convertAffectedStatus(data.affected_status));

	// store given data
    clinvar_upload_data_ = data;

	// check for reupload
	if (clinvar_upload_data_.variant_publication_id > 0)
	{
		// reupload
		if (clinvar_upload_data_.stable_id.trimmed().isEmpty())
		{
			// reupload of failed submission
			setWindowTitle(windowTitle() + " (Reupload of failed submission by " + db_.userName(clinvar_upload_data_.user_id) + ")");
		}
		else
		{
			// modification of successful submission
			setWindowTitle(windowTitle() + " (Modification of successfull submission (" + clinvar_upload_data_.stable_id + ") by " + db_.userName(clinvar_upload_data_.user_id) + ")");
		}
	}

    //validate input
    checkGuiData();
}

void ClinvarUploadDialog::initGui()
{
    // set combobox entries
    ui_.cb_clin_sig_desc->addItems(CLINICAL_SIGNIFICANCE_DESCRIPTION);
    ui_.cb_inheritance->addItems(MODE_OF_INHERITANCE);
    ui_.cb_affected_status->addItems(AFFECTED_STATUS);
    ui_.cb_allele_origin->addItems(ALLELE_ORIGIN);
    ui_.cb_collection_method->addItems(COLLECTION_METHOD);
    ui_.cb_assembly->addItems(ASSEMBLY);
    ui_.cb_chr->addItems(CHR);

    // set date
    ui_.de_last_eval->setDate(QDate::currentDate());

    // set headers for disease info
    ui_.tw_disease_info->setColumnCount(2);
    ui_.tw_disease_info->setHorizontalHeaderItem(0, new QTableWidgetItem("type"));
    ui_.tw_disease_info->setHorizontalHeaderItem(1, new QTableWidgetItem("id"));
	//GUIHelper::resizeTableCells(ui_.tw_disease_info);
    ui_.tw_disease_info->setColumnWidth(0, 250);
    ui_.tw_disease_info->setColumnWidth(1, 150);

    // set defaults:
    ui_.cb_collection_method->setCurrentText("clinical testing");

    //connect signal and slots
    connect(ui_.upload_btn, SIGNAL(clicked(bool)), this, SLOT(upload()));
    connect(ui_.cb_chr, SIGNAL(currentTextChanged(QString)), this, SLOT(checkGuiData()));
    connect(ui_.le_gene, SIGNAL(textEdited(QString)), this, SLOT(checkGuiData()));
    connect(ui_.phenos, SIGNAL(phenotypeSelectionChanged()), this, SLOT(checkGuiData()));
    connect(ui_.print_btn, SIGNAL(clicked(bool)), this, SLOT(printResults()));
    connect(ui_.comment_upload, SIGNAL(textChanged()), this, SLOT(updatePrintButton()));

    checkGuiData();
}

void ClinvarUploadDialog::upload()
{
	//deactivate upload button
	ui_.upload_btn->setEnabled(false);

    QJsonObject clinvar_submission = createJson();

    QStringList errors;
    if (!validateJson(clinvar_submission, errors))
    {
        QMessageBox::warning(this, "JSON validation failed", "The generated JSON contains the following errors: \n" + errors.join("\n"));
		ui_.upload_btn->setEnabled(true);
        return;
    }

    ui_.comment_upload->setText("JSON validation successful.\n");

    // read API key
    QByteArray api_key = getSettings("clinvar_api_key").toUtf8();

    QJsonObject post_request;
    QJsonArray actions;
    QJsonObject action;
    action.insert("type", "AddData");
    action.insert("targetDb", "clinvar");
    QJsonObject data;
    data.insert("content", clinvar_submission);
    action.insert("data", data);
    actions.append(action);
    post_request.insert("actions", actions);

    // perform upload
    static HttpHandler http_handler(HttpRequestHandler::INI); //static to allow caching of credentials
    try
    {
        QStringList messages;
        messages << ui_.comment_upload->toPlainText();

        //add headers
        HttpHeaders add_headers;
        add_headers.insert("Content-Type", "application/json");
        add_headers.insert("SP-API-KEY", api_key);

        //post request
		QByteArray reply = http_handler.post("https://submit.ncbi.nlm.nih.gov/api/v1/submissions/", QJsonDocument(post_request).toJson(QJsonDocument::Compact), add_headers);

        // parse response
        bool success = false;
        QString submission_id;
        QJsonObject response = QJsonDocument::fromJson(reply).object();

        //successful dry-run
        if (response.isEmpty())
        {
            messages << "MESSAGE: Dry-run successful!";
        }
        else if (response.contains("id"))
        {
            //successfully submitted
            messages << "MESSAGE: The submission was successful!";
            submission_id = response.value("id").toString();
            messages << "MESSAGE: Submission ID: " + submission_id;
            success = true;
        }
        else if (response.contains("message"))
        {
            //errors
            messages << "ERROR: " + response.value("message").toString();
        }

        if (success)
        {
            // add entry to the NGSD
            QStringList details;
            details << "submission_id=" + submission_id;
            //clinical significance
            details << "clinical_significance_desc=" + ui_.cb_clin_sig_desc->currentText();
            details << "clinical_significance_comment=" + VcfFile::encodeInfoValue(ui_.le_clin_sig_desc_comment->text());
            details << "last_evaluatued=" + ui_.de_last_eval->date().toString("yyyy-MM-dd");
            details << "mode_of_inheritance=" + ui_.cb_inheritance->currentText();
            //condition set
            QStringList condition;
            for (int row_idx = 0; row_idx < ui_.tw_disease_info->rowCount(); ++row_idx)
            {
                condition << ui_.tw_disease_info->item(row_idx, 0)->text() + "|" + ui_.tw_disease_info->item(row_idx, 1)->text();
            }
            details << "condition=" + condition.join(',');
			details << "variant_id=" + QString::number(clinvar_upload_data_.variant_id);
			details << "variant_rc_id=" + QString::number(clinvar_upload_data_.report_config_variant_id);
            //observed in
            details << "affected_status=" + ui_.cb_affected_status->currentText();
            details << "allele_origin=" + ui_.cb_allele_origin->currentText();
            QStringList phenotypes;
            foreach (const Phenotype& phenotype, ui_.phenos->selectedPhenotypes())
            {
                phenotypes << phenotype.accession();
            }
            details << "clinical_features=" + phenotypes.join(',');
            details << "clinical_feature_comment=" + VcfFile::encodeInfoValue(ui_.le_clin_feat_comment->text());
			details << "collection_method=" + ui_.cb_collection_method->currentText();

            details << "release_status=" + ui_.cb_release_status->currentText();
            details << "gene=" +  NGSD().genesToApproved(GeneSet::createFromStringList(ui_.le_gene->text().replace(";", ",").split(','))).toStringList().join(',');

			// additional info for reupload
			if (clinvar_upload_data_.variant_publication_id > 0)
			{
				details << "reupload=true";
				details << "previous_publication_id=" + QString::number(clinvar_upload_data_.variant_publication_id);
				details << "reupload_by=" + LoginManager::userLogin();
			}

            // log publication in NGSD
			db_.addVariantPublication(clinvar_upload_data_.processed_sample, clinvar_upload_data_.variant, "ClinVar", clinvar_upload_data_.report_variant_config.classification,
									  details.join(";"), clinvar_upload_data_.user_id);

			// for reupload: flag previous upload as replaced
			if (clinvar_upload_data_.variant_publication_id > 0) db_.flagVariantPublicationAsReplaced(clinvar_upload_data_.variant_publication_id);

            //show result
            QStringList lines;
            lines << "DATA UPLOAD TO CLINVAR SUCCESSFUL";
            lines << "";
            lines << messages.join("\n");
            lines << "";
            lines << "sample: " + clinvar_upload_data_.processed_sample;
			// log original submitter for reuploads
			if (clinvar_upload_data_.user_id > 0)
			{
				lines << "user: " + db_.userLogin(clinvar_upload_data_.user_id) + " (Reupload by " + LoginManager::userLogin() + ")";
			}
			else
			{
				lines << "user: " + LoginManager::userLogin();
			}
            lines << "date: " + Helper::dateTime();
            lines << "";
            lines <setText(lines.join("\n").replace("=", ": "));

            //write report file to transfer folder
            QString gsvar_publication_folder = Settings::path("gsvar_publication_folder");
            if (gsvar_publication_folder!="")
            {
					QString file_rep = gsvar_publication_folder + "/" + clinvar_upload_data_.processed_sample + "_CLINVAR_" + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".txt";
                    Helper::storeTextFile(file_rep, ui_.comment_upload->toPlainText().split("\n"));
            }
			ui_.upload_btn->setEnabled(false);

        }
        else
        {
            // Upload failed
            ui_.comment_upload->setText("DATA UPLOAD ERROR:\n" + messages.join("\n"));
            ui_.upload_btn->setEnabled(true);
        }
    }
    catch(Exception e)
    {
        ui_.comment_upload->setText("DATA UPLOAD FAILED:\n" + e.message());
        ui_.upload_btn->setEnabled(true);
    }

}

bool ClinvarUploadDialog::checkGuiData()
{
	ui_.comment_upload->clear();

    //check if already published
	bool uploaded_to_clinvar = false;
	QString upload_details;
    if (clinvar_upload_data_.processed_sample !="" && clinvar_upload_data_.variant.isValid())
    {
		upload_details = db_.getVariantPublication(clinvar_upload_data_.processed_sample, clinvar_upload_data_.variant);
        if (upload_details!="")
        {
			//check if uploaded to Clinvar
			foreach (const QString& line, upload_details.split('\n'))
			{
				QStringList columns = line.split(' ');
				for (int i = 0; i < (columns.size()-1); ++i)
				{
					if (columns[i] == "db:")
					{
						if (columns[i+1] == "ClinVar")
						{
							// already uploaded to ClinVar
							uploaded_to_clinvar = true;
						}
						break;
					}
				}
				// shortcut
				if (uploaded_to_clinvar) break;
			}
        }
    }

    //perform checks
	QStringList errors;
    // check chromosome
    if (ui_.cb_chr->currentText().trimmed().isEmpty())
    {
        errors << "Chromosome unset!";
    }

    // check sequences
    QRegExp re("[-]|[ACGTU]*");
    if (!re.exactMatch(ui_.le_ref->text()))
    {
        errors << "invalid reference sequence '" + ui_.le_ref->text() + "'!";
    }
    if (!re.exactMatch(ui_.le_obs->text()))
    {
        errors << "invalid observed sequence '" + ui_.le_obs->text() + "'!";
    }

    //check genes
    GeneSet gene_set = GeneSet::createFromStringList(ui_.le_gene->text().split(','));
    QStringList invalid_genes;
    foreach (const QByteArray gene, gene_set)
    {
        QByteArray approved_gene_name = NGSD().geneToApproved(gene, false);
        if(approved_gene_name.isEmpty() || (gene != approved_gene_name))
        {
            invalid_genes << gene;
        }
    }
    if (invalid_genes.size() > 0)
    {
        errors << (invalid_genes.join(", ") + " are not HGNC approved gene names!");
    }

    // check phenotypes
    if (ui_.phenos->selectedPhenotypes().count()==0)
    {
        errors << "No phenotypes selected!";
    }

    // check inheritance
    if (!MODE_OF_INHERITANCE.contains(ui_.cb_inheritance->currentText()))
    {
        errors << "No valid inheritance mode selected!";
    }

	QStringList upload_comment_text;
	if (uploaded_to_clinvar)
	{
		upload_comment_text << "WARNING: This variant has already been uploaded to ClinVar! Are you sure you want to upload it again?
" + upload_details.replace("\n", "
");
	}

    //show error or enable upload button
    if (errors.count()>0)
    {
        ui_.upload_btn->setEnabled(false);
		upload_comment_text << "Cannot upload data because:
  - " +  errors.join("
  - ");
		ui_.comment_upload->setText(upload_comment_text.join("

"));
        return false;
    }
    else
    {
        ui_.upload_btn->setEnabled(true);
		ui_.comment_upload->setText(upload_comment_text.join("
"));
        return true;
    }
}

void ClinvarUploadDialog::printResults()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setFullPage(true);
    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    if (dlg->exec() == QDialog::Accepted)
    {
        QTextDocument *doc = new QTextDocument();
        doc->setPlainText(ui_.comment_upload->toPlainText());
        doc->print(&printer);
        delete doc;
    }
    delete dlg;
}

void ClinvarUploadDialog::updatePrintButton()
{
    ui_.print_btn->setEnabled(!ui_.comment_upload->toPlainText().trimmed().isEmpty());
}

QJsonObject ClinvarUploadDialog::createJson()
{
    //Check GUI for correct entries
    if (!checkGuiData())
    {
        QMessageBox::warning(this, "Gui validation failed!", "There are errors in you GUI input. Please fix them and try again.");
        return QJsonObject();
    }

    //build up JSON
    QJsonObject json;

    //required
    QJsonObject clinvar_submission;
    {
        //optional
        QJsonObject assertion_criteria;
        {
            // add hardcoded citation
            QJsonObject citation;
            citation.insert("db", "PubMed");
            citation.insert("id", "25741868");
            assertion_criteria.insert("citation", citation);
            assertion_criteria.insert("method", "ACMG Guidelines, 2015");
        }
        clinvar_submission.insert("assertionCriteria", assertion_criteria);

        //required
        QJsonObject clinical_significance;
        {
            //required
            clinical_significance.insert("clinicalSignificanceDescription", ui_.cb_clin_sig_desc->currentText());

            //optional
            if (!ui_.le_clin_sig_desc_comment->text().trimmed().isEmpty())
            {
                clinical_significance.insert("comment", ui_.le_clin_sig_desc_comment->text());
            }

            //optional
            clinical_significance.insert("dateLastEvaluated", ui_.de_last_eval->date().toString("yyyy-MM-dd"));

            //optional
            if (!ui_.cb_inheritance->currentText().trimmed().isEmpty())
            {
                clinical_significance.insert("modeOfInheritance", ui_.cb_inheritance->currentText());
            }
        }
        clinvar_submission.insert("clinicalSignificance", clinical_significance);

        //optional
		if (!clinvar_upload_data_.stable_id.isEmpty())
		{
			clinvar_submission.insert("clinvarAccession", clinvar_upload_data_.stable_id);
		}

        //required
        QJsonObject condition_set;
        {
            QJsonArray condition;
            {
                for (int row_idx = 0; row_idx < ui_.tw_disease_info->rowCount(); ++row_idx)
                {
                    if (ui_.tw_disease_info->item(row_idx, 0)->text() == "OMIM disease/phenotype identifier")
                    {
                        QJsonObject disease_info;
                        disease_info.insert("db", "OMIM");
						//extract ID
						QString omim_id = ui_.tw_disease_info->item(row_idx, 1)->text();
						if (!omim_id.startsWith("#")) THROW(ArgumentException, "Invalid OMIM id '" + ui_.tw_disease_info->item(row_idx, 1)->text() + "'!");
						omim_id = omim_id.split('#').at(1);
						bool ok;
						omim_id.toInt(&ok);
						if (!ok) THROW(ArgumentException, "Invalid OMIM id '" + ui_.tw_disease_info->item(row_idx, 1)->text() + "'!");
						disease_info.insert("id", omim_id);
                        condition.append(disease_info);
                    }
                    else if (ui_.tw_disease_info->item(row_idx, 0)->text() == "Orpha number")
                    {
                        QJsonObject disease_info;
                        disease_info.insert("db", "Orphanet");
						//extract ID
						QString orphanet_id = ui_.tw_disease_info->item(row_idx, 1)->text();
						if (!orphanet_id.startsWith("ORPHA:")) THROW(ArgumentException, "Invalid Orphanet id '" + ui_.tw_disease_info->item(row_idx, 1)->text() + "'!");
						orphanet_id = orphanet_id.split(':').at(1);
						bool ok;
						orphanet_id.toInt(&ok);
						if (!ok) THROW(ArgumentException, "Invalid Orphanet id '" + ui_.tw_disease_info->item(row_idx, 1)->text() + "'!");
						disease_info.insert("id", orphanet_id);
                        condition.append(disease_info);
                    }
                    else
                    {
                        THROW(ArgumentException, "Invalid disease info '" + ui_.tw_disease_info->item(row_idx, 0)->text() + "' in disease info table!");
                    }
                }
            }
            condition_set.insert("condition", condition);
        }
        clinvar_submission.insert("conditionSet", condition_set);

        //optional
        clinvar_submission.insert("localID", QString::number(clinvar_upload_data_.variant_id));

        //optional
		clinvar_submission.insert("localKey", QString::number(clinvar_upload_data_.report_config_variant_id));

        //required
        QJsonObject observed_in;
        {
            //required
            observed_in.insert("affectedStatus", ui_.cb_affected_status->currentText());

            //required
            observed_in.insert("alleleOrigin", ui_.cb_allele_origin->currentText());

            //optional
            QJsonArray clinical_features;
            {
                foreach (const Phenotype& phenotype, ui_.phenos->selectedPhenotypes())
                {
                    QJsonObject feature;
                    feature.insert("db", "HP");
                    feature.insert("id", QString(phenotype.accession()));
					feature.insert("clinicalFeaturesAffectedStatus", "present");
                    clinical_features.append(feature);

                }
            }
            observed_in.insert("clinicalFeatures", clinical_features);

            //optional
            if (!ui_.le_clin_feat_comment->text().trimmed().isEmpty())
            {
                observed_in.insert("clinicalFeaturesComment", ui_.le_clin_feat_comment->text());
            }

            //required
            observed_in.insert("collectionMethod", ui_.cb_collection_method->currentText());

            //optional
            //observed_in.insert("numberOfIndividuals", ui_.sb_n_individuals->value());

            //optional
            //observed_in.insert("structVarMethodType", ui_.cb_method_type->currentText());

        }
        clinvar_submission.insert("observedIn", QJsonArray() << observed_in);

        //required
		clinvar_submission.insert("recordStatus", "novel");

        //required
        clinvar_submission.insert("releaseStatus", ui_.cb_release_status->currentText());

        //required
        QJsonObject variant_set;
        {
            QJsonArray variants;
            {
                //variant
                QJsonObject variant;
                {
                    //required (except hgvs)
                    QJsonObject chromosome_coordinates;
                    {
                        chromosome_coordinates.insert("alternateAllele", ui_.le_obs->text());
                        chromosome_coordinates.insert("assembly", ui_.cb_assembly->currentText());
                        chromosome_coordinates.insert("chromosome", ui_.cb_chr->currentText());
                        chromosome_coordinates.insert("referenceAllele", ui_.le_ref->text());
                        chromosome_coordinates.insert("start", Helper::toInt(ui_.le_start->text()));
                        chromosome_coordinates.insert("stop", Helper::toInt(ui_.le_end->text()));
                    }
                    variant.insert("chromosomeCoordinates", chromosome_coordinates);

					//optional (but required for deletions and insertions)
					QString variant_type;
					if (ui_.le_ref->text().contains("-") || ui_.le_ref->text().trimmed().isEmpty()) variant_type = "Insertion";
					if (ui_.le_obs->text().contains("-") || ui_.le_obs->text().trimmed().isEmpty()) variant_type = "Deletion";
					if (!variant_type.isEmpty()) variant.insert("variantType", variant_type);

                    //optional
                    if (!ui_.le_gene->text().trimmed().isEmpty())
                    {
                        QJsonArray genes;
                        {
                            GeneSet gene_set = NGSD().genesToApproved(GeneSet::createFromStringList(ui_.le_gene->text().replace(";", ",").split(',')));
                            foreach (const QByteArray& gene_name, gene_set)
                            {
                                QJsonObject gene;
                                gene.insert("symbol", QString(gene_name));
                                genes.append(gene);
                            }
                        }
                        variant.insert("gene", genes);
                    }

                }
                variants.append(variant);
            }
            variant_set.insert("variant", variants);

        }
        clinvar_submission.insert("variantSet", variant_set);

    }
    json.insert("clinvarSubmission", QJsonArray() << clinvar_submission);

    //optional
    //json.insert("submissionName", "");

    return json;
}

bool ClinvarUploadDialog::validateJson(const QJsonObject& json, QStringList& errors)
{
    bool is_valid = true;
    // check clinvarSubmission
    if (!json.contains("clinvarSubmission"))
    {
        errors << "Required JSON object 'clinvarSubmission' missing!";
        return false;
    }

    QJsonArray clinvar_submission_array = json.value("clinvarSubmission").toArray();
    if (clinvar_submission_array.size() < 1)
    {
        errors << "No entry in 'clinvarSubmission'!";
        return false;
    }
    else if (clinvar_submission_array.size() > 1)
    {
        errors << "Multiple entries in 'clinvarSubmission'!";
        return false;
    }
    QJsonObject clinvar_submission = clinvar_submission_array[0].toObject();

    // check required entries
    if (clinvar_submission.contains("recordStatus"))
    {
        QStringList record_status = QStringList() <<  "novel" << "update";
        if (!record_status.contains(clinvar_submission.value("recordStatus").toString()))
        {
            errors << "Invalid entry '" + clinvar_submission.value("recordStatus").toString() + "' in 'recordStatus'!";
            is_valid = false;
        }
    }
    else
    {
        errors << "Required string 'recordStatus' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

    if (clinvar_submission.contains("releaseStatus"))
    {
        QStringList release_status = QStringList() <<  "public" << "hold until published";
        if (!release_status.contains(clinvar_submission.value("releaseStatus").toString()))
        {
            errors << "Invalid entry '" + clinvar_submission.value("releaseStatus").toString() + "' in 'releaseStatus'!";
            is_valid = false;
        }
    }
    else
    {
        errors << "Required string 'releaseStatus' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

    if (clinvar_submission.contains("clinicalSignificance"))
    {
        //parse clinicalSignificance
        QJsonObject clinical_significance = clinvar_submission.value("clinicalSignificance").toObject();
        if (clinical_significance.contains("clinicalSignificanceDescription"))
        {
            if (!CLINICAL_SIGNIFICANCE_DESCRIPTION.contains(clinical_significance.value("clinicalSignificanceDescription").toString()))
            {
                errors << "Invalid entry '" + clinical_significance.value("clinicalSignificanceDescription").toString() + "' in 'clinicalSignificanceDescription'!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required string 'clinicalSignificanceDescription' in 'clinicalSignificance' missing!";
            is_valid = false;
        }

    }
    else
    {
        errors << "Required string 'clinicalSignificance' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

	if (clinvar_submission.contains("clinvarAccession"))
	{
		//parse optional ClinVar accession
		QString scv_id = clinvar_submission.value("clinvarAccession").toString();
		if (!scv_id.startsWith("SCV"))
		{
			errors << "ID '" + scv_id + "' for 'clinvarAccession' in 'clinvarSubmission' doesn't match the required format (Has to start with SCV)!";
			is_valid = false;
		}
	}

    if (clinvar_submission.contains("observedIn"))
    {
        // allow only one entry in observedIn array
        QJsonArray observed_in_array = clinvar_submission.value("observedIn").toArray();
        if (observed_in_array.size() < 1)
        {
            errors << "No entry in 'observedIn'!";
            return false;
        }
        else if (observed_in_array.size() > 1)
        {
            errors << "Multiple entries in 'observedIn'!";
            return false;
        }

        //parse observedIn
        QJsonObject observed_in = observed_in_array[0].toObject();
        if (observed_in.contains("alleleOrigin"))
        {
            if (!ALLELE_ORIGIN.contains(observed_in.value("alleleOrigin").toString()))
            {
                errors << "Invalid entry '" + observed_in.value("alleleOrigin").toString() + "' in 'observedIn'!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required string 'alleleOrigin' in 'observedIn' missing!";
            is_valid = false;
        }
        if (observed_in.contains("affectedStatus"))
        {
            if (!AFFECTED_STATUS.contains(observed_in.value("affectedStatus").toString()))
            {
                errors << "Invalid entry '" + observed_in.value("affectedStatus").toString() + "' in 'observedIn'!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required string 'affectedStatus' in 'observedIn' missing!";
            is_valid = false;
        }
        if (observed_in.contains("collectionMethod"))
        {
            if (!COLLECTION_METHOD.contains(observed_in.value("collectionMethod").toString()))
            {
                errors << "Invalid entry '" + observed_in.value("collectionMethod").toString() + "' in 'observedIn'!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required string 'collectionMethod' in 'observedIn' missing!";
            is_valid = false;
        }

    }
    else
    {
        errors << "Required JSON object 'observedIn' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

    if (clinvar_submission.contains("variantSet"))
    {
        //parse variantSet
        QJsonObject variant_set = clinvar_submission.value("variantSet").toObject();
        if (variant_set.contains("variant"))
        {
            QJsonArray variant_array = variant_set.value("variant").toArray();
            if (variant_array.size() > 0)
            {
                foreach (const QJsonValue& variant, variant_array)
                {
                    if (variant.toObject().contains("chromosomeCoordinates"))
                    {
                        QJsonObject chromosome_coordinates = variant.toObject().value("chromosomeCoordinates").toObject();
                        if (chromosome_coordinates.contains("chromosome"))
                        {
                            if (!CHR.contains(chromosome_coordinates.value("chromosome").toString()))
                            {
                                errors << "Invalid entry '" + chromosome_coordinates.value("chromosome").toString() + "' in 'chromosome'!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Required string 'chromosome' in 'chromosomeCoordinates' missing!";
                            is_valid = false;
                        }

                        if (chromosome_coordinates.contains("start"))
                        {
							int valid_int = chromosome_coordinates.value("start").toInt(-1);
							if (valid_int < 0)
                            {
                                errors << "Invalid entry '" + chromosome_coordinates.value("start").toString() + "' in 'start'!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Required number 'start' in 'chromosomeCoordinates' missing!";
                            is_valid = false;
                        }

                        if (chromosome_coordinates.contains("stop"))
                        {
							int valid_int = chromosome_coordinates.value("stop").toInt(-1);
							if (valid_int < 0)
                            {
                                errors << "Invalid entry '" + chromosome_coordinates.value("stop").toString() + "' in 'stop'!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Required number 'stop' in 'chromosomeCoordinates' missing!";
                            is_valid = false;
                        }

                        if (chromosome_coordinates.contains("referenceAllele"))
                        {
                            QString ref = chromosome_coordinates.value("referenceAllele").toString().trimmed();
                            QRegExp re("[-]|[ACGTUacgtu]+");
                            if (!re.exactMatch(ref))
                            {
                                errors << "Invalid entry '" + ref + "' in 'referenceAllele'!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Required string 'referenceAllele' in 'chromosomeCoordinates' missing!";
                            is_valid = false;
                        }

                        if (chromosome_coordinates.contains("alternateAllele"))
                        {
                            QString alt = chromosome_coordinates.value("alternateAllele").toString().trimmed();
                            QRegExp re("[-]|[ACGTUacgtu]+");
                            if (alt != "-" && !alt.isEmpty() && !re.exactMatch(alt))
                            {
                                errors << "Invalid entry '" + alt + "' in 'alternateAllele'!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Required string 'alternateAllele' in 'chromosomeCoordinates' missing!";
                            is_valid = false;
                        }

                    }
                    else
                    {
                        errors << "Required JSON object 'chromosomeCoordinates' in 'variant' missing!";
                        is_valid = false;
                    }

					if (variant.toObject().contains("variantType"))
					{
						QString variant_type = variant.toObject().value("chromosomeCoordinates").toString();
						if (!VARIANT_TYPE.contains(variant_type))
						{
							errors << "Invalid variantType '" + variant_type + "'!";
							is_valid = false;
						}
					}
                }
            }
            else
            {
				errors << "JSON array 'variant' in 'variantSet' has to have at least one entry!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required JSON array 'variant' in 'variantSet' missing!";
            is_valid = false;
        }

    }
    else
    {
        errors << "Required string 'variantSet' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

    if (clinvar_submission.contains("conditionSet"))
    {
        //parse variantSet
        QJsonObject condition_set = clinvar_submission.value("conditionSet").toObject();
        if (condition_set.contains("condition"))
        {
            QJsonArray condition_array = condition_set.value("condition").toArray();
            if (condition_array.size() > 0)
            {
                foreach (const QJsonValue& condition, condition_array)
                {
                    if (condition.toObject().contains("db"))
                    {
                        QString db = condition.toObject().value("db").toString();
                        if (db == "OMIM")
                        {
                            if (condition.toObject().contains("id"))
                            {
                                QString id = condition.toObject().value("id").toString();
								bool ok;
								id.toInt(&ok);
								if (!ok)
                                {
                                    errors << "Invalid entry '" + id + "' in 'id'!";
                                    is_valid = false;
                                }
                            }
                            else
                            {
                                errors << "Required string 'id' in 'condition' missing!";
                                is_valid = false;
                            }
                        }
                        else if (db == "Orphanet")
                        {
                            if (condition.toObject().contains("id"))
                            {
                                QString id = condition.toObject().value("id").toString();
								bool ok;
								id.toInt(&ok);
								if (!ok)
								{
                                    errors << "Invalid entry '" + id + "' in 'id'!";
                                    is_valid = false;
                                }
                            }
                            else
                            {
                                errors << "Required string 'id' in 'condition' missing!";
                                is_valid = false;
                            }
                        }
                        else
                        {
                            errors << "Invalid entry '" + db + "' in 'db'!";
                            is_valid = false;
                        }
                    }
                    else
                    {
                        errors << "Required string 'db' in 'condition' missing!";
                        is_valid = false;
                    }
                }
            }
            else
            {
                errors << "JSON array 'condition' in 'conditionSet' has to have at least one entry!";
                is_valid = false;
            }
        }
        else
        {
            errors << "Required JSON array 'variant' in 'variantSet' missing!";
            is_valid = false;
        }

    }
    else
    {
        errors << "Required string 'conditionSet' in 'clinvarSubmission' missing!";
        is_valid = false;
    }

    return is_valid;
}

QString ClinvarUploadDialog::getSettings(QString key)
{
    QString output = Settings::string(key).trimmed();
    if (output.isEmpty())
    {
        THROW(FileParseException, "Settings INI file does not contain key '" + key + "'!");
    }
    return output;
}

QString ClinvarUploadDialog::convertClassification(QString classification)
{
    if (classification=="5")
    {
        return "Pathogenic";
    }
    if (classification=="4")
    {
        return "Likely pathogenic";
    }
    if (classification=="3" || classification=="n/a" || classification=="")
    {
        return "Uncertain significance";
    }
    if (classification=="2")
    {
        return "Likely benign";
    }
    if (classification=="1")
    {
        return "Benign";
    }
    else if (classification=="M")
    {
        return "risk factor";
    }

    THROW(ProgrammingException, "Unknown classification '" + classification + "' in ClinvarUploadDialog::convertClassification(...) method!");
}

QString ClinvarUploadDialog::convertInheritance(QString inheritance)
{
    if (inheritance == "AR")
    {
        return "Autosomal recessive inheritance";
    }
    if (inheritance == "AD")
    {
        return "Autosomal dominant inheritance";
    }
    if (inheritance == "XLR")
    {
        return "X-linked recessive inheritance";
    }
    if (inheritance == "XLD")
    {
        return "X-linked dominant inheritance";
    }
    if (inheritance == "MT")
    {
        return "Mitochondrial inheritance";
    }
    if (inheritance == "n/a")
    {
        return "";
    }
    THROW(ProgrammingException, "Unknown inheritance mode '" + inheritance + "' in ClinvarUploadDialog::convertInheritance(...) method!");
}

QString ClinvarUploadDialog::convertAffectedStatus(QString affected_status)
{
    if (affected_status == "n/a")
    {
        return "not provided";
    }
    if (affected_status == "Affected")
    {
        return "yes";
    }
    if (affected_status == "Unaffected")
    {
        return "no";
    }
    if (affected_status == "Unclear")
    {
        return "unknown";
    }
    THROW(ProgrammingException, "Unknown affected status '" + affected_status + "' in ClinvarUploadDialog::convertAffectedStatus(...) method!");
}

//Define enum sets with allowed values for JSON output
const QStringList ClinvarUploadDialog::CLINICAL_SIGNIFICANCE_DESCRIPTION =
{
    "Pathogenic",
    "Likely pathogenic",
    "Uncertain significance",
    "Likely benign",
    "Benign",
    "affects",
    "association",
    "drug response",
    "confers sensitivity",
    "protective",
    "risk factor",
    "other",
    "not provided"
};
const QStringList ClinvarUploadDialog::MODE_OF_INHERITANCE =
{
    "",
    "Autosomal dominant inheritance",
    "Autosomal recessive inheritance",
    "Mitochondrial inheritance",
    "Somatic mutation",
    "Genetic anticipation",
    "Sporadic",
    "Sex-limited autosomal dominant",
    "X-linked recessive inheritance",
    "X-linked dominant inheritance",
    "Y-linked inheritance",
    "Other",
    "X-linked inheritance",
    "Codominant",
    "Autosomal unknown",
    "Autosomal dominant inheritance with maternal imprinting",
    "Autosomal dominant inheritance with paternal imprinting",
    "Multifactorial inheritance",
    "Unknown mechanism",
    "Oligogenic inheritance"
};
const QStringList ClinvarUploadDialog::AFFECTED_STATUS =
{
    "yes",
    "no",
    "unknown",
    "not provided",
    "not applicable"
};
const QStringList ClinvarUploadDialog::ALLELE_ORIGIN =
{
    "germline",
    "somatic",
    "de novo",
    "unknown",
    "not provided",
    "inherited",
    "maternal",
    "paternal",
    "biparental",
    "not-reported",
    "tested-inconclusive",
    "not applicable",
    "experimentally generated"
};
const QStringList ClinvarUploadDialog::COLLECTION_METHOD =
{
    "curation",
    "literature only",
    "reference population",
    "provider interpretation",
    "phenotyping only",
    "case-control",
    "clinical testing",
    "in vitro",
    "in vivo",
    "research",
    "not provided"
};
const QStringList ClinvarUploadDialog::STRUCT_VAR_METHOD_TYPE =
{
    "",
    "SNP array",
    "Oligo array",
    "Read depth",
    "Paired-end mapping",
    "One end anchored assembly",
    "Sequence alignment",
    "Optical mapping",
    "Curated,PCR"
};
const QStringList ClinvarUploadDialog::ASSEMBLY =
{
    "GRCh38",
    "hg38",
    "GRCh37",
    "hg19",
    "NCBI36",
    "hg18"
};
const QStringList ClinvarUploadDialog::CHR =
{
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12",
    "13",
    "14",
    "15",
    "16",
    "17",
    "18",
    "19",
    "20",
    "21",
    "22",
    "X",
    "Y",
	"MT"
};
const QStringList ClinvarUploadDialog::VARIANT_TYPE =
{
    "",
    "Variation",
    "Insertion",
    "Mobile element insertion",
    "Novel sequence insertion",
    "Microsatellite",
    "Deletion",
    "single nucleotide variant",
    "Multiple nucleotide variation",
    "Indel",
    "Duplication",
    "Tandem duplication",
    "copy number loss",
    "copy number gain",
    "protein only",
    "Inversion",
    "Translocation",
    "Interchromosomal breakpoint",
    "Intrachromosomal breakpoint",
    "Complex"
};


text:
/***
 Wait for Process Termination.

@module posix.sys.wait
*/

#include <sys/wait.h>

#include "_helpers.c"

/***
Wait for child process to terminate.
@function wait
@int[opt=-1] pid child process id to wait for, or -1 for any child process
@int[opt] options bitwise OR of `WNOHANG` and `WUNTRACED`
@treturn[1] int pid of running child, if not exited yet and called with `WNOHANG`
@treturn[1] string "running"
@treturn[2] int pid of terminated child, if successful
@treturn[2] string "exited", "killed" or "stopped"
@treturn[2] int exit status, or signal number responsible for "killed" or "stopped"
@return[3] nil
@treturn[3] string error message
@treturn[3] int errnum
@see waitpid(2)
@see posix.unistd.fork
*/
static int
Pwait(lua_State *L)
{
	int status = 0;
	pid_t pid = optint(L, 1, -1);
	int options = optint(L, 2, 0);
	checknargs(L, 2);

	pid = waitpid(pid, &status, options);
	if (pid == -1)
		return pusherror(L, NULL);
	lua_pushinteger(L, pid);
	if (pid == 0)
	{
		lua_pushliteral(L,"running");
		return 2;
	}
	else if (WIFEXITED(status))
	{
		lua_pushliteral(L,"exited");
		lua_pushinteger(L, WEXITSTATUS(status));
		return 3;
	}
	else if (WIFSIGNALED(status))
	{
		lua_pushliteral(L,"killed");
		lua_pushinteger(L, WTERMSIG(status));
		return 3;
	}
	else if (WIFSTOPPED(status))
	{
		lua_pushliteral(L,"stopped");
		lua_pushinteger(L, WSTOPSIG(status));
		return 3;
	}
	return 1;
}

static const luaL_Reg posix_sys_wait_fns[] =
{
	LPOSIX_FUNC( Pwait		),
	{NULL, NULL}
};

/***
Constants.
@section constants
*/

/***
Wait constants.
Any constants not available in the underlying system will be `nil` valued.
@table posix.sys.wait
@int WNOHANG don't block waiting
@int WUNTRACED report status of stopped children
@usage
  -- Print wait constants supported on this host.
  for name, value in pairs (require "posix.sys.wait") do
    if type (value) == "number" then
      print (name, value)
     end
  end
*/

LUALIB_API int
luaopen_posix_sys_wait(lua_State *L)
{
	luaL_newlib(L, posix_sys_wait_fns);

	lua_pushstring(L, LPOSIX_VERSION_STRING("sys.wait"));
	lua_setfield(L, -2, "version");

	LPOSIX_CONST( WNOHANG		);
	LPOSIX_CONST( WUNTRACED		);

	return 1;
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <description>Kurento Chroma module</description>
        <url>http://www.kurento.org/</url>

        <licenses>
          <license>
              <name>Apache 2.0</name>
              <url>http://www.apache.org/licenses/LICENSE-2.0</url>
              <distribution>repo</distribution>
          </license>
        </licenses>

        <developers>
          <developer>
              <id>kurento.org</id>
              <name>Kurento Community</name>
              <organization>kurento.org</organization>
              <organizationUrl>http://www.kurento.org</organizationUrl>
          </developer>
        </developers>

        <scm>
          <url>https://github.com/Kurento/kms-chroma</url>
          <connection>scm:git:https://github.com/Kurento/kms-chroma.git</connection>
          <developerConnection>scm:git:ssh://github.com/Kurento/kms-chroma.git</developerConnection>
        </scm>

</project>


text:
class Student < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  devise :omniauthable, :omniauth_providers => [:facebook, :github]
  has_many :notes
  has_many :tracks
  has_many :topics
  has_many :units
  has_many :lessons
  has_many :lesson_tags, through: :lessons
  has_many :tags, through: :lesson_tags
  belongs_to :current_track, class_name: 'Track', optional: true
  scope :on_track,
      (->(track) { select { |student| student.current_track.slug = track unless student.current_track.nil?} } )

  def self.from_omniauth(auth)
   where(provider: auth.provider, uid: auth.uid).first_or_create do |student|
     student.email = auth.info.email
     student.password = Devise.friendly_token[0,20]
   end
  end

end


text:
namespace Microsoft.Azure.Management.Compute.Models
{

    /// <summary>
    /// Defines values for GalleryProvisioningState.
    /// </summary>
    public static class GalleryProvisioningState
    {
        public const string Creating = "Creating";
        public const string Updating = "Updating";
        public const string Failed = "Failed";
        public const string Succeeded = "Succeeded";
        public const string Deleting = "Deleting";
        public const string Migrating = "Migrating";
    }
}