text:
LPCTSTR ErrorTextFromErrorId(unsigned int uiErrorId, bool bIsPsrec)
{
   if (bIsPsrec)
   {
      // these are different to the other common codes, so treat them specially here
      switch (uiErrorId)
      {
         // Function Parameter errors
      case prINVALID_PARAMETER: return _T("Invalid parameter");
      case prINVALID_HANDLE: return _T("Invalid handle");
      case prINVALID_FN_CALL: return _T("Invalid function call");
      case prWAIT_TIMEOUT_ERROR: return _T("Wait timeout error");
      case prINSUFFICIENT_BUFFER: return _T("Insufficient buffer");
      case prEVENT_CALLBACK_EXIST: return _T("Event callback exists");
      }
   }

   switch (uiErrorId)
   {
   case cdOK: return _T("OK");

      // Miscellaneous errors
   case cdUNIMPLEMENTED: return _T("Unimplemented");
   case cdINTERNAL_ERROR: return _T("Internal Error");
   case cdMEM_ALLOC_FAILED: return _T("Mem alloc failed");
   case cdMEM_FREE_FAILED: return _T("Mem free failed");
   case cdOPERATION_CANCELLED: return _T("Operation cancelled");
   case cdINCOMPATIBLE_VERSION: return _T("Incompatible version");
   case cdNOT_SUPPORTED: return _T("Not supported");
   case cdUNEXPECTED_EXCEPTION: return _T("Unexpected exception");
   case cdPROTECTION_VIOLATION: return _T("Protection violation");
   case cdMISSING_SUBCOMPONENT: return _T("Missing subcomponent");
   case cdSELECTION_UNAVAILABLE: return _T("Selection unavailable");

      // File errors
   case cdFILE_IO_ERROR: return _T("File IO error");
   case cdFILE_TOO_MANY_OPEN: return _T("Too many files open");
   case cdFILE_NOT_FOUND: return _T("File not found");
   case cdFILE_OPEN_ERROR: return _T("File open error");
   case cdFILE_CLOSE_ERROR: return _T("File close error");
   case cdFILE_SEEK_ERROR: return _T("File seek error");
   case cdFILE_TELL_ERROR: return _T("File tell error");
   case cdFILE_READ_ERROR: return _T("File read error");
   case cdFILE_WRITE_ERROR: return _T("File write error");
   case cdFILE_PERMISSION_ERROR: return _T("File permission error");
   case cdFILE_DISK_FULL_ERROR: return _T("Disk full error");
   case cdFILE_ALREADY_EXISTS: return _T("File already exists");
   case cdFILE_FORMAT_UNRECOGNIZED: return _T("File format not recognized");
   case cdFILE_DATA_CORRUPT: return _T("File data corrupt");
   case cdFILE_NAMING_NA: return _T("File naming N/A");

      // Directory errors
   case cdDIR_NOT_FOUND: return _T("Dir not found");
   case cdDIR_IO_ERROR: return _T("Dir IO error");
   case cdDIR_ENTRY_NOT_FOUND: return _T("Dir entry not found");
   case cdDIR_ENTRY_EXISTS: return _T("Dir entry exists");
   case cdDIR_NOT_EMPTY: return _T("Dir not empty");

      // Property errors
   case cdPROPERTIES_UNAVAILABLE: return _T("Properties unavailable");
   case cdPROPERTIES_MISMATCH: return _T("Properties mismatch");
   case cdPROPERTIES_NOT_LOADED: return _T("Properties not loaded");

      // Function Parameter errors
   case cdINVALID_PARAMETER: return _T("Invalid parameter");
   case cdINVALID_HANDLE: return _T("Invalid handle");
   case cdINVALID_POINTER: return _T("Invalid pointer");
   case cdINVALID_INDEX: return _T("Invalid index");
   case cdINVALID_LENGTH: return _T("Invalid length");
   case cdINVALID_FN_POINTER: return _T("Invalid function pointer");
   case cdINVALID_SORT_FN: return _T("Invalid sort function");

      // Device errors
   case cdDEVICE_NOT_FOUND: return _T("Device not found");
   case cdDEVICE_BUSY: return _T("Device busy");
   case cdDEVICE_INVALID: return _T("Device invalid");
   case cdDEVICE_EMERGENCY: return _T("Device emergency");
   case cdDEVICE_MEMORY_FULL: return _T("Device memory full");
   case cdDEVICE_INTERNAL_ERROR: return _T("Device internal error");
   case cdDEVICE_INVALID_PARAMETER: return _T("Invalid parameter");
   case cdDEVICE_NO_DISK: return _T("Device no disk");
   case cdDEVICE_DISK_ERROR: return _T("Device disk error");
   case cdDEVICE_CF_GATE_CHANGED: return _T("Device CF gate changed");
   case cdDEVICE_DIAL_CHANGED: return _T("Device dial changed");
   case cdDEVICE_NOT_INSTALLED: return _T("Device not installed");
   case cdDEVICE_STAY_AWAKE: return _T("Device stay awake");
   case cdDEVICE_NOT_RELEASED: return _T("Device not released");

      // Stream errors
   case cdSTREAM_IO_ERROR: return _T("Stream IO error");
   case cdSTREAM_NOT_OPEN: return _T("Stream not open");
   case cdSTREAM_ALREADY_OPEN: return _T("Stream already open");
   case cdSTREAM_OPEN_ERROR: return _T("Stream open error");
   case cdSTREAM_CLOSE_ERROR: return _T("Stream close error");
   case cdSTREAM_SEEK_ERROR: return _T("Stream seek error");
   case cdSTREAM_TELL_ERROR: return _T("Stream tell error");
   case cdSTREAM_READ_ERROR: return _T("Stream read error");
   case cdSTREAM_WRITE_ERROR: return _T("Stream write error");
   case cdSTREAM_PERMISSION_ERROR: return _T("Stream permission error");
   case cdSTREAM_COULDNT_BEGIN_THREAD: return _T("Stream couldn't begin thread");
   case cdSTREAM_BAD_OPTIONS: return _T("Stream bad options");
   case cdSTREAM_END_OF_STREAM: return _T("End of stream");

      // Communications errors
   case cdCOMM_PORT_IS_IN_USE: return _T("Comm port in use");
   case cdCOMM_DISCONNECTED: return _T("Comm disconnected");
   case cdCOMM_DEVICE_INCOMPATIBLE: return _T("Comm device incompatible");
   case cdCOMM_BUFFER_FULL: return _T("Comm buffer full");
   case cdCOMM_USB_BUS_ERR: return _T("Comm USB bus error");

      // Lock/Unlock
   case cdUSB_DEVICE_LOCK_ERROR: return _T("USB device lock error");
   case cdUSB_DEVICE_UNLOCK_ERROR: return _T("USB device unlock error");

      // STI/WIA
   case cdSTI_UNKNOWN_ERROR: return _T("STI unknown error");
   case cdSTI_INTERNAL_ERROR: return _T("STI internal error");
   case cdSTI_DEVICE_CREATE_ERROR: return _T("STI device created error");
   case cdSTI_DEVICE_RELEASE_ERROR: return _T("STI device released error");
   case cdDEVICE_NOT_LAUNCHED: return _T("Device not launched");

   case cdENUM_NA: return _T("Enum N/A");
   case cdINVALID_FN_CALL: return _T("Invalid function call");
   case cdHANDLE_NOT_FOUND: return _T("Handle not found");
   case cdINVALID_ID: return _T("Invalid ID");
   case cdWAIT_TIMEOUT_ERROR: return _T("Wait timeout error");

      // PTP
   case prRESPONSE_Undefined: return _T("PTP: Undefined");
   case prRESPONSE_GeneralError: return _T("PTP: General error");
   case cdSESSION_NOT_OPEN: return _T("PTP: Session not open");
   case cdINVALID_TRANSACTIONID: return _T("PTP: Invalid transaction ID");
   case prRESPONSE_OperationNotSupported: return _T("PTP: Operation not supported");
   case prRESPONSE_ParameterNotSupported: return _T("PTP: Parameter not supported");
   case cdINCOMPLETE_TRANSFER: return _T("PTP: Incomplete transfer");
   case cdINVALID_STRAGEID: return _T("PTP: Invalid stage ID");
   case prRESPONSE_InvalidObjectHandle: return _T("PTP: Invalid object handle");
   case cdDEVICEPROP_NOT_SUPPORTED: return _T("PTP: Device property not supported");
   case cdINVALID_OBJECTFORMATCODE: return _T("PTP: Invalid object format code");
   case prRESPONSE_StoreFull: return _T("PTP: Store full");
   case prRESPONSE_ObjectWriteProtected: return _T("PTP: Object write protected");
   case prRESPONSE_StoreRead_Only: return _T("PTP: Store read-only");
   case prRESPONSE_AccessDenied: return _T("PTP: Access denied");
   case prRESPONSE_NoThumbnailPresent: return _T("PTP: No thumbnail present");
   case cdSELF_TEST_FAILED: return _T("PTP: Self test failed");
   case cdPARTIAL_DELETION: return _T("PTP: Partial deletion");
   case prRESPONSE_StoreNotAvailable: return _T("PTP: Store not available");
   case cdSPECIFICATION_BY_FORMAT_UNSUPPORTED: return _T("PTP: Specification by format unsupported");
   case cdNO_VALID_OBJECTINFO: return _T("PTP: No valid object info");
   case cdINVALID_CODE_FORMAT: return _T("PTP: Invalid code format");
   case cdUNKNOWN_VENDER_CODE: return _T("PTP: Unknown vendor code");
   case cdCAPTURE_ALREADY_TERMINATED: return _T("PTP: Capture already terminated");
   case prRESPONSE_DeviceBusy: return _T("PTP: Device busy");
   case cdINVALID_PARENTOBJECT: return _T("PTP: Invalid parent object");
   case cdINVALID_DEVICEPROP_FORMAT: return _T("PTP: Invalid device property format");
   case cdINVALID_DEVICEPROP_VALUE: return _T("PTP: Invalid device property value");
   case cdSESSION_ALREADY_OPEN: return _T("PTP: Session already open");
   case cdTRANSACTION_CANCELLED: return _T("PTP: Transaction cancelled");
   case cdSPECIFICATION_OF_DESTINATION_UNSUPPORTED: return _T("PTP: Specification of destination unsupported");
   case EDS_ERR_NOT_CAMERA_SUPPORT_SDK_VERSION: return _T("Camera not supported by SDK version");

      /// PTP vendor extensions
   case prRESPONSE_Ex_Undefined: return _T("PTP: Undefined");
   case cdUNKNOWN_COMMAND: return _T("PTP: Unknown command");
   case prRESPONSE_Ex_MemAllocFailed: return _T("PTP: Mem alloc failed");
   case prRESPONSE_Ex_InternalError: return _T("PTP: Internal error");
   case prRESPONSE_Ex_DirIOError: return _T("PTP: Dir IO error");
   case cdOPERATION_REFUSED: return _T("PTP: Operation refused");
   case cdLENS_COVER_CLOSE: return _T("PTP: Lens cover closed");
   case prRESPONSE_Ex_NoRelease: return _T("PTP: No release");
   case prRESPONSE_Ex_DeviceIsHot: return _T("PTP: Device is hot");
   case prRESPONSE_Ex_LowBattery: return _T("PTP: Low battery");
   case prRESPONSE_Ex_AlreadyExit: return _T("PTP: Already exited");
   case EDS_ERR_LOW_BATTERY: return _T("PTP: Low battery error");
   case EDS_ERR_OBJECT_NOTREADY: return _T("PTP: Image data set not ready for live view");
   case EDS_ERR_CANNOT_MAKE_OBJECT: return _T("PTP: Cannot make object");
   case EDS_ERR_MEMORYSTATUS_NOTREADY: return _T("PTP: Memory status not ready");

      // Take Picture errors
   case EDS_ERR_TAKE_PICTURE_AF_NG: return _T("Focus failed");
   case EDS_ERR_TAKE_PICTURE_RESERVED: return _T("Reserved");
   case EDS_ERR_TAKE_PICTURE_MIRROR_UP_NG: return _T("Currently configuring mirror up");
   case EDS_ERR_TAKE_PICTURE_SENSOR_CLEANING_NG: return _T("Currently cleaning sensor");
   case EDS_ERR_TAKE_PICTURE_SILENCE_NG: return _T("Currently performing silent operation");
   case EDS_ERR_TAKE_PICTURE_NO_CARD_NG: return _T("Card not installed");
   case EDS_ERR_TAKE_PICTURE_CARD_NG: return _T("Error writing to card");
   case EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG: return _T("Card write protected");
   case EDS_ERR_TAKE_PICTURE_MOVIE_CROP_NG: return _T("Movie crop");
   case EDS_ERR_TAKE_PICTURE_STROBO_CHARGE_NG: return _T("Strobo change");
   case EDS_ERR_TAKE_PICTURE_NO_LENS_NG: return _T("No lens");
   case EDS_ERR_TAKE_PICTURE_SPECIAL_MOVIE_MODE_NG: return _T("Special movie mode");

   default:
      return _T("???");
   }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150419_202229_CT_services extends Migration
{
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
        $this->createTable('service',[
                'id'=>Schema::TYPE_PK,
                'title'=>Schema::TYPE_STRING,
                'processor'=>Schema::TYPE_STRING,
                'url'=>Schema::TYPE_TEXT,
                'last_call'=>Schema::TYPE_DATETIME
            ]);
    }

    public function safeDown()
    {
        $this->dropTable('service');
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Dropbox;

/**
 * Helper functions for security-related things.
 */
class Security
{
    /**
     * A string equality function that compares strings in a way that isn't suceptible to timing
     * attacks.  An attacker can figure out the length of the string, but not the string's value.
     *
     * Use this when comparing two strings where:
     * - one string could be influenced by an attacker
     * - the other string contains data an attacker shouldn't know
     *
     * @param string $a
     * @param string $b
     * @return bool
     */
    static function stringEquals($a, $b)
    {
        // Be strict with arguments.  PHP's liberal types could get us pwned.
        if (func_num_args() !== 2) {
            throw new \InvalidArgumentException("Expecting 2 args, got ".func_num_args().".");
        }
        Checker::argString("a", $a);
        Checker::argString("b", $b);

        if (strlen($a) !== strlen($b)) return false;
        $result = 0;
        for ($i = 0; $i < strlen($a); $i++) {
            $result |= ord($a[$i]) ^ ord($b[$i]);
        }
        return $result === 0;
    }

    /**
     * Returns cryptographically strong secure random bytes (as a PHP string).
     *
     * @param int $numBytes
     *    The number of bytes of random data to return.
     *
     * @return string
     */
    static function getRandomBytes($numBytes)
    {
        Checker::argIntPositive("numBytes", $numBytes);

        // openssl_random_pseudo_bytes had some issues prior to PHP 5.3.4
        if (function_exists('openssl_random_pseudo_bytes')
                && version_compare(PHP_VERSION, '5.3.4') >= 0) {
            $s = openssl_random_pseudo_bytes($numBytes, $isCryptoStrong);
            if ($isCryptoStrong) return $s;
        }

        if (function_exists('mcrypt_create_iv')) {
            return mcrypt_create_iv($numBytes);
        }

        // Hopefully the above two options cover all our users.  But if not, there are
        // other platform-specific options we could add.
        throw new \Exception("no suitable random number source available");
    }
}


text:
#include "stdhdr.h"
#include "simveh.h"
#include "simbase.h"
#include "digi.h"
#include "sensors.h"
#include "object.h"
#include "simbase.h"
#include "airframe.h"
#include "aircrft.h"
#include "Graphics/Include/tmap.h"
/* S.G. NEED TO KNOW WHICH WEAPON WE FIRED */#include "Missile.h"
/* S.G. NEED TO KNOW WHICH WEAPON WE FIRED */#include "vehrwr.h"
/* S.G. 2001-06-29 */#include "CampBase.h"
/* S.G. 2001-06-29 */#include "WingOrder.h"
#include "sms.h" // S.G. 2002-01-02
#include "flight.h" // MN 2002-03-27
#include "visual.h"//Cobra for the eyeball ;)

/*--------------------------*/
/* last ditch maneuver time */
/*--------------------------*/

#define LD_TIME  1.0

#define MISSILE_LETHAL_CONE    45.0F

extern float g_fAIDropStoreLauncherRange;

void DigitalBrain::MissileDefeatCheck(void)
{
    short edata[6];
    int   response;

    //Cobra Moved here before jump out of function code.
    if (targetPtr) //me123 defensive flare
    {
        int looks_scarry = 0;

        //me123 status test. let's drop a flare if we are threatened, even with no missile in the air. better safe then sory
        if (targetData->ataFrom < MISSILE_LETHAL_CONE * DTR and targetData->range < 2.0f * 6000.0f)
        {
            //me123 status test. we are inside 2nm, somebody is pointing at us and they look like they can fire a missile.
            if (targetData->ata < 30.0f * DTR)
            {
                looks_scarry = FALSE;
            }

            else if (targetData->ata > 30.0f * DTR and targetData->ata < 60.0f * DTR and targetData->range > 5000.0f)
            {
                looks_scarry = TRUE;
            }

            else if (targetData->ata > 60.0f * DTR and targetData->ata < 120.0f * DTR and targetData->range > 4000.0f)
            {
                looks_scarry = TRUE;
            }

            else if (targetData->ata > 120.0f * DTR and targetData->range > 3000.0f)
            {
                looks_scarry = TRUE;
            }

            if (looks_scarry == TRUE)
            {
                if (SimLibElapsedTime > self->FlareExpireTime() + 4 * SEC_TO_MSEC)
                {
                    //let's pump a flare if none is in the air.
                    ((AircraftClass*)self)->dropFlareCmd = TRUE;
                }
            }
        }
    }

    // ADDED BY S.G.SINCE THIS ROUTINE IS CALLED OFTEN, WE CAN DEREFERENCE THE LAUNCHED MISSILE POINTER ONCE IT IS DEAD
    // NO POINT WAITING FOR SOMEONE TO SHOOT AT US FOR THIS TO HAPPEN
    if (missileFiredEntity)
    {
        // Has the missile exploded yet?
        if (((SimWeaponClass *)missileFiredEntity)->IsDead())
        {
            VuDeReferenceEntity((SimWeaponClass *)missileFiredEntity);
            missileFiredEntity = NULL;
        }
    }

    // 2000-09-03 ADDED BY S.G. WE NEED TO STOP EVADING IF THE MISSILE IS NO LONGER TARGETING.
    // ALSO, SINCE THE CHECK FOR self->incomingMissile[0] EXISTING IS BEING DONE IN BOTH IF AND ELSE CLAUSE, IT WILL BE MOVED HERE
    if ( not self->incomingMissile[0])
        return;

    if (self->incomingMissile[0]->IsDead())
    {
        self->SetIncomingMissile(NULL);
        return;
    }

    // RV - Biker - Allow to shoot them back
    if (((MissileClass *)self->incomingMissile[0])->parent and not ((MissileClass *)self->incomingMissile[0])->parent->OnGround())
        missileShotTimer = 0;

    // 2000-09-05 this will make the range not target base but from us to the missile
    float dx, dy, dz, missileRange;

    dx = self->incomingMissile[0]->XPos() - self->XPos();
    dy = self->incomingMissile[0]->YPos() - self->YPos();
    dz = self->incomingMissile[0]->ZPos() - self->ZPos();
    missileRange = (float)sqrt(dx * dx + dy * dy + dz * dz);

    // If the missile's range is more than the previous missile range (that we kept), the missile has passed by us.
    if (missileRange > self->incomingMissileRange and self->incomingMissileRange)
    {
        if (self->incomingMissileEvadeTimer + (6 - SkillLevel()) * SEC_TO_MSEC < SimLibElapsedTime)
        {
            //We have spoofed the missile, now forget about it
            // Cobra - Destroy the missile
            if (missileFiredEntity)
            {
                ((SimWeaponClass *)missileFiredEntity)->SetFlag(MissileClass::SensorLostLock);
                ((SimWeaponClass *)missileFiredEntity)->SetFlag(MissileClass::ClosestApprch);
                ((SimWeaponClass *)missileFiredEntity)->SetExploding(TRUE);
                ((SimWeaponClass *)missileFiredEntity)->SetDead(TRUE);
            }

            if (self->incomingMissile[0])
            {
                self->incomingMissile[0]->SetFlag(MissileClass::SensorLostLock);
                self->incomingMissile[0]->SetFlag(MissileClass::ClosestApprch);
                self->incomingMissile[0]->SetExploding(TRUE);
                self->incomingMissile[0]->SetDead(TRUE);
            }
            else if (self->incomingMissile[1])
            {
                self->incomingMissile[1]->SetFlag(MissileClass::SensorLostLock);
                self->incomingMissile[1]->SetFlag(MissileClass::ClosestApprch);
                self->incomingMissile[1]->SetExploding(TRUE);
                self->incomingMissile[1]->SetDead(TRUE);
            }

            self->SetIncomingMissile(NULL);
            self->incomingMissileRange = 500 * NM_TO_FT; //initialize
            return;
        }
    }
    else
        self->incomingMissileEvadeTimer = SimLibElapsedTime;

    // Keep this as the old missileRange
    self->incomingMissileRange = missileRange;
    // END OF ADDED SECTION

    /*-------*/
    /* entry */
    /*-------*/
    if (curMode not_eq MissileDefeatMode)
    {

        // 2000-09-01 ADDED BY S.G. SO AI ARE NOT AWARE OF ARH MISSILE STILL COMMAND GUIDED (NOT ACTIVE) OR SARH OR ACTIVE ARH UNLESS IT'S GETTING CLOSE OR HAS A RWR, SKILL RELATED
        VehRwrClass::DetectListElement *rwrElement;
        SensorClass *rwrSensor;
        /*
         // Must have a RWR or visual tally on the missile
         if ( not ((
         ((MissileClass *)self->incomingMissile[0])->GetSeekerType() not_eq SensorClass::IRST and // Don't test for RWR if it's a IR missile...
         (rwrSensor = FindSensor(self, SensorClass::RWR)) and // The plane has an RWR (without it, why bother)
         (
         ( (MissileClass *)self->incomingMissile[0])->GetSeekerType() == SensorClass::RadarHoming or // The real missile sensor is a SARH
         (((MissileClass *)self->incomingMissile[0])->sensorArray and ((MissileClass *)self->incomingMissile[0])->sensorArray[0]->Type() == SensorClass::Radar) or // The current sensor is a ARH (if it's a local entity)
         ( not ((MissileClass *)self->incomingMissile[0])->sensorArray and (rwrElement = ((VehRwrClass *)rwrSensor)->IsTracked(self->incomingMissile[0])) and rwrElement->missileLaunch) // There is no sensor (non local enity) but the missile is on RWR with a launch
            )) or // Don't forget we take the REVERSE of the test if ( not (...
             missileRange < ((float)SkillLevel() + 1.5f) * NM_TO_FT)) // Or the missile has come to visual range
         return;*/

        //Cobra Removed above so I can sort through this mess.  I want to know exactly how the AI
        //Is "seeing" the missile

        //Cobra Test this Radar Detect stuff
        if (((MissileClass *)self->incomingMissile[0])->GetSeekerType() not_eq SensorClass::IRST)
        {
            if (rwrSensor = FindSensor(self, SensorClass::RWR))
            {
                if (((MissileClass *)self->incomingMissile[0])->GetSeekerType() == SensorClass::RadarHoming)
                {
                    int testme = 1;
                }

                if (((MissileClass *)self->incomingMissile[0])->sensorArray and ((MissileClass *)self->incomingMissile[0])->sensorArray[0]->Type() == SensorClass::Radar)
                {
                    int testme = 1;
                }

                if (( not ((MissileClass *)self->incomingMissile[0])->sensorArray) and (rwrElement = ((VehRwrClass *)rwrSensor)->IsTracked(self->incomingMissile[0])) and rwrElement->missileLaunch)
                {
                    int testme = 1;
                }
            }
        }

        //end

        if (((MissileClass *)self->incomingMissile[0])->GetSeekerType() not_eq SensorClass::IRST
           and (rwrSensor = FindSensor(self, SensorClass::RWR))
            and
            (((MissileClass *)self->incomingMissile[0])->GetSeekerType() == SensorClass::RadarHoming
             or (((MissileClass *)self->incomingMissile[0])->sensorArray and ((MissileClass *)self->incomingMissile[0])->sensorArray[0]->Type() == SensorClass::Radar)
             or ( not ((MissileClass *)self->incomingMissile[0])->sensorArray and (rwrElement = ((VehRwrClass *)rwrSensor)->IsTracked(self->incomingMissile[0])) and rwrElement->missileLaunch)))
        {
            int donothing = 1;
        }
        else if (missileRange < (10.0f * NM_TO_FT) and SimLibElapsedTime > visDetectTimer)
        {
            int donothing1 = 1;
            VisualClass *eyeball = (VisualClass*)FindSensor((SimMoverClass *)self, SensorClass::Visual);
            float az, el, ata, ataFrom, droll;
            int canSee = 0;

            if (eyeball)
            {
                CalcRelValues((SimBaseClass *)self, (MissileClass*)self->incomingMissile[0], &az, &el, &ata, &ataFrom, &droll);
                canSee = eyeball->CanSeeObject(az, el);

                if ( not canSee)
                {
                    return;
                }
                else
                {
                    if (missileRange > (8.0f * NM_TO_FT) and SimLibElapsedTime > visDetectTimer
                       and rand() % 100 < 3)
                    {
                        int testme = 0;
                    }
                    else if (missileRange > (6.0f * NM_TO_FT) and missileRange < (8.0f * NM_TO_FT)
                            and SimLibElapsedTime > visDetectTimer and rand() % 100 < 10)
                    {
                        int testme = 0;
                    }
                    else if (missileRange > (4.0f * NM_TO_FT) and missileRange < (6.0f * NM_TO_FT)
                            and SimLibElapsedTime > visDetectTimer and rand() % 100 < 25)
                    {
                        int testme = 0;
                    }
                    else if (missileRange > (2.0f * NM_TO_FT) and missileRange < (4.0f * NM_TO_FT)
                            and SimLibElapsedTime > visDetectTimer and rand() % 100 < 40)
                    {
                        int testme = 0;
                    }
                    else if (missileRange > (0.5f * NM_TO_FT) and missileRange < (2.0f * NM_TO_FT)
                            and SimLibElapsedTime > visDetectTimer and rand() % 100 < 65)
                    {
                        int testme = 0;
                    }
                    else
                    {
                        visDetectTimer = SimLibElapsedTime + 5000;
                        return;
                    }
                }
            }
        }
        else
        {
            return;
        }

        // If we get here, either we acquired the missile visually, or we have an RWR and the missile is either an SARH or an actively guiding ARH
        // ADDED BY S.G. SO DIGI PILOT SHOOTING SARH WONT GET SCARED RIGHT AWAY
        if (missileFiredEntity)
        {
            // No need to check if its dead, we did that above already...
            // If we are providing radar guidance to hit (SARH), see if we should wait before defeating the incoming missile
            if (((SimWeaponClass *)missileFiredEntity)->sensorArray and ((SimWeaponClass *)missileFiredEntity)->sensorArray[0]->Type() == SensorClass::RadarHoming)
            {
                // Check if we are in our 'count down'. First bit will be 1 if so
                if (missileFiredTime bitand 0x1)
                {
                    // Is our count down over? If not, that's it
                    if (missileFiredTime > SimLibElapsedTime)
                        return;
                    // So it is over, start evading
                    else
                    {
                        VuDeReferenceEntity((SimWeaponClass *)missileFiredEntity);
                        missileFiredEntity = NULL;
                    }
                }
                // Ok we're just entering here for the first time
                else
                {
                    //  So check how long ago the our missile was fired
                    if (missileFiredTime  + SEC_TO_MSEC * (SkillLevel() + 1) <= SimLibElapsedTime)
                    {
                        // It was launched not long ago (skill dependant), Evade
                        VuDeReferenceEntity((SimWeaponClass *)missileFiredEntity);
                        missileFiredEntity = NULL;
                    }
                    // It's in the air long enough, give us a count down timer, skill based. Also set the first bit to say we're in count down
                    else
                    {
                        missileFiredTime = (SimLibElapsedTime + rand() % (((SimLibElapsedTime - missileFiredTime) - SEC_TO_MSEC * SkillLevel()) + 1) + SEC_TO_MSEC * (SkillLevel() + 1)) bitor 0x1;  // 2002-01-28 MODIFIED BY S.G. Added '+ 1' in the '%' section to prevent a rare divide by 0 CTD.
                        // Don't go in MissileDefeatMode.
                        return;
                    }
                }
            }
            // It's not even (or anymore) a RadarHoming missile, so why should we bother?
            else
            {
                VuDeReferenceEntity((SimWeaponClass *)missileFiredEntity);
                missileFiredEntity = NULL;
            }
        }

        // END OF ADDED SECTION
        AddMode(MissileDefeatMode);
        missileDefeatTtgo = -1.0F;

        // RV - Biker - This does not work (try something basic for now)
        //if (((MissileClass *)self->incomingMissile[0])->parent and ( not self->Sms->DidEmergencyJettison()))
        //{
        // float launcherRange = 9999999.9F;
        // dx = ((MissileClass *)self->incomingMissile[0])->parent->XPos() - self->XPos();
        // dy = ((MissileClass *)self->incomingMissile[0])->parent->YPos() - self->YPos();
        // dz = ((MissileClass *)self->incomingMissile[0])->parent->ZPos() - self->ZPos();
        // launcherRange = SqrtF( dx*dx + dy*dy + dz*dz );
        //
        // // 2002-01-01 ADDED BY S.G. From GunJinks.cpp, drop stores under some conditions...
        // //Cobra we modified this - me too
        // if (self->CombatClass() not_eq MnvrClassBomber
        // and (((launcherRange < g_fAIDropStoreLauncherRange * NM_TO_FT) and (launcherRange > 0.0f))
        // and (((MissileClass *)self->incomingMissile[0])->parent
        // and ( not ((MissileClass *)self->incomingMissile[0])->parent->OnGround())
        // and (((MissileClass *)self->incomingMissile[0])->GetSeekerType() not_eq SensorClass::IRST)))
        // )
        // {
        // self->Sms->AGJettison();
        // SelectGroundWeapon();
        // }
        // END OF ADDED SECTION
        //}
        // Have wingman say something useful when he is engaged
        edata[0] = isWing;
        response = rcENGDEFENSIVEC;
        AiMakeRadioResponse(self, response, edata);

        // 2000-09-03 COMMENTED OUT BY S.G. SINCE THEIR BODY WERE COMMENTED OUT AS WELL
        //       }
        //    }
    }

    /*------*/
    /* exit */
    /*------*/
    if (curMode == MissileDefeatMode)
    {
        AddMode(MissileDefeatMode);
    }
}

void DigitalBrain::MissileDefeat()
{
    /*-------------------*/
    /* Shouldn't be here */
    /*-------------------*/
    if (self->incomingMissile[0])
    {
        if (self->incomingMissile[0]->IsDead())
        {
            self->SetIncomingMissile(NULL);
            return;
        }
    }
    else
    {
        return;
    }

    // RV - Biker - Allow to shoot them back
    if (((MissileClass *)self->incomingMissile[0])->parent and not ((MissileClass *)self->incomingMissile[0])->parent->OnGround())
        missileShotTimer = 0;

    // RV - Biker - Maybe check some extra conditions later
    if ( not self->Sms->DidEmergencyJettison() and self->incomingMissileRange < 10.0f * NM_TO_FT)
    {
        if (self->CombatClass() not_eq MnvrClassBomber)
        {
            if (rand() % 100 < SkillLevel() * 25)
            {
                self->Sms->EmergencyJettison();
                SelectGroundWeapon();
            }
            else if (rand() bitand 1)
            {
                self->Sms->AGJettison();
                SelectGroundWeapon();
            }
        }
    }

    // 2001-06-29 ADDED BY S.G. I WANT LEAD TO ASK WINGS TO ATTACK IF HE IS ENGAGED OTHERWISE HE WON'T...
    if (/* not isWing and */ ((MissileClass *)self->incomingMissile[0])->parent and ((MissileClass *)self->incomingMissile[0])->parent->OnGround())
    {
        // Have we given the attack yet? Oh yeah, do we have some AG weapons and do we have someone to direct?
        if (sentWingAGAttack not_eq AG_ORDER_ATTACK and IsSetATC(HasAGWeapon) and self->GetCampaignObject()->NumberOfComponents() > 1)
        {
            VU_ID targetId = FalconNullId;

            // Only SEADS on target of opportunity changes to the target shooting at me...
            // Cobra - changed to NOT ( not ) IsNotMainTargetSEAD() (double negatives :^( )
            if ( not IsNotMainTargetSEAD())
            {
                if (((MissileClass *)self->incomingMissile[0])->parent->IsSim())
                    targetId = ((SimBaseClass *)((MissileClass *)self->incomingMissile[0])->parent.get())->GetCampaignObject()->Id();
                else
                    targetId = ((MissileClass *)self->incomingMissile[0])->parent->Id();
            }
            // Otherwise, tell them to engage our current target if they can (and we have one) while we ditch the missile
            else if (groundTargetPtr)
            {
                if (groundTargetPtr->BaseData()->IsSim())
                    targetId = ((SimBaseClass *)groundTargetPtr->BaseData())->GetCampaignObject()->Id();
                else
                    targetId = groundTargetPtr->BaseData()->Id();
            }

            if (targetId not_eq FalconNullId)
            {
                SetGroundTargetPtr(NULL); // First clean our ground target so we can release the radar if we were targeting it
                gndTargetHistory[0] = NULL; // Then remove our hold on the target so it can be retargeted

                AiSendCommand(self, FalconWingmanMsg::WMAssignTarget, AiFlight, targetId);
                AiSendCommand(self, FalconWingmanMsg::WMShooterMode, AiFlight, targetId);
                sentWingAGAttack = AG_ORDER_ATTACK;
                // 2002-01-20 ADDED BY S.G. Added the new nextAttackCommandToSend variable check to force the lead to reissue an attack in case wings went back into formation (can we say HACK?)
                nextAttackCommandToSend = SimLibElapsedTime + 60 * SEC_TO_MSEC;
            }
        }
    }

    // END OF ADDED SECTION

    /*------------------------------*/
    /* new missile, initialize data */
    /*------------------------------*/
    if (missileDefeatTtgo < 0.0F)
    {
        missileDefeatTtgo    = 1000.0F;
        missileFindDragPt    = TRUE;
        missileFinishedBeam  = FALSE;
        missileShouldDrag    = FALSE;
    }

    // calc approx threat time
    float dx, dy, dz, range, threatTime;

    dx = self->incomingMissile[0]->XPos() - self->XPos();
    dy = self->incomingMissile[0]->YPos() - self->YPos();
    dz = self->incomingMissile[0]->ZPos() - self->ZPos();

    range = (float)sqrt(dx * dx + dy * dy + dz * dz);
    threatTime = range / AVE_AIM9L_VEL;

    /*--------------------------------------------*/
    /* Use threat time for time to go if known.   */
    /* Otherwise run down the clock in real time. */
    /*--------------------------------------------*/
    if (threatTime < MAX_THREAT_TIME)
    {
        missileDefeatTtgo = threatTime;
    }
    else
        missileDefeatTtgo -= SimLibMinorFrameTime;

    if (missileDefeatTtgo < 0.0)
        missileDefeatTtgo = 0.0F;

    /*--------------------*/
    /* maneuver selection */
    /*--------------------*/
    if (missileDefeatTtgo > LD_TIME)
    {
        ((AircraftClass*)self)->DropProgramed();

        /*if (((MissileClass *)self->incomingMissile[0])->targetPtr)
         if (((MissileClass *)self->incomingMissile[0])->targetPtr->localData->range > ((float)(6.0f - SkillLevel()) * NM_TO_FT) and
          ((MissileClass *)self->incomingMissile[0])->targetPtr->localData->range < ((float)(19.0f - SkillLevel()) * NM_TO_FT))
         missileShouldDrag = TRUE;

        if ( not missileShouldDrag)
         MissileBeamManeuver();
        else
         MissileDragManeuver();*/

        //Cobra
        float closure = self->GetKias() - self->incomingMissile[0]->GetKias();

        if (((MissileClass *)self->incomingMissile[0])->targetPtr)
        {
            if (((MissileClass *)self->incomingMissile[0])->targetPtr->localData->range > 2.0f * NM_TO_FT
                or closure < 400.0f)
            {
                MissileDragManeuver();
            }
            else
            {
                MissileBeamManeuver();
            }
        }

        // 2000-09-08 ADDED BY S.G. SO WE DON'T GO IN AFTER BURNER WHEN AN IR MISSILE IS LAUNCHED AT US UNTIL WE TRY TO DITCH IT IF WE ARE VETERANS OR ACES
        // WE DO THIS AFTER THE MANEUVERS SO WE OVERIDE THE THROTTLE SETTING BY THESE MANEUVERS
        if (((MissileClass *)self->incomingMissile[0])->GetSeekerType() == SensorClass::IRST and SkillLevel() > 2)
            //     throtl = min (throtl, 0.0f);//me123 from 1.0 to 0 (we wanna go idle // S.G. RP4 COMPABILITY
            throtl = min(throtl, 0.99f);

        // END OF ADDED SECTION

    }
    else
        MissileLastDitch(dx, dy, dz);

}

int DigitalBrain::MissileBeamManeuver()
{
    int retval = FALSE;
    float nh1, nh2, az;
    float at;
    mlTrig trig;

    /*-----------------*/
    /* missile heading */
    /*-----------------*/
    az = self->incomingMissile[0]->Yaw();

    /*--------------------*/
    /* pick a new heading */
    /*--------------------*/
    nh1 = az + PI * 0.5F;

    if (nh1 > PI)
        nh1 -= PI;

    nh2 = az - PI * 0.5F;

    if (nh2 < -PI)
        nh2 += PI;

    if (fabs(self->Yaw() - nh1) < fabs(self->Yaw() - nh2))
        az = nh1;
    else
        az = nh2;

    /*------------------------------------*/
    /* find a stationary point 10 NM away */
    /* in the nh? direction.              */
    /*------------------------------------*/
    mlSinCos(&trig, az);
    // Cobra - Use local max elevation to try and keep AI from lawndarting
    float tz = TheMap.GetMEA(((AircraftClass*) self)->XPos(), ((AircraftClass*) self)->YPos());

    //Cobra
    if (self->ZPos() < -20000.0f)
    {
        tz = self->ZPos() - 10000.0f - trackZ;
    }
    else
    {
        tz += -2000.0f;
    }

    SetTrackPoint(
        self->XPos() + 0.5F * NM_TO_FT * trig.cos,
        self->YPos() + 0.5F * NM_TO_FT * trig.sin,
        tz
    );

    /*----------------------------------------------------------*/
    /* use AUTO_TRACK to steer toward point, override gs limits */
    /*----------------------------------------------------------*/
    at = AutoTrack(maxGs);
    //MachHold(2*cornerSpeed,self->GetKias(), TRUE);//Cobra We want corner speed on beams
    MachHold(cornerSpeed, self->GetKias(), TRUE);

    if (at < 5.0F)
        retval = TRUE;

    return (retval);
}

void DigitalBrain::MissileDragManeuver(void)
{
    float az;
    mlTrig trig;
    az = self->incomingMissile[0]->Yaw();//Cobra

    if (missileFindDragPt)
    {
        /*--------------------*/
        /* pick a new heading */
        /*--------------------*/
        // az = self->incomingMissile[0]->Yaw();

        /*-------------------------------------------*/
        /* find a stationary point 20 NM away in the */
        /* correct direction to chase.               */
        /*-------------------------------------------*/
        mlSinCos(&trig, az);

        // Cobra - Use local max elevation to try and keep AI from lawndarting
        float tz = TheMap.GetMEA(((AircraftClass*) self)->XPos(), ((AircraftClass*) self)->YPos());

        //Cobra
        if (self->ZPos() < -20000.0f)
        {
            tz = self->ZPos() - 10000.0f - trackZ;
        }
        else
        {
            tz += -2000.0f;
        }

        SetTrackPoint(self->XPos() + 20.0F * NM_TO_FT * trig.cos, self->YPos() + 20.0F * NM_TO_FT * trig.sin, tz);
        missileFindDragPt = FALSE;
    }

    /*----------------------------------------------------------*/
    /* use AUTO_TRACK to steer toward point, override gs limits */
    /*----------------------------------------------------------*/
    AutoTrack(maxGs);
    MachHold(3 * cornerSpeed, self->GetKias(), TRUE);
}

void DigitalBrain::MissileLastDitch(float xft, float yft, float zft)
{
    //TJL 11/14/03. The roll code was causing the AI to never pull. It's been removed and now the AI pull to evade.
    //float tDroll,roll_offset,newroll,eroll;

    /*--------------*/
    /* target droll */
    /*--------------*/
    /*
    float rx = self->dmx[0][0]*xft + self->dmx[0][1]*yft + self->dmx[0][2]*zft;
    float ry = self->dmx[1][0]*xft + self->dmx[1][1]*yft + self->dmx[1][2]*zft;
    float rz = self->dmx[2][0]*xft + self->dmx[2][1]*yft + self->dmx[2][2]*zft;
    float droll =  (float)atan2 (ry,-rz);

    tDroll = droll*RTD;

    */
    /*------------------------------------------*/
    /* offset required to put wings on attacker */
    /*------------------------------------------*/

    /*
    if (tDroll >= 0.0)
     roll_offset = tDroll - 90.0F;
    else
     roll_offset = tDroll + 90.0F;
    */
    /*------------------------*/
    /* generate new phi angle */
    /*------------------------*/
    //   newroll = self->Roll()*RTD + roll_offset;

    /*------------------------------------------*/
    /* roll the aircraft the shortest direction */
    /*------------------------------------------*/
    /*
    if (newroll > 180.0)
     newroll -= 360.0F;
    else if (newroll < -180.0)
     newroll += 360.0F;

    eroll = newroll - self->Roll();

    if (eroll > 180.0)
     eroll -= 360.0F;
    else if (eroll < -180.0)
     eroll += 360.0F;
    */
    /*------------------------------*/
    /* generate roll stick commands */
    /*------------------------------*/
    // SetRstick( eroll );
    //   SetMaxRoll ((self->Roll() + eroll) * RTD);

    /*-----------*/
    /* max pitch */
    /*-----------*/
    SetPstick(maxGs, maxGs, AirframeClass::GCommand);

    /*----------------------*/
    /* center rudder pedals */
    /*----------------------*/
    SetYpedal(0.0F);

    /*-------------------*/
    /* hold corner speed */
    /*-------------------*/
    MachHold(cornerSpeed, self->GetKias(), TRUE);

    /*------*/
    /* Pray */
    /*------*/

    if (missileDefeatTtgo > LD_TIME * 0.25F and missileDefeatTtgo < LD_TIME * 0.8F and
        ((AircraftClass*)self)->HasPilot())
    {
        if (SimLibElapsedTime > self->ChaffExpireTime())
        {
            ((AircraftClass*)self)->dropChaffCmd = TRUE;
        }

        if (SimLibElapsedTime > self->FlareExpireTime())
        {
            ((AircraftClass*)self)->dropFlareCmd = TRUE;
        }
    }
}

int DigitalBrain::MissileEvade(void)
{
    return TRUE;
}


text:
package examples

import (
	"fmt"
	. "github.com/0x19/goesl"
	"os"
	"runtime"
	"strings"
)

var welcomeFile = "%s/media/welcome.wav"

func main() {

	defer func() {
		if r := recover(); r != nil {
			Error("Recovered in f", r)
		}
	}()

	// Boost it as much as it can go ...
	runtime.GOMAXPROCS(runtime.NumCPU())

	wd, err := os.Getwd()

	if err != nil {
		Error("Error while attempt to get WD: %s", wd)
		os.Exit(1)
	}

	welcomeFile = fmt.Sprintf(welcomeFile, wd)

	if s, err := NewOutboundServer(":8084"); err != nil {
		Error("Got error while starting Freeswitch outbound server: %s", err)
	} else {
		go handle(s)
		s.Start()
	}

}

// handle - Running under goroutine here to explain how to handle playback ( play to the caller )
func handle(s *OutboundServer) {

	for {

		select {

		case conn := <-s.Conns:
			Notice("New incomming connection: %v", conn)

			if err := conn.Connect(); err != nil {
				Error("Got error while accepting connection: %s", err)
				break
			}

			answer, err := conn.ExecuteAnswer("", false)

			if err != nil {
				Error("Got error while executing answer: %s", err)
				break
			}

			Debug("Answer Message: %s", answer)
			Debug("Caller UUID: %s", answer.GetHeader("Caller-Unique-Id"))

			cUUID := answer.GetCallUUID()

			if sm, err := conn.Execute("playback", welcomeFile, true); err != nil {
				Error("Got error while executing playback: %s", err)
				break
			} else {
				Debug("Playback Message: %s", sm)
			}

			if hm, err := conn.ExecuteHangup(cUUID, "", false); err != nil {
				Error("Got error while executing hangup: %s", err)
				break
			} else {
				Debug("Hangup Message: %s", hm)
			}

			go func() {
				for {
					msg, err := conn.ReadMessage()

					if err != nil {

						// If it contains EOF, we really dont care...
						if !strings.Contains(err.Error(), "EOF") {
							Error("Error while reading Freeswitch message: %s", err)
						}
						break
					}

					Debug("%s", msg)
				}
			}()

		default:
			// YabbaDabbaDooooo!
			//Flintstones. Meet the Flintstones. They're the modern stone age family. From the town of Bedrock,
			// They're a page right out of history. La la,lalalalala la :D
		}
	}

}


text:
package com.heliosapm.webrpc.jsonservice;

/**
 *
Title: ResponseType

 *
Description: Enumerates the JSON response types

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
org.helios.tsdb.plugins.remoting.json.ResponseType

 */

public enum ResponseType {
	/** Response flag for an error message */
	ERR("err"),  // undefined continuation
	/** Response flag for a request response */
	RESP("resp"), // one time response
	/** Response flag for a request response with a finite number of responses */
	MRESP("mresp"), // n-times response ending with a final event
	/** Response flag for a request response with a finite number of responses */
	XMRESP("xmresp"), // final event on an MRESP sequence
	/** Response flag for a subscription event delivery */
	SUB("sub"),  // infinite response
	/** Response flag for a subscription start confirm */
	SUB_STARTED("subst"),  // starts a sequence of infinite responses
	/** Response flag for a subscription stop notification */
	SUB_STOPPED("xmsub"), // ends a sequence of infinite responses
	/** Response flag for a growl */
	GROWL("growl");  // infinite response, no starter, no ender

	private ResponseType(final String code) {
		this.code = code;
	}

	/** The code for the response type */
	public final String code;

}


text:
layout: default
title: 404
---

Oh, snap! Looks like this page doesn't exist.


text:
require 'spec_helper'

class Dummy
  include CategoryRouter
end

describe CategoryRouter do
  subject(:dummy) { Dummy.new }

  describe ".find_category!" do
    it "raises if user isn't in the right org" do
      params  = { category: "america", organization: "sharks" }
      user    = instance_double("User", admin?: false, organization: "jets")

      expect { subject.find_category!(params, user) }.to raise_error(WrongOrganizationError)
    end

    it "doesn't care if the category doesn't belong to an organization" do
      params  = { category: "america" }
      user    = instance_double("User", admin?: false)
      klass   = spy("Category", find_by!: "fie!")

      expect { subject.find_category!(params, user, klass) }.not_to raise_error
    end

    it "allows admins through regardless" do
      params  = { category: "america", organization: "sharks" }
      user    = double("User", admin?: true, organization: "jets")
      klass   = double("Category", organization: "sharks", find_by!: "fie!")

      expect { subject.find_category!(params, user, klass) }.not_to raise_error
    end

    it "looks for the category when bidden" do
      params  = { category: "america", organization: "sharks" }
      user    = instance_double("User", admin?: false, organization: "sharks")
      klass   = spy("Category")

      subject.find_category!(params, user, klass)

      expected_vals = hash_including(handle: "america", organization: "sharks")
      expect(klass).to have_received(:find_by!).with(expected_vals)
    end
  end

  describe "#path_for" do
    subject(:router) { CategoryRouter }

    it "uses helpers" do
      helpers = spy("UrlHelpers")
      cat     = double("Category", organization: "org", handle: "handle")

      subject.path_for(cat, helpers)

      expected_vals = hash_including(category: "handle", organization: "org")
      expect(helpers).to have_received(:category_path).with(expected_vals)
    end
  end
end


text:
from inliner import utils
import ast

class InlineMethodLocator(ast.NodeVisitor):
    def __init__(self):
        self.functions = {}

    def visit_FunctionDef(self, node):
        if any(filter(lambda d: d.id == "inline", node.decorator_list)):
            func_name = utils.getFunctionName(node)
            self.functions[func_name] = node


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Knuth-Morris-Pratt Search</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="The Boost Algorithm Library">
<link rel="up" href="../../algorithm/Searching.html" title="Searching Algorithms">
<link rel="prev" href="BoyerMooreHorspool.html" title="Boyer-Moore-Horspool Search">
<link rel="next" href="../../algorithm/CXX11.html" title="C++11 Algorithms">

Home
Libraries
People
FAQ
More

Knuth-Morris-Pratt
      Search

        Overview

        The header file 'knuth_morris_pratt.hpp' contains an implementation of the
        Knuth-Morris-Pratt algorithm for searching sequences of values.

        The basic premise of the Knuth-Morris-Pratt algorithm is that when a mismatch
        occurs, there is information in the pattern being searched for that can be
        used to determine where the next match could begin, enabling the skipping
        of some elements of the corpus that have already been examined.

        It does this by building a table from the pattern being searched for, with
        one entry for each element in the pattern.

        The algorithm was conceived in 1974 by Donald Knuth and Vaughan Pratt, and
        independently by James H. Morris. The three published it jointly in 1977
        in the SIAM Journal on Computing http://citeseer.ist.psu.edu/context/23820/0

        However, the Knuth-Morris-Pratt algorithm cannot be used with comparison
        predicates like std::search.

        Interface

        Nomenclature: I refer to the sequence being searched for as the "pattern",
        and the sequence being searched in as the "corpus".

        For flexibility, the Knuth-Morris-Pratt algorithm has two interfaces; an
        object-based interface and a procedural one. The object-based interface builds
        the table in the constructor, and uses operator () to perform the search.
        The procedural interface builds the table and does the search all in one
        step. If you are going to be searching for the same pattern in multiple corpora,
        then you should use the object interface, and only build the tables once.

        Here is the object interface:

template <typename patIter>
class knuth_morris_pratt {
public:
    knuth_morris_pratt ( patIter first, patIter last );
    ~knuth_morris_pratt ();

    template <typename corpusIter>
    corpusIter operator () ( corpusIter corpus_first, corpusIter corpus_last );
    };

        and here is the corresponding procedural interface:

template <typename patIter, typename corpusIter>
corpusIter knuth_morris_pratt_search (
        corpusIter corpus_first, corpusIter corpus_last,
        patIter pat_first, patIter pat_last );

        Each of the functions is passed two pairs of iterators. The first two define
        the corpus and the second two define the pattern. Note that the two pairs
        need not be of the same type, but they do need to "point" at the
        same type. In other words, patIter::value_type
        and curpusIter::value_type need to be the same type.

        The return value of the function is an iterator pointing to the start of
        the pattern in the corpus. If the pattern is not found, it returns the end
        of the corpus (corpus_last).

        Performance

        The execution time of the Knuth-Morris-Pratt algorithm is linear in the size
        of the string being searched. Generally the algorithm gets faster as the
        pattern being searched for becomes longer. Its efficiency derives from the
        fact that with each unsuccessful attempt to find a match between the search
        string and the text it is searching, it uses the information gained from
        that attempt to rule out as many positions of the text as possible where
        the string cannot match.

        Memory
        Use

        The algorithm an that contains one entry for each element the pattern, plus
        one extra. So, when searching for a 1026 byte string, the table will have
        1027 entries.

        Complexity

        The worst-case performance is O(2n), where n
        is the length of the corpus. The average time is O(n).
        The best case performance is sub-linear.

        Exception
        Safety

        Both the object-oriented and procedural versions of the Knuth-Morris-Pratt
        algorithm take their parameters by value and do not use any information other
        than what is passed in. Therefore, both interfaces provide the strong exception
        guarantee.

        Notes

            When using the object-based interface, the pattern must remain unchanged
            for during the searches; i.e, from the time the object is constructed
            until the final call to operator () returns.

            The Knuth-Morris-Pratt algorithm requires random-access iterators for
            both the pattern and the corpus. It should be possible to write this
            to use bidirectional iterators (or possibly even forward ones), but this
            implementation does not do that.

Copyright © 2010-2012 Marshall Clow

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Copyright (C) 2016 INFRAWARE, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/*
 * NavigatorDeviceGallery.h
 *
 *  Created on: 2016. 01. 21.
 *      Author: Jeseon Park
 */

#ifndef NavigatorDeviceGallery_h
#define NavigatorDeviceGallery_h

#include "platform/Supplementable.h"
#include "platform/heap/Handle.h"

namespace blink {

class Navigator;
class DeviceGallery;

class NavigatorDeviceGallery final
    : public GarbageCollected<NavigatorDeviceGallery>,
      public HeapSupplement<Navigator> {
    USING_GARBAGE_COLLECTED_MIXIN(NavigatorDeviceGallery);
public:
    static NavigatorDeviceGallery& from(Navigator&);

    static DeviceGallery* devicegallery(Navigator& navigator);
    DeviceGallery* devicegallery();

    DECLARE_TRACE();

private:
    explicit NavigatorDeviceGallery(Navigator&);
    static const char* supplementName();
    Member<DeviceGallery> mDeviceGallery;
};

}

#endif  // NavigatorDeviceGallery_h


text:
package fr.webnicol.mondoapp;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                String uri = "https://auth.getmondo.co.uk/?client_id=oauthclient_000096sfV33HOBgmnDC92H&redirect_uri=http://webnicol.fr:81/oauth/callback&response_type=code&state=toto";
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(browserIntent);
            }
        });

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click

                Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
                startActivity(homeIntent);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
using System.Windows.Input;
using Ais.Internal.Dcm.ModernUIV2.Common;
using Ais.Internal.Dcm.ModernUIV2.ViewModels;
using FirstFloor.ModernUI.Windows;
using FirstFloor.ModernUI.Windows.Navigation;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using NLog;
using FirstFloor.ModernUI.Windows.Controls;

namespace Ais.Internal.Dcm.ModernUIV2.Tabs
{
    /// <summary>
    /// Interaction logic for AssetFiles.xaml
    /// </summary>
    public partial class AssetFiles : UserControl, IContent, INotifyPropertyChanged, IDisposable
    {
        #region Constructor

        public AssetFiles()
        {
            InitializeComponent();
            client = App.GetHttpClient();
            MediaContextHelper.FileUploader.OnUploadStatusChange += uploadHelper_OnUploadStatusChange;

        }

        #endregion

        #region Properties

       // private UploadHelper uploadHelper = new UploadHelper();
        private string selectedAssetId { get; set; }
        private string filePath = string.Empty;
        private HttpClient client = new HttpClient();
        private bool CanNavigate { get; set; }
        private Logger logger = LogManager.GetCurrentClassLogger();
        private bool IsFileLocal { get; set; }
        public string AssetName { get; set; }

        private AssetInfo selectedAsset;

        public AssetInfo SelectedAsset
        {
            get { return selectedAsset; }
            set
            {
                selectedAsset = value;
                OnPropertyChanged("SelectedAsset");
            }
        }

        private AssetFileInfo selectedAssetFile;

        public AssetFileInfo SelectedAssetFile
        {
            get { return selectedAssetFile; }
            set
            {
                selectedAssetFile = value;
                OnPropertyChanged("SelectedAssetFile");
            }
        }

        private string localFilePath;

        public string LocalFilePath
        {
            get { return localFilePath; }
            set
            {
                localFilePath = value;
                OnPropertyChanged("LocalFilePath");
                CheckForEncodingOrUpload(localFilePath);
            }
        }

        private string uploadStatus;

        public string UploadStatus
        {
            get { return uploadStatus; }
            set
            {
                uploadStatus = value;
                OnPropertyChanged("UploadStatus");
            }
        }

        private ObservableCollection<AssetFileInfo> assetFileList;

        public ObservableCollection<AssetFileInfo> AssetFileList
        {
            get { return assetFileList; }
            set
            {
                assetFileList = value;
                OnPropertyChanged("AssetFileList");
            }
        }

        private ObservableCollection<EncodingTypeModel> encodingTypes;

        public ObservableCollection<EncodingTypeModel> EncodingTypes
        {
            get { return encodingTypes; }
            set
            {
                encodingTypes = value;
                OnPropertyChanged("EncodingTypes");
            }
        }

        private EncodingTypeModel selectedEncodingType;

        public EncodingTypeModel SelectedEncodingType
        {
            get { return selectedEncodingType; }
            set
            {
                selectedEncodingType = value;
                OnPropertyChanged("SelectedEncodingType");
            }
        }

        private List<string> imageQualityList;

        public List<string> ImageQualityList
        {
            get { return imageQualityList; }
            set
            {
                imageQualityList = value;
                OnPropertyChanged("ImageQualityList");
            }
        }

        private string selectedImageQuality;

        public string SelectedImageQuality
        {
            get { return selectedImageQuality; }
            set
            {
                selectedImageQuality = value;
                OnPropertyChanged("SelectedImageQuality");
            }
        }

        private List<string> imageSizeList;

        public List<string> ImageSizeList
        {
            get { return imageSizeList; }
            set
            {
                imageSizeList = value;
                OnPropertyChanged("ImageSizeList");
            }
        }

        private string selectedImageSize;

        public string SelectedImageSize
        {
            get { return selectedImageSize; }
            set
            {
                selectedImageSize = value;
                OnPropertyChanged("SelectedImageSize");
            }
        }

        private int imageDurationInSeconds;

        public int ImageDurationInSeconds
        {
            get { return imageDurationInSeconds; }
            set
            {
                imageDurationInSeconds = value;
                OnPropertyChanged("ImageDurationInSeconds");
            }
        }

        private int maxNoOfThumbnails;

        public int MaxNoOfThumbnails
        {
            get { return maxNoOfThumbnails; }
            set
            {
                maxNoOfThumbnails = value;
                OnPropertyChanged("MaxNoOfThumbnails");
            }
        }

        private bool thumbnailJobSelected;

        public bool ThumbnailJobSelected
        {
            get { return thumbnailJobSelected; }
            set
            {
                thumbnailJobSelected = value;
                OnPropertyChanged("ThumbnailJobSelected");
            }
        }

        private bool thumbnailJobNotSelected;

        public bool ThumbnailJobNotSelected
        {
            get { return thumbnailJobNotSelected; }
            set
            {
                thumbnailJobNotSelected = value;
                OnPropertyChanged("ThumbnailJobNotSelected");
            }
        }

        private string _waitMessage;

        public string WaitMessage
        {
            get { return _waitMessage; }

            set
            {
                _waitMessage = value;
                OnPropertyChanged("WaitMessage");
            }
        }

        private bool processEnabled;

        public bool ProcessEnabled
        {
            get { return processEnabled; }
            set
            {
                processEnabled = value;
                OnPropertyChanged("ProcessEnabled");
            }
        }

        private ObservableCollection<UploadStatusViewModel> uploadList;

        public ObservableCollection<UploadStatusViewModel> UploadList
        {
            get { return uploadList; }
            set
            {
                uploadList = value;
                OnPropertyChanged("UploadList");
            }
        }

        private ObservableCollection<Tag> tagList;

        public ObservableCollection<Tag> TagList
        {
            get { return tagList; }
            set
            {
                tagList = value;
                OnPropertyChanged("TagList");
            }
        }

        private ObservableCollection<string> tagSource;

        public ObservableCollection<string> TagSource
        {
            get { return tagSource; }
            set
            {
                tagSource = value;
                OnPropertyChanged("TagSource");
            }
        }

        #endregion

        #region Event Handlers

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region Navigation Methods
        public void OnFragmentNavigation(FirstFloor.ModernUI.Windows.Navigation.FragmentNavigationEventArgs e)
        {
            try
            {
                Loaded -= AssetFiles_Loaded;
            }
            catch (Exception exp)
            {
                logger.LogException(LogLevel.Error, exp.Message, exp);
                UIHelper.HandlerException(exp);
            }
        }

        public void OnNavigatedFrom(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                Loaded -= AssetFiles_Loaded;
            }
            catch (Exception exp)
            {
                logger.LogException(LogLevel.Error, exp.Message, exp);
                UIHelper.HandlerException(exp);
            }
        }

        public void OnNavigatedTo(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                var frame = NavigationHelper.FindFrame(null, (FrameworkElement) this.Parent);
                if (frame != null)
                {
                    var source = frame.Source;
                    selectedAssetId = source.ToString().Split('#')[1];
                    SelectedAsset = MediaContextHelper.SelectedAsset;
                    this.TagList = new ObservableCollection<Tag>();
                    this.LocalFilePath = string.Empty;
                    if (MediaContextHelper.AssetFileList != null && MediaContextHelper.AssetFileList.Count > 0)
                    {
                        if (AssetFileList == null)
                        {
                            AssetFileList = new ObservableCollection<AssetFileInfo>(MediaContextHelper.AssetFileList);
                            this.DataContext = this;
                        }
                        Loaded -= AssetFiles_Loaded; // no load required
                    }
                    else
                    {
                        Loaded += AssetFiles_Loaded;
                    }
                }
            }
            catch (Exception exp)
            {
                logger.LogException(LogLevel.Error, exp.Message, exp);
                UIHelper.HandlerException(exp);
            }
        }

        public void OnNavigatingFrom(FirstFloor.ModernUI.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {
                //if (CanNavigate == false)
                //{
                //    MessageBoxResult result =
                //        ModernDialog.ShowMessage("Uploading and Encoding of a file is in process? ", "Warning",
                //                                 MessageBoxButton.YesNo);
                //    if (result == MessageBoxResult.Yes)
                //    {
                //        Loaded -= AssetFiles_Loaded;
                //    }
                //    if (result != MessageBoxResult.Yes)
                //    {
                //        e.Cancel = true;
                //    }
                //}
                //else
                //{
                    Loaded -= AssetFiles_Loaded;
                //}
                UploadList = null;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
                UIHelper.HandlerException(exception);
            }
        }
        #endregion

        #region Private Methods
        private void uploadHelper_OnUploadStatusChange(object sender, UploadFileEventArgs e)
        {
            try
            {
                List<UploadStatusViewModel> list = new List<UploadStatusViewModel>();
                foreach (var item in e.FileStatus)
                {
                    if (item.AssetId == MediaContextHelper.SelectedAsset.Id)
                    {
                        list.Add(new UploadStatusViewModel { FileName = item.FileName, Percentage = item.UploadPercentage });
                    }
                    //update the percentage
                }
                if (!list.Exists(p => p.Percentage != 100))
                {
                    ToggleEnableVisibility(true);
                }
                UploadList = new ObservableCollection<UploadStatusViewModel>(list);
            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_LOADING_ASSETS_PROPERTIES;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.HandlerException(exception);
            }
        }

        private async void AssetFiles_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ProcessEnabled = false;
                CanNavigate = true;
                LoadImageCustomizations();
                await LoadTags();
                this.TagList = new ObservableCollection<Tag>();
                //TagBox.EntryChanged += TagBox_EntryChanged;
                var encodingList = await FetchEncodingTypes();
                EncodingTypes = new ObservableCollection<EncodingTypeModel>(encodingList);
                //uploadHelper.OnUploadStatusChange += uploadHelper_OnUploadStatusChange;
                UploadList = new ObservableCollection<UploadStatusViewModel>();
               await Application.Current.Dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    new Action(
                        () =>
                        {
                            this.DataContext = this;
                            //ProcessEnabled = true;
                            loading.Visibility = Visibility.Collapsed;
                        }));
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
                UIHelper.HandlerException(exception);
            }
        }

        private void CheckForEncodingOrUpload(string localFilePath)
        {
            if (!string.IsNullOrWhiteSpace(localFilePath))
            {
                this.ProcessEnabled = true;
            }
        }

        private async Task LoadTags()
        {
            var tags = new List<Tag>();
            try
            {
                string uri = string.Format(Literals.URL_GET_TAGS,
                                           MediaContextHelper.accountName);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<IEnumerable<Tag>>().Result;
                tags = responseAsset as List<Tag>;
                TagSource = new ObservableCollection<string>(tags.Select(t => t.Name));
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
        }

        private void LoadImageCustomizations()
        {
            try
            {
                ThumbnailJobSelected = false;
                this.MaxNoOfThumbnails = 5;
                var imgQualityList = new List<string> { "High", "Medium", "Low" };
                this.ImageQualityList = new List<string>(imgQualityList);
                this.selectedImageQuality = "High";

                var imgSizeList = new List<string> { "320x240", "480x320", "640x480", "800x600" };
                this.ImageSizeList = new List<string>(imgSizeList);
                this.SelectedImageSize = "640x480";
                this.ImageDurationInSeconds = 20;
            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_THUMBNAIL_SETTINGS;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
            }
        }

        private async Task<List<EncodingTypeModel>> FetchEncodingTypes()
        {
            var encodingTypes = new List<EncodingTypeModel>();
            try
            {
                string uri = string.Format(Literals.URL_GET_ENCODING_TYPE,
                                           MediaContextHelper.accountName);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<IEnumerable<EncodingTypeModel>>().Result;
                encodingTypes = responseAsset as List<EncodingTypeModel>;
                return encodingTypes;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
                //UIHelper.HandlerException(ex);
            }
            return encodingTypes;
        }

        private void LocalUpload_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var dlg = new OpenFileDialog
                    {
                        FileName = "",
                        DefaultExt = ".mp4",
                        Filter =
                            Literals.SETTINGS_MEDIA_FILE_TYPES,
                        Multiselect = true
                    };

                bool? result = dlg.ShowDialog();
                if (result == true)
                {
                    // Open document
                    filePath = dlg.FileName;
                    LocalFilePath = filePath;
                    IsFileLocal = true;
                    FocusManager.SetFocusedElement(Upload_Local, null);
                    Keyboard.ClearFocus();

                    //UploadFileToAsset(filePath);
                }
            }
            catch (Exception exception)
            {
                var message = Literals.MESSAGE_ERROR_THUMBNAIL_SETTINGS;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
                //UIHelper.HandlerException(ex);
            }
        }

        private void CloudUpload_Click(object sender, RoutedEventArgs e)
        {
            var cloudWindow = new CloudUploadDialog(selectedAssetId);
            cloudWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            cloudWindow.AssetFileSelected += cloudWindow_AssetFileSelected;
            cloudWindow.Owner = Application.Current.MainWindow;
            cloudWindow.ShowDialog();

        }

        private void cloudWindow_AssetFileSelected(object sender, EventArgs e)
        {
            try
            {
                IsFileLocal = false;
                SelectedAssetFile = (e as AssetFileEventArgs).AssetFile;
                LocalFilePath = SelectedAssetFile.Name;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, Literals.MESSAGE_ERROR_LOAD_CLOUD_FILE, exception);
                UIHelper.HandlerException(exception);
            }
        }

        private async void ProcessJob_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedEnFriendlyNames = string.Empty;
                var selectedEncodings = SelectedEncodings(ref selectedEnFriendlyNames);
                bool isPrimary = false;
                string uploadSasUrl = string.Empty;
                string fileName = string.Empty;
                bool jobAlreadyExists = false;

                if (IsFileLocal)
                {
                    CanNavigate = false;
                    //selected encoding is empty or no thumbnail job is created
                    //if ((string.IsNullOrWhiteSpace(selectedEncodings) && !ThumbnailJobSelected))
                    //{
                    //    MessageBoxResult upload =
                    //        ModernDialog.ShowMessage(
                    //            Literals.MESSAGE_WARNING_ONLY_UPLOAD,
                    //            Literals.MESSAGE_HEADER_UPLOAD_CONFIRMATION, MessageBoxButton.YesNo);
                    //    if (upload == MessageBoxResult.No)
                    //    {
                    //        CanNavigate = true;
                    //        return;
                    //    }
                    //}
                    jobAlreadyExists = await IsAJobPending(selectedAssetId);
                    if (jobAlreadyExists)
                    {
                        MessageBoxResult upload =
                            ModernDialog.ShowMessage(
                                Literals.MESSAGE_WARNING_ONLY_UPLOAD,
                                Literals.MESSAGE_HEADER_UPLOAD_CONFIRMATION, MessageBoxButton.YesNo);
                        if (upload == MessageBoxResult.No)
                        {
                            CanNavigate = true;
                            return;
                        }
                    }

                    await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                               new Action(
                                                                   () =>
                                                                   {
                                                                       loading.Visibility = Visibility.Visible;
                                                                       SelectFileGrid.Visibility =
                                                                           Visibility.Collapsed;
                                                                       ProcessEnabled = false;
                                                                   }));

                    WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_CHECKING_FILE;// "Checking file";

                    uploadSasUrl = await GetUploadUrl();

                    if (!string.IsNullOrWhiteSpace(uploadSasUrl))
                    {
                        fileName = System.IO.Path.GetFileName(filePath);
                        WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_CHECKING_FILE;
                        string sasUrl = BuildSasUrl(uploadSasUrl, fileName);
                        await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send,
                                                                   new Action(
                                                                       () =>
                                                                       {
                                                                           WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_UPLOADING_FILE; // Uploading file....
                                                                       }));

                        await Task.Run(() => MediaContextHelper.FileUploader.UploadFile(MediaContextHelper.SelectedAsset.Id, filePath, uploadSasUrl)).ContinueWith(
                            delegate { CanNavigate = true; });

                        await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send,
                                                                   new Action(
                                                                       () =>
                                                                       {
                                                                           WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_UPLOADED_FILE; //
                                                                       }));
                        bool linkSuccess = await LinkFileToAsset();
                        if (linkSuccess)
                        {
                            await CreateUpdateTagsForAsset();
                            if (!string.IsNullOrWhiteSpace(selectedEncodings) || ThumbnailJobSelected)
                            {
                                var assetFiles = await GetFilesInAsset();
                                if (assetFiles != null)
                                {
                                    var files = assetFiles.Where(file => file.Name == Path.GetFileName(fileName));
                                    var maxDate = files.Max(f => f.Created);
                                    var assetFile = assetFiles.FirstOrDefault(f => f.Created == maxDate);
                                    if (assetFile != null)
                                    {
                                        isPrimary = await MakeFileAsPrimary(assetFile.Id, ThumbnailJobSelected);
                                        await CreateUpdateTagsForAssetFile(assetFile.Id);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                               new Action(
                                                                   () =>
                                                                   {
                                                                       loading.Visibility = Visibility.Visible;
                                                                       SelectFileGrid.Visibility =
                                                                           Visibility.Collapsed;
                                                                       ProcessEnabled = false;
                                                                   }));
                    WaitMessage = "Checking status";
                    jobAlreadyExists = await IsAJobPending(selectedAssetId);
                    if (jobAlreadyExists)
                    {
                        await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                   new Action(
                                                                       () =>
                                                                       {
                                                                           loading.Visibility = Visibility.Collapsed;
                                                                           SelectFileGrid.Visibility =
                                                                               Visibility.Visible;
                                                                           ProcessEnabled = true;
                                                                       }));
                        ModernDialog.ShowMessage(Literals.MESSAGE_WARNING_ALREADY_JOB_RUNNING,
                                                 Literals.MESSAGE_HEADER_SERVICE_INFO,
                                                 MessageBoxButton.OK);

                        return;
                    }
                    if (!string.IsNullOrWhiteSpace(selectedEncodings) || ThumbnailJobSelected)
                    {

                        isPrimary = await MakeFileAsPrimary(SelectedAssetFile.Id, ThumbnailJobSelected);
                    }
                    //TODO: Show message encoding should be selected
                    else
                    {
                        ModernDialog.ShowMessage(Literals.MESSAGE_WARNING_MUST_SELECT_THUMBNAIL_SETTING,
                            Literals.MESSAGE_HEADER_UPLOAD_CONFIRMATION,
                                                 MessageBoxButton.OK);
                        ToggleEnableVisibility(true);
                        return;
                    }
                }

                if (jobAlreadyExists) return;
                //Initiate Job
                if (ThumbnailJobSelected)
                {
                    WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_GENERATING_THUMBNAIL;;

                    await InitiateThumbnailJob();
                }

                if (!string.IsNullOrWhiteSpace(selectedEncodings))
                {
                    WaitMessage = Literals.MESSAGE_STATUS_UPLOAD_PROCESSING_ENCODING;

                    await InitiateJob(selectedEncodings, selectedEnFriendlyNames);
                    WaitMessage =  Literals.MESSAGE_STATUS_UPLOAD_COMPLETED_ENCODING;
                }
                await LoadTags();
            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_ENCODING_ERROR;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
                //UIHelper.HandlerException(ex);
            }
        }

        private async Task CreateUpdateTagsForAsset()
        {
            try
            {
                var tags = PrepareTagStringToUpload();
                string uri =
                    string.Format(Literals.URL_UPDATE_ASSET_TAG,
                                  MediaContextHelper.accountName, selectedAssetId, tags);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_UPDATING_TAG;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
                throw;
            }
        }

        private string PrepareTagStringToUpload()
        {
            try
            {
                string tags = TagList.Aggregate(string.Empty, (current, tag) => current + (tag.Name + ","));
                //string tags = TextTags.Text.Trim();
                if (!string.IsNullOrWhiteSpace(tags))
                {
                    var lastIndex = tags.LastIndexOf(",", System.StringComparison.Ordinal);
                    if (lastIndex > 0 && lastIndex == tags.Length - 1)
                        tags = tags.Remove(tags.LastIndexOf(",", System.StringComparison.Ordinal));
                }
                return tags;
            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_UPDATING_TAG;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
                throw;
            }
        }

        private async Task CreateUpdateTagsForAssetFile(string assetFileId)
        {
            var tags = PrepareTagStringToUpload();
            string uri =
                string.Format(
                    Literals.URL_UPDATE_FILE_TAG,
                    MediaContextHelper.accountName, selectedAssetId, assetFileId, tags);
            var response = await client.GetAsync(uri);
            response.EnsureSuccessStatusCode(); // Throw on error code.
        }

        private async Task<bool> IsAJobPending(string selectedAssetId)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(selectedAssetId))
                {
                    string uri = string.Format(
                        Literals.URL_GET_JOB_STATUS,
                        MediaContextHelper.accountName, selectedAssetId);
                    var response = await client.GetAsync(uri);
                    response.EnsureSuccessStatusCode(); // Throw on error code.

                    var responseAsset = response.Content.ReadAsAsync<bool>().Result;

                    ToggleEnableVisibility(true);

                    return responseAsset;
                }
            }
            catch (Exception exception)
            {
                string message = Literals.MESSAGE_ERROR_JOB_STATUS;
                logger.LogException(LogLevel.Error, message, exception);
                UIHelper.ShowMessage(message, Literals.MESSAGE_HEADER_ERROR, MessageBoxButton.OK);
            }
            return false;
        }

        private string SelectedEncodings(ref string selectedEnFriendlyNames)
        {
            string selectedEncodings = string.Empty;
            try
            {
                foreach (var encoding in EncodingTypes)
                {
                    if (encoding.IsSelected)
                    {
                        selectedEncodings = selectedEncodings + encoding.TechnicalName + ",";
                        selectedEnFriendlyNames = selectedEnFriendlyNames + encoding.FriendlyName + ",";
                    }
                }
                selectedEncodings = !string.IsNullOrWhiteSpace(selectedEncodings)
                                        ? selectedEncodings.Remove(selectedEncodings.LastIndexOf(","))
                                        : string.Empty;
                selectedEnFriendlyNames = !string.IsNullOrWhiteSpace(selectedEnFriendlyNames)
                                              ? selectedEnFriendlyNames.Remove(selectedEnFriendlyNames.LastIndexOf(","))
                                              : string.Empty;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return selectedEncodings;
        }

        private async Task<string> InitiateThumbnailJob()
        {
            try
            {
                var maxNoOfThumnails = MaxNoOfThumbnails;
                var imgQuality = SelectedImageQuality;
                var imageSize = SelectedImageSize.Split('x');
                var height = imageSize[0];
                var width = imageSize[1];
                var imgDurInSec = ImageDurationInSeconds.ToString();
                var enStrings = imgQuality + "," + height + "," + width + ","
                                + maxNoOfThumnails + "," + imgDurInSec;
                string uri = string.Format(
                   Literals.URL_INIT_THUMB_JOB,
                    MediaContextHelper.accountName, selectedAssetId, enStrings);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<string>().Result;

                ToggleEnableVisibility(true);

                return responseAsset;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return string.Empty;
        }

        private async Task<string> InitiateJob(string selEncodings, string selEnFriendlyNames)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(selEncodings))
                {
                    string uri = string.Format(
                       Literals.URl_INIT_JOB,
                        MediaContextHelper.accountName, selectedAssetId, selEncodings, selEnFriendlyNames);
                    var response = await client.GetAsync(uri);
                    response.EnsureSuccessStatusCode(); // Throw on error code.

                    var responseAsset = response.Content.ReadAsAsync<string>().Result;

                    ToggleEnableVisibility(true);

                    return responseAsset;
                }
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return string.Empty;
        }

        private void ToggleEnableVisibility(bool visible)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                       new Action(
                                                           () =>
                                                           {
                                                               loading.Visibility = (visible
                                                                                ? Visibility.Collapsed
                                                                                : Visibility.Visible);
                                                               SelectFileGrid.Visibility = visible
                                                                                ? Visibility.Visible
                                                                                : Visibility
                                                                                .Collapsed;
                                                               ProcessEnabled = visible;
                                                           }));
        }

        private async Task<bool> LinkFileToAsset()
        {
            try
            {
                string uri = string.Format(Literals.URL_GENERATE_FILE_METADATA,
                                           MediaContextHelper.accountName, selectedAssetId);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<bool>().Result;

                return responseAsset;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return false;
        }

        private async Task<List<AssetFileInfo>> GetFilesInAsset()
        {
            try
            {
                string uri = string.Format(Literals.URL_ASSET_FILE_CONTEXT,
                                           MediaContextHelper.accountName, selectedAssetId);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<List<AssetFileInfo>>().Result;

                return responseAsset;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return null;
        }

        private async Task<bool> MakeFileAsPrimary(string assetFileId, bool isThumbnailJobSelected)
        {
            try
            {
                string uri = string.Format(
                   Literals.URL_MAKE_FILE_PRIMARY,
                    MediaContextHelper.accountName, selectedAssetId, assetFileId, isThumbnailJobSelected);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<bool>().Result;

                return responseAsset;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return false;
        }

        internal string BuildSasUrl(string locatorPath, string fileName)
        {
            try
            {
                string queryPart = new Uri(locatorPath).Query;
                string blobContainerUri = locatorPath.Substring(0, locatorPath.Length - queryPart.Length);
                string fileUrl = string.Format("{0}/{1}{2}", blobContainerUri, fileName, queryPart);
                return fileUrl;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return string.Empty;
        }

        private async Task<string> GetUploadUrl()
        {
            try
            {
                string uri = string.Format(Literals.URL_GET_SAS_URL_UPLOAD,
                                           MediaContextHelper.accountName, selectedAssetId);
                var response = await client.GetAsync(uri);
                response.EnsureSuccessStatusCode(); // Throw on error code.

                var responseAsset = response.Content.ReadAsAsync<string>().Result;

                return responseAsset;
            }
            catch (Exception exception)
            {
                logger.LogException(LogLevel.Error, exception.Message, exception);
            }
            return string.Empty;
        }

        private void AddTags_Click(object sender, RoutedEventArgs e)
        {
            var tags = TextTags.Text.Trim();
            if (!String.IsNullOrWhiteSpace(tags))
            {
                var tagStrings = tags.Split(',').ToList();
                foreach (var tag in tagStrings)
                {
                    if (!string.IsNullOrWhiteSpace(tag))
                    {
                        var tagItem = new Tag { Id = Guid.Empty.ToString(), Name = tag };
                        if (TagList.Count == 0 || TagList.Count(t => t.Name == tag) == 0)
                        {
                            this.TagList.Add(new Tag() { Id = Guid.Empty.ToString(), Name = tag });
                        }
                        else
                        {
                            if (TagList.Any(t => string.CompareOrdinal(t.Name, tag) == 0))
                                UIHelper.ShowMessage("Tag with the same name exists", "Information", MessageBoxButton.OK);
                        }
                    }
                }
                TextTags.Text = string.Empty;
                FocusManager.SetFocusedElement(Add_Tags, null);
                Keyboard.ClearFocus();

            }
        }

        private void RemoveTag_Click(object sender, RoutedEventArgs e)
        {
            var tagId = (sender as Button).Tag.ToString();
            var tag = this.TagList.FirstOrDefault(t => t.Id == tagId);
            this.TagList.Remove(tag);
        }
        #endregion

        #region Protected Methods
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (client != null) client.Dispose();
            }
        }
        #endregion

        #region Public Methods
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}