text:
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include <unistd.h>
#include <sys/time.h>
#include <iostream>
#include <termios.h>
#include <math.h>
#include <iostream>

#include "tm_driver/tm_driver.h"

#include "tm_reflexxes/tm_reflexxes.h"

//----------------------------------------------------------------------
//! The functions in this code using Reflexxes API are distributed by
//!
//! \copyright Copyright (C) 2014 Google, Inc.
//! \n
//! \n
//! <b>GNU Lesser General Public License</b>
//! \n
//! \n
//! This file is part of the Type II Reflexxes Motion Library.
//! \n\n
//! The Type II Reflexxes Motion Library is free software: you can redistribute
//! it and/or modify it under the terms of the GNU Lesser General Public License
//! as published by the Free Software Foundation, either version 3 of the
//! License, or (at your option) any later version.
//! \n\n
//! The Type II Reflexxes Motion Library is distributed in the hope that it
//! will be useful, but WITHOUT ANY WARRANTY; without even the implied
//! warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
//! the GNU Lesser General Public License for more details.
//! \n\n
//! You should have received a copy of the GNU Lesser General Public License
//! along with the Type II Reflexxes Motion Library. If not, see
//! <http://www.gnu.org/licenses/>.

#include "ReflexxesAPI.h"
#include "RMLPositionFlags.h"
#include "RMLPositionInputParameters.h"
#include "RMLPositionOutputParameters.h"

#include "RMLVelocityFlags.h"
#include "RMLVelocityInputParameters.h"
#include "RMLVelocityOutputParameters.h"

namespace tm_reflexxes{

    void initTermios(int echo)
    {
        tcgetattr(STDIN_FILENO, &oldt); /* grab old terminal i/o settings */
        newt = oldt; /* make new settings same as old settings */
        newt.c_lflag &= ~ICANON; /* disable buffered i/o */
        newt.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
        tcsetattr(STDIN_FILENO, TCSANOW, &newt); /* use these new terminal i/o settings now */
    }

    /* Restore old terminal i/o settings */
    void resetTermios()
    {
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    }

    int kbhit()
    {
        struct timeval tv;
        fd_set rdfs;
        tv.tv_sec = 0;
        tv.tv_usec = 0;
        FD_ZERO(&rdfs);
        FD_SET (STDIN_FILENO, &rdfs);
        select(STDIN_FILENO + 1, &rdfs, NULL, NULL, &tv);
        return FD_ISSET(STDIN_FILENO, &rdfs);
    }

    //  ********************************************************************/
    //  fn        : ReflexxesSmoothStop() [Overloaded] : Velocity based use
    //  beirf     : Use RML velocity based API to stop robot smoothly.
    //              Desgin for using under velocity based API.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML velocity based.
    //  param[in] : TargetVelocity, The final velocity of each joint.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    void ReflexxesSmoothStop(       TmDriver& TR,
                                    RMLVelocityInputParameters *InputState,
                                    double SynTime)
    {
        double blend = 0, time_s;
        std::vector<double> vec;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;
        int ResultValue = 0;
        bool pass = true;
        struct timeval tm1,tm2, tm3, tm4;

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);
        IP = InputState;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library*/

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = 0.0;
            if(IP->CurrentVelocityVector->VecData[i] != 0.0)
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;

        }
        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
            printf("Input values are INVALID!\n");

        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        gettimeofday(&tm3, NULL);
        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }
            vec = { OP->NewVelocityVector->VecData[0],
                    OP->NewVelocityVector->VecData[1],
                    OP->NewVelocityVector->VecData[2],
                    OP->NewVelocityVector->VecData[3],
                    OP->NewVelocityVector->VecData[4],
                    OP->NewVelocityVector->VecData[5]};

            TR.setMoveJointSpeedabs(vec, blend);

            //**********************
            // Print out commands

            time_s = TR.interface->stateRT->getTime();
            printf("[ %lf ] pos:  ",time_s );

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //**********************

            *IP->CurrentPositionVector      =   *OP->NewPositionVector      ;
            *IP->CurrentVelocityVector      =   *OP->NewVelocityVector      ;
            *IP->CurrentAccelerationVector  =   *OP->NewAccelerationVector  ;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            // The area execution in 25ms real time sharp
            //********************************************************
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        std::vector<double> FinalPosition;
        time_s = TR.interface->stateRT->getQAct(FinalPosition);
        printf("=============== Final state of Smooth Stop =========================\n");
        printf("[ %lf ]  ", time_s);

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            printf(" %10.4lf ",FinalPosition[i]);
        printf("\n");
        print_info("Smooth stop finish in %llu us", tt);
        InputState = IP;

        delete  RML;
        delete  IP;
        delete  OP;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesSmoothStop() [Overloadded] : Positioin based use
    //  beirf     : Use RML velocity based API to stop robot smoothly.
    //              Degigned for using under postion based API.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML position based.
    //  param[in] : TargetVelocity, The final velocity of each joint.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    void ReflexxesSmoothStop(       TmDriver& TR,
                                    RMLPositionInputParameters *InputState,
                                    double SynTime)
    {
        double blend = 0, time_s;
        std::vector<double> vec;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;
        int ResultValue = 0;
        bool pass = true;
        struct timeval tm1,tm2, tm3, tm4;

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP  = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP  = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);

        *IP->CurrentPositionVector     = *InputState->CurrentPositionVector;
        *IP->CurrentVelocityVector     = *InputState->CurrentVelocityVector;
        *IP->CurrentAccelerationVector = *InputState->CurrentAccelerationVector;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library*/

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = 0.0;
            if(IP->CurrentVelocityVector->VecData[i] != 0.0)
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;

        }
        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
            printf("Input values are INVALID!\n");

        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        gettimeofday(&tm3, NULL);
        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }
            vec = { OP->NewVelocityVector->VecData[0],
                    OP->NewVelocityVector->VecData[1],
                    OP->NewVelocityVector->VecData[2],
                    OP->NewVelocityVector->VecData[3],
                    OP->NewVelocityVector->VecData[4],
                    OP->NewVelocityVector->VecData[5]};

            TR.setMoveJointSpeedabs(vec, blend);

            //**********************
            // Print out commands

            time_s = TR.interface->stateRT->getTime();
            printf("[ %lf ] pos:  ",time_s );

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //**********************

            *IP->CurrentPositionVector      =   *OP->NewPositionVector      ;
            *IP->CurrentVelocityVector      =   *OP->NewVelocityVector      ;
            *IP->CurrentAccelerationVector  =   *OP->NewAccelerationVector  ;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            // The area execution in 25ms real time sharp
            //********************************************************
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        std::vector<double> FinalPosition;
        time_s = TR.interface->stateRT->getQAct(FinalPosition);
        printf("=============== Final state of Smooth Stop =========================\n");
        printf("[ %lf ]  ", time_s);

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            printf(" %10.4lf ",FinalPosition[i]);
        printf("\n");
        print_info("Smooth stop finish in %llu us", tt);

        *InputState->CurrentPositionVector     = *IP->CurrentPositionVector;
        *InputState->CurrentVelocityVector     = *IP->CurrentVelocityVector;
        *InputState->CurrentAccelerationVector = *IP->CurrentAccelerationVector;

        delete  RML;
        delete  IP;
        delete  OP;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesVelocityRun()
    //  beirf     : Use RML API to execute given velocity.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML.
    //  param[in] : TargetVelocity, The velocity when reach target position.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    bool ReflexxesVelocityRun(      TmDriver& TR,
                                    RMLVelocityInputParameters &InputState,
                                    std::vector<double> TargetVelocity,
                                    double SynTime)
    {
        double blend = 0, time_s;
        std::vector<double> vec;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;
        int ResultValue = 0;
        bool pass = true;

        initTermios(1);

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP  = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP  = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);
        *IP = InputState;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library*/

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = TargetVelocity[i];

            if(IP->CurrentVelocityVector->VecData[i] != TargetVelocity[i])
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;
        }

        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
            printf("Input values are INVALID!\n");

        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        struct timeval tm1,tm2, tm3, tm4;

        gettimeofday(&tm3, NULL);

        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }
            vec = { OP->NewVelocityVector->VecData[0],
                    OP->NewVelocityVector->VecData[1],
                    OP->NewVelocityVector->VecData[2],
                    OP->NewVelocityVector->VecData[3],
                    OP->NewVelocityVector->VecData[4],
                    OP->NewVelocityVector->VecData[5]};

            TR.setMoveJointSpeedabs(vec, blend);

            //**********************
            // Print out commands

            time_s = TR.interface->stateRT->getTime();
            printf("[ %lf ] pos:  ",time_s );
            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");
            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //***********************

            if (kbhit())
            {
                char c = getchar();
                if (c == 'q' || c == 'Q')
                {
                    print_info("Smooth Stop Activate...");
                    ReflexxesSmoothStop(TR, IP, 0.5);
                    pass = false;
                    break;
                }
            }

            *IP->CurrentPositionVector      =   *OP->NewPositionVector      ;
            *IP->CurrentVelocityVector      =   *OP->NewVelocityVector      ;
            *IP->CurrentAccelerationVector  =   *OP->NewAccelerationVector  ;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            //********************************************************
            // The area execution in 25ms real time sharp
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        if(pass)
        {
            std::vector<double> FinalPosition;
            time_s = TR.interface->stateRT->getQAct(FinalPosition);
            printf("=============== Final state velocity based =========================\n");
            printf("[ %lf ]  ", time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf(" %10.4lf ",FinalPosition[i]);
            printf("\n");
            print_info("Finished in %llu us", tt);
        }

        resetTermios();

        InputState = *IP;

        delete  RML;
        delete  IP;
        delete  OP;

        return pass;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesPositionRun()
    //  beirf     : Use RML API to execute given position.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML.
    //  param[in] : TargetVelocity, The final velocity of each joint.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    bool ReflexxesPositionRun(      TmDriver& TR,
                                    RMLPositionInputParameters &InputState,
                                    std::vector<double> TargetPosition,
                                    std::vector<double> TargetVelocity,
                                    double SynTime)
    {
        double blend = 0, time_s;
        std::vector<double> vec, CurrentPosition, FinalPosition;
        bool pass = true;
        struct timeval tm1,tm2, tm3, tm4;

        ReflexxesAPI *RML = NULL    ;
        RMLPositionInputParameters  *IP = NULL;
        RMLPositionOutputParameters *OP = NULL;
        RMLPositionFlags Flags;
        int ResultValue = 0;

        initTermios(1);

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLPositionInputParameters(NUMBER_OF_DOFS);
        OP = new RMLPositionOutputParameters(NUMBER_OF_DOFS);
        *IP = InputState;
        time_s = TR.interface->stateRT->getQAct(CurrentPosition);

        //  ********************************************************************/
        //  Assigning all RMLPositionInputParameters :
        //  Current POS, VEL, ACC : set before call ReflexxesPositionRun
        //  Target POS, VEL       : set before call ReflexxesPositionRun
        //  Max VEL, ACC          : set after call ReflexxesPositionRun
        //  SelectionVector       : set after call ReflexxesPositionRun
        //  ********************************************************************
        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->CurrentPositionVector->VecData[i] = CurrentPosition[i];
            IP->MaxVelocityVector->VecData[i] = MAX_VELOCITY; //0.3247
            IP->MaxAccelerationVector->VecData[i] = MAX_ACC;
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->TargetPositionVector->VecData[i] = TargetPosition[i];
            IP->TargetVelocityVector->VecData[i] = TargetVelocity[i];
            IP->SelectionVector->VecData[i] = true;
        }
        IP->MinimumSynchronizationTime = SynTime;

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
        {
            printf("Input values are INVALID!\n");
            pass = false;
        }

        gettimeofday(&tm3, NULL);

        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLPosition(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }
            vec = { OP->NewVelocityVector->VecData[0],
                    OP->NewVelocityVector->VecData[1],
                    OP->NewVelocityVector->VecData[2],
                    OP->NewVelocityVector->VecData[3],
                    OP->NewVelocityVector->VecData[4],
                    OP->NewVelocityVector->VecData[5]};

            TR.setMoveJointSpeedabs(vec, blend);

            //**********************************
            // Print out commands

            time_s = TR.interface->stateRT->getTime();
            printf("[ %lf ] pos:  ",time_s );

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            {
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);
            }

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            {
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);
            }
            printf("\n");

            //***********************************

            if (kbhit())
            {
                char c = getchar();
                if (c == 'q' || c == 'Q')
                {
                    print_info("Smooth Stop Activate...");
                    ReflexxesSmoothStop(TR, IP, 0.5);
                    pass = false;
                    break;
                }
            }

            *IP->CurrentPositionVector =  *OP->NewPositionVector;
            *IP->CurrentVelocityVector =  *OP->NewVelocityVector;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            //********************************************************
            // The area execution in 25ms real time sharp
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        if(pass) // print out final state
        {
            time_s = TR.interface->stateRT->getQAct(FinalPosition);
            printf("=============== Final state position based =========================\n");
            printf("[ %lf ]  ", time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf(" %10.4lf ",FinalPosition[i]);

            printf("\n");
            print_info("Finished in %llu us", tt);
        }

        resetTermios();

        InputState = *IP;

        delete  RML;
        delete  IP;
        delete  OP;

        return pass;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesSmoothStop_sim() [Overloaded] : velocity-based use
    //  beirf     : Use RML velocity based API to stop robot smoothly.
    //              Degigned for using under velocity based API.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML velocity based.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    void ReflexxesSmoothStop_sim(   RMLVelocityInputParameters *InputState,
                                    double SynTime)
    {
        double time_s;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;

        int ResultValue = 0;
        bool pass = true;
        struct timeval tm1,tm2, tm3, tm4;
        double cycle_iteration = 1.0;

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);
        IP = InputState;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library*/

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = 0.0;

            if(IP->CurrentVelocityVector->VecData[i] != 0.0)
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;

        }
        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
        {
            printf("Input values are INVALID!\n");
        }

        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        gettimeofday(&tm3, NULL);
        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }

            //**********************
            // Print out commands

            time_s = cycle_iteration*0.025;
            cycle_iteration++;
            printf("[ %lf ] pos:  ",time_s );

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //**********************

            *IP->CurrentPositionVector      =   *OP->NewPositionVector      ;
            *IP->CurrentVelocityVector      =   *OP->NewVelocityVector      ;
            *IP->CurrentAccelerationVector  =   *OP->NewAccelerationVector  ;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            // The area execution in 25ms real time sharp
            //********************************************************
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        printf("=============== Final state of Smooth Stop =========================\n");
        printf("[ %lf ]  ", time_s);

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            printf(" %10.4lf ",IP->CurrentPositionVector->VecData[i]);
        printf("\n");
        print_info("Smooth stop finish in %llu us", tt);
        InputState = IP;

        delete  RML;
        delete  IP;
        delete  OP;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesSmoothStop_sim() [Overloaded] : position -based use
    //  beirf     : Use RML velocity based API to stop robot smoothly.
    //              Degigned for using under postion based API.
    //  param[in] : TR, Object of TM driver.
    //  param[in] : &InputState, Current State of robot under RML velocity based.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    void ReflexxesSmoothStop_sim(   RMLPositionInputParameters *InputState,
                                    double SynTime)
    {
        double time_s;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;

        int ResultValue = 0;
        bool pass = true;
        struct timeval tm1,tm2, tm3, tm4;
        double cycle_iteration = 1.0;

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);

        *IP->CurrentPositionVector     = *InputState->CurrentPositionVector;
        *IP->CurrentVelocityVector     = *InputState->CurrentVelocityVector;
        *IP->CurrentAccelerationVector = *InputState->CurrentAccelerationVector;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library*/

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = 0.0;

            if(IP->CurrentVelocityVector->VecData[i] != 0.0)
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;

        }
        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
        {
            printf("Input values are INVALID!\n");
        }

        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        gettimeofday(&tm3, NULL);
        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }

            //**********************
            // Print out commands

            time_s = cycle_iteration*0.025;
            cycle_iteration++;
            printf("[ %lf ] pos:  ",time_s );

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //**********************

            *IP->CurrentPositionVector      =   *OP->NewPositionVector      ;
            *IP->CurrentVelocityVector      =   *OP->NewVelocityVector      ;
            *IP->CurrentAccelerationVector  =   *OP->NewAccelerationVector  ;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            // The area execution in 25ms real time sharp
            //********************************************************
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        printf("=============== Final state of Smooth Stop =========================\n");
        printf("[ %lf ]  ", time_s);

        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            printf(" %10.4lf ",IP->CurrentPositionVector->VecData[i]);
        printf("\n");
        print_info("Smooth stop finish in %llu us", tt);
        *InputState->CurrentPositionVector     = *IP->CurrentPositionVector;
        *InputState->CurrentVelocityVector     = *IP->CurrentVelocityVector;
        *InputState->CurrentAccelerationVector = *IP->CurrentAccelerationVector;

        delete  RML;
        delete  IP;
        delete  OP;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesVelocityRun_sim()
    //  beirf     : Use RML API to execute given velocity in simulation.
    //  param[in] : &InputState, Current State of robot under RML.
    //  param[in] : TargetVelocity, The velocity when reach target position.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    bool ReflexxesVelocityRun_sim(  RMLVelocityInputParameters &InputState,
                                    std::vector<double> TargetVelocity,
                                    double SynTime)
    {
        double time_s;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;
        int ResultValue = 0;
        bool pass = true;

        initTermios(1);

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);
        *IP = InputState;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library
        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = TargetVelocity[i];

            if(IP->CurrentVelocityVector->VecData[i] != TargetVelocity[i])
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;
        }
        IP->MinimumSynchronizationTime = SynTime;

        // ********************************************************************

        if (IP->CheckForValidity())
        {
            printf("Input values are valid!\n");
        }
        else
        {
            printf("Input values are INVALID!\n");
        }
        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        struct timeval tm1,tm2, tm3, tm4;
        double cycle_iteration = 1.0;

        gettimeofday(&tm3, NULL);

        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }

            //***************************************************************
            // Print out commands

            time_s = cycle_iteration*0.025;
            cycle_iteration++;

            printf("[ %lf ] pos:  ",time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //***************************************************************
            if (kbhit())
            {
                char c = getchar();
                if (c == 'q' || c == 'Q')
                {
                    print_info("Smooth Stop Activate...");
                    ReflexxesSmoothStop_sim(IP, 0.5);
                    pass = false;
                    break;
                }
            }

            *IP->CurrentPositionVector =  *OP->NewPositionVector;
            *IP->CurrentVelocityVector =  *OP->NewVelocityVector;
            *IP->CurrentAccelerationVector = *OP->NewAccelerationVector;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            //********************************************************
            // The area execution in 25ms real time sharp
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        if(pass)
        {
            printf("=============== Final state velocity based =========================\n");
            printf("[ %lf ]  ", time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf(" %10.4lf ",IP->CurrentVelocityVector->VecData[i]);
            printf("\n");
            print_info("Finished in %llu us", tt);
        }

        resetTermios();

        InputState = *IP;
        delete  RML;
        delete  IP;
        delete  OP;

        return pass;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesVelocityRun_sim() [Overloaded]
    //  beirf     : Use RML API to execute given velocity in simulation.
    //  param[in] : &InputState, Current State of robot under RML.
    //  param[in] : TargetVelocity, The velocity when reach target position.
    //  ********************************************************************
    bool ReflexxesVelocityRun_sim(  RMLVelocityInputParameters &InputState,
                                    std::vector<double> TargetVelocity)
    {
        double time_s;

        ReflexxesAPI *RML = NULL;
        RMLVelocityInputParameters  *IP = NULL;
        RMLVelocityOutputParameters *OP = NULL;
        RMLVelocityFlags Flags;
        int ResultValue = 0;
        bool pass = true;

        initTermios(1);

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLVelocityInputParameters(NUMBER_OF_DOFS);
        OP = new RMLVelocityOutputParameters(NUMBER_OF_DOFS);
        *IP = InputState;

        // ********************************************************************/
        // Creating all relevant objects of the Type II Reflexxes Motion Library
        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxAccelerationVector->VecData[i] = 0.5*40;
            IP->TargetVelocityVector->VecData[i] = TargetVelocity[i];

            if(IP->CurrentVelocityVector->VecData[i] != TargetVelocity[i])
                IP->SelectionVector->VecData[i] = true;
            else
                IP->SelectionVector->VecData[i] = false;
        }

        // ********************************************************************

        if (IP->CheckForValidity())
        {
            printf("Input values are valid!\n");
        }
        else
        {
            printf("Input values are INVALID!\n");
        }
        Flags.SynchronizationBehavior = RMLFlags::ONLY_TIME_SYNCHRONIZATION;

        struct timeval tm1,tm2, tm3, tm4;
        double cycle_iteration = 1.0;

        gettimeofday(&tm3, NULL);

        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLVelocity(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }

            //***************************************************************
            // Print out commands

            time_s = cycle_iteration*0.025;
            cycle_iteration++;

            printf("[ %lf ] pos:  ",time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);

            printf("\n");

            //***************************************************************
            if (kbhit())
            {
                char c = getchar();
                if (c == 'q' || c == 'Q')
                {
                    print_info("Smooth Stop Activate...");
                    ReflexxesSmoothStop_sim(IP, 0.5);
                    pass = false;
                    break;
                }
            }

            *IP->CurrentPositionVector =  *OP->NewPositionVector;
            *IP->CurrentVelocityVector =  *OP->NewVelocityVector;
            *IP->CurrentAccelerationVector = *OP->NewAccelerationVector;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            //********************************************************
            // The area execution in 25ms real time sharp
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        if(pass)
        {
            printf("=============== Final state velocity based =========================\n");
            printf("[ %lf ]  ", time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf(" %10.4lf ",IP->CurrentVelocityVector->VecData[i]);
            printf("\n");
            print_info("Finished in %llu us", tt);
        }

        resetTermios();

        InputState = *IP;
        delete  RML;
        delete  IP;
        delete  OP;

        return pass;
    }

    //  ********************************************************************/
    //  fn        : ReflexxesPositionRun_sim()
    //  beirf     : Use RML API to execute given position in silumation.
    //  param[in] : &InputState, Current State of robot under RML.
    //  param[in] : TargetVelocity, The final velocity of each joint.
    //  param[in] : SynTime, The time for execute the trajectory.
    //  ********************************************************************
    bool ReflexxesPositionRun_sim(  RMLPositionInputParameters &InputState,
                                    std::vector<double> TargetPosition,
                                    std::vector<double> TargetVelocity,
                                    double SynTime)
    {
        double time_s;
        std::vector<double> FinalPosition;
        bool pass = true;

        ReflexxesAPI *RML = NULL    ;
        RMLPositionInputParameters  *IP = NULL;
        RMLPositionOutputParameters *OP = NULL;
        RMLPositionFlags Flags;
        int ResultValue = 0;

        initTermios(1);

        RML = new ReflexxesAPI(NUMBER_OF_DOFS, CYCLE_TIME_IN_SECONDS);
        IP = new RMLPositionInputParameters(NUMBER_OF_DOFS);
        OP = new RMLPositionOutputParameters(NUMBER_OF_DOFS);

        *IP = InputState;

        //  ********************************************************************/
        //  Assigning all RMLPositionInputParameters :
        //  Current POS, VEL, ACC : set before call ReflexxesPositionRun
        //  Target POS, VEL       : set before call ReflexxesPositionRun
        //  Max VEL, ACC          : set after call ReflexxesPositionRun
        //  SelectionVector       : set after call ReflexxesPositionRun
        //  ********************************************************************
        for (int i = 0; i < NUMBER_OF_DOFS; ++i)
        {
            IP->MaxJerkVector->VecData[i] = 100; //RMLTypeII not using, needed for validity
            IP->MaxVelocityVector->VecData[i] = MAX_VELOCITY; //0.3247
            IP->MaxAccelerationVector->VecData[i] = MAX_ACC;
            IP->TargetPositionVector->VecData[i] = TargetPosition[i];
            IP->TargetVelocityVector->VecData[i] = TargetVelocity[i];
            IP->SelectionVector->VecData[i] = true;
        }
        IP->MinimumSynchronizationTime = SynTime;

        if (IP->CheckForValidity())
            printf("Input values are valid!\n");
        else
        {
            printf("Input values are INVALID!\n");
            pass = false;
        }

        struct timeval tm1,tm2, tm3, tm4;
        double cycle_iteration = 1.0;

        gettimeofday(&tm3, NULL);

        while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
        {
            //********************************************************
            // The area execution in 25ms real time sharp

            gettimeofday(&tm1, NULL);

            ResultValue =  RML->RMLPosition(*IP, OP, Flags );

            if (ResultValue < 0)
            {
                printf("An error occurred (%d).\n", ResultValue );
                break;
            }

            //***************************************************************
            // Print out commands

            time_s = cycle_iteration*0.025;
            cycle_iteration++;

            printf("[ %lf ] pos:  ",time_s);

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            {
                printf("%10.4lf ", OP->NewPositionVector->VecData[i]);
            }

            printf(" | spd: ");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
            {
                printf("%10.4lf ", OP->NewVelocityVector->VecData[i]);
            }
            printf("\n");

            //***************************************************************

            if (kbhit())
            {
                char c = getchar();
                if (c == 'q' || c == 'Q')
                {
                    print_info("Smooth Stop Activate...");
                    ReflexxesSmoothStop_sim(IP, 0.5);
                    pass = false;
                    break;
                }
            }

            *IP->CurrentPositionVector =  *OP->NewPositionVector;
            *IP->CurrentVelocityVector =  *OP->NewVelocityVector;

            gettimeofday(&tm2, NULL);
            long long time_compensation = 1000000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec);
            usleep(24940 - time_compensation);

            //********************************************************
            // The area execution in 25ms real time sharp
        }

        gettimeofday(&tm4, NULL);
        long long tt = 1000000 * (tm4.tv_sec - tm3.tv_sec) + (tm4.tv_usec - tm3.tv_usec);

        if(pass)
        {
            printf("=============== Final state =========================\n");

            for (int i = 0; i < NUMBER_OF_DOFS; ++i)
                printf("%10.4lf ", IP->CurrentPositionVector->VecData[i]);

            printf("\n");
            print_info("Finished in %llu us", tt);
        }
        resetTermios();
        InputState = *IP;

        delete  RML;
        delete  IP;
        delete  OP;

        return pass;
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Background related CSS Properties | CSS World</title>
	<link rel="stylesheet" href="css/common.css">
	<link rel="stylesheet" href="css/15-forms.css">
	<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400|Slabo+27px" rel="stylesheet">

CSS World

Type

Block

List

Background

Border

Box

Positions

@Rules

Animation

Flex

Grids

Video, Audio, Canvas

Layouts

Tables

Forms

Form Tag

	<form action="thankyou.html" method="post" name="" >

			Username
			<input type="text" id="uName" placeholder="Enter USer name" name="uName">

			Password
			<input type="password" id="uPass" placeholder="Enter Password" name="uPass">

			<input type="submit"  value="Login">

	</form>

Form Tags

	<form action="test" method="get">
		<fieldset>
			<legend>Personal Info</legend>

				First Name
				<input type="text" id="fName">

				Last Name
				<input type="text" id="lName">

				Email
				<input type="text" id="email">

		</fieldset>
		<fieldset>
			<legend>Address</legend>

				First Name
				<input type="text" id="fName" maxlength="2">

				Last Name
				<input type="text" id="lName">

		</fieldset>
	</form>

----------- eo form-wrap bg-grey -----------

Input Tag

	<form action="test" method="get">
		<fieldset>
			<legend>Input Tag</legend>

				Input Tag demo
				<input type="text" name="input1" id="input1" placeholder="Input tag demo" value="some text" disabled readonly required>

				Input Type Text
				<input type="text" name="input2" id="input2" placeholder="Input type text"  >

				Input Type Text
				<input type="text" name="input21" id="input21" placeholder="Input type text" class="input-bgi"  >

				Input Type Text

<input type="text" name="input22" id="input22" placeholder="Input type text" class="input-bg"  >

				Input Type Password
				<input type="password" name="input3" id="input3" placeholder="Input type password" >

				Input Type File
				<input type="file" name="input4" id="input4" placeholder="Input type File" >

				Input Type Image
				<input type="image" name="input5" id="input5" src="img/icon-speaker.png"  >

				Input Type Button
				<input type="button" name="input6" id="input6" value="Dummy Button"  >

				Input Type Submit
				<input type="submit" name="input7" id="input7" value="Submit Button"  >

				Input Type Reset
				<input type="reset" name="input8" id="input8" value="Reset Button"  >

			<input type="hidden" name="courseType" value="Web developer training"  >

		</fieldset>
		<fieldset>
			<legend>Input Tag - Radio Buttons</legend>

Who is the president of India

					<input type="radio" name="president" id="radio1" value="Pranab Mukerji" >
					Pranab Mukerji

					<input type="radio" name="president" id="radio2" value="Meira Kumar" >
					Meira Kumar

					<input type="radio" name="president" id="radio3" value="Ram Nath Kovind" >
					Ram Nath Kovind

					<input type="radio" name="president" id="radio4" value="Narendra Modi" checked  >
					Narendra Modi

		</fieldset>
		<fieldset>
			<legend>Input Tag - Checkboxes</legend>

Who is your favourite actor

					<input type="checkbox" name="actor" id="checkbox1" value="Sharukh Khan" >
					Sharukh Khan

					<input type="checkbox" name="actor" id="checkbox2" value="Salman Khan" >
					Salman Khan

					<input type="checkbox" name="actor" id="checkbox3" value="Akshay Kumar" >
					Akshay Kumar

					<input type="checkbox" name="actor" id="checkbox4" value="Aamir Khan" >
					Aamir Khan

					<input type="checkbox" name="actor" id="checkbox5" value="Saif Ali Khan" >
					Saif Ali Khan

					<input type="checkbox" name="actor" id="checkbox6" value="Ranbir Kapoor" >
					Ranbir Kapoor

		</fieldset>
		<fieldset>
			<legend>Other Tags</legend>

				Enter your message
				<textarea name="message" id="txtarea1" placeholder="Enter your message" class="txt-area" autofocus>textarea specific css property
.txt-area{
  resize: horizontal;
  width:300px;
}

				</textarea>

				Select box
				<select name="Select1" id="select1">
					<option value="">Select your City</option>
					<option value="Maddur">Maddur</option>
					<option value="Mandya">Mandya</option>
					<option value="Mysore">Mysore</option>
					<option value="Mangaluru">Mangaluru</option>
					<option value="Meerut">Meerut</option>
					<option value="Meghalaya">Meghalaya</option>
				</select>

				Select box Mulitple
				<select name="Select2" id="select2" multiple>
					<option value="">Select your City</option>
					<option value="Maddur">Maddur</option>
					<option value="Mandya">Mandya</option>
					<option value="Mysore">Mysore</option>
					<option value="Mangaluru">Mangaluru</option>
					<option value="Meerut">Meerut</option>
					<option value="Meghalaya">Meghalaya</option>
				</select>

				Select box With optgroup
				<select name="Select3" id="select3">
					<option value="">Select your City</option>
					<optgroup label="Metro Cities">
						<option value="Delhi">Delhi</option>
						<option value="Kolkatta">Kolkatta</option>
						<option value="Mumbai">Mumbai</option>
						<option value="Chennai">Chennai</option>
					</optgroup>
					<optgroup label="Other Cities">
						<option value="Maddur">Maddur</option>
						<option value="Mandya">Mandya</option>
						<option value="Mysore">Mysore</option>
						<option value="Mangaluru">Mangaluru</option>
						<option value="Meerut">Meerut</option>
						<option value="Meghalaya">Meghalaya</option>
					</optgroup>
				</select>

		</fieldset>
	</form>

HTML5 form tags

	<form action="test" method="get">
		<fieldset>
			<legend>HTML5 form elements</legend>

				Input Type Email
				<input type="email" name="input9" id="input9" placeholder="Enter your email">

				Input Type URL
				<input type="url" name="input10" id="input10" placeholder="Enter your url">

				Input Type number
				<input type="number" name="input11" id="input11" placeholder="Enter your number" min="200" max="500" step="50">

				Input Type range
				<input type="range" name="input12" id="input12" placeholder="Enter your range" min="200" max="500" step="50">

				Input Type range
				<input type="date" name="input13" id="input13" placeholder="Enter your DOB" >

		</fieldset>

	</form>

© 2017 - KriS' School of Web, all rights reserved

redpajama_set_name: RedPajamaGithub


text:
/* @flow */
import { remote } from "electron";

import path from "path";

import { selectors } from "@nteract/core";
import type { ContentRef, KernelRef, AppState } from "@nteract/core";

import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";
// $FlowFixMe: This exists, we're missing a flow definition
import { combineLatest } from "rxjs/observable/combineLatest";
import { from } from "rxjs/observable/from";

import {
  map,
  distinctUntilChanged,
  debounceTime,
  switchMap,
  mergeMap,
  share
} from "rxjs/operators";

const HOME = remote.app.getPath("home");

/**
 * Turn a path like /Users/n/mine.ipynb to ~/mine.ipynb
 * @param  {string} p the full path to a file
 * @return {string}   tildified path
 */
export function tildify(p: ?string) {
  if (!p) {
    return "";
  }
  const s = path.normalize(p) + path.sep;
  return (s.indexOf(HOME) === 0
    ? s.replace(HOME + path.sep, `~${path.sep}`)
    : s
  ).slice(0, -1);
}

export function setTitleFromAttributes(attributes: *) {
  const filename = tildify(attributes.fullpath);
  const { kernelStatus } = attributes;

  try {
    const win = remote.getCurrentWindow();
    if (filename && win.setRepresentedFilename) {
      win.setRepresentedFilename(attributes.fullpath);
      win.setDocumentEdited(attributes.modified);
    }
    const title = `${filename} - ${kernelStatus}`;
    win.setTitle(title);
  } catch (e) {
    /* istanbul ignore next */
    (function log1277() {
      console.error(
        "Unable to set the filename, see https://github.com/nteract/nteract/issues/1277"
      );
      console.error(e);
      console.error(e.stack);
    })();
  }
}

export function createTitleFeed(contentRef: ContentRef, state$: *) {
  const content$ = state$.pipe(
    mergeMap((state: AppState) => {
      const content = selectors.content(state, { contentRef });
      if (content) {
        return of(content);
      } else {
        return empty();
      }
    })
  );

  const fullpath$ = content$.pipe(
    map(content => content.filepath || "Untitled"),
    distinctUntilChanged()
  );

  const modified$ = content$.pipe(
    map(content => selectors.notebook.isDirty(content.model)),
    distinctUntilChanged()
  );

  const kernelRef$ = content$.pipe(
    mergeMap(content => {
      if (content && content.type === "notebook") {
        // FIXME COME BACK TO HERE, we need to strip off the kernelRef
        // const kernelRef = content.model.kernelRef;
        return of(content.model.kernelRef);
      } else {
        return empty();
      }
    })
  );

  const kernelStatus$ = combineLatest(
    state$,
    kernelRef$,
    (state: AppState, kernelRef: KernelRef) => {
      const kernel = selectors.kernel(state, { kernelRef });
      if (!kernel) {
        return "not connected";
      } else {
        return kernel.status;
      }
    }
  ).pipe(debounceTime(200));

  return combineLatest(
    modified$,
    fullpath$,
    kernelStatus$,
    (modified, fullpath, kernelStatus) => ({
      modified,
      fullpath,
      kernelStatus
    })
  ).pipe(
    distinctUntilChanged(),
    switchMap(i => of(i))
  );
}

export function initNativeHandlers(contentRef: ContentRef, store: *) {
  const state$ = from(store).pipe(share());

  return createTitleFeed(contentRef, state$).subscribe(
    setTitleFromAttributes,
    err => console.error(err)
  );
}


text:
#ifndef OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_HPP_
#define OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_HPP_

#include <string>
#include <vector>

#include "extractor/guidance/turn_instruction.hpp"
#include "util/typedefs.hpp" // EdgeID

namespace osrm
{
namespace extractor
{
namespace guidance
{

// Every Turn Operation describes a way of switching onto a segment, indicated by an EdgeID. The
// associated turn is described by an angle and an instruction that is used to announce it.
// The Turn Operation indicates what is exposed to the outside of the turn analysis.
struct TurnOperation final
{
    EdgeID eid;
    double angle;
    TurnInstruction instruction;
};

// A Connected Road is the internal representation of a potential turn. Internally, we require
// full list of all connected roads to determine the outcome.
// The reasoning behind is that even invalid turns can influence the perceived angles, or even
// instructions themselves. An pososible example can be described like this:
//
// aaa(2)aa
//          a - bbbbb
// aaa(1)aa
//
// will not be perceived as a turn from (1) -> b, and as a U-turn from (1) -> (2).
// In addition, they can influence whether a turn is obvious or not. b->(2) would also be no
// turn-operation,
// but rather a name change.
//
// If this were a normal intersection with
//
// cccccccc
//            o  bbbbb
// aaaaaaaa
//
// We would perceive a->c as a sharp turn, a->b as a slight turn, and b->c as a slight turn.
struct ConnectedRoad final
{
    ConnectedRoad(const TurnOperation turn, const bool entry_allowed = false);

    // a turn may be relevant to good instructions, even if we cannot enter the road
    bool entry_allowed;
    TurnOperation turn;
};

// small helper function to print the content of a connected road
std::string toString(const ConnectedRoad &road);

typedef std::vector<ConnectedRoad> Intersection;

} // namespace guidance
} // namespace extractor
} // namespace osrm

#endif /*OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_HPP_*/


text:
#pragma once

namespace libh
{
namespace detail
{
namespace backend
{
namespace cuda
{
namespace detail
{

template<typename T_RAND_ACCESS_ITERATOR1,
         typename T_RAND_ACCESS_ITERATOR2,
         typename T_HASH_FUNCTOR,
         typename hash_access_tag>
void hash(T_RAND_ACCESS_ITERATOR1 keys_begin,
          T_RAND_ACCESS_ITERATOR1 keys_end,
          T_RAND_ACCESS_ITERATOR2 hash_table_begin,
          T_RAND_ACCESS_ITERATOR2 hash_table_end,
          T_HASH_FUNCTOR          hf,
          bool                    constrained_hash_access,
          libhu::U32             &max_age);

template<typename T_RAND_ACCESS_ITERATOR1,
         typename T_RAND_ACCESS_ITERATOR2,
         typename T_RAND_ACCESS_ITERATOR3,
         typename T_HASH_FUNCTOR,
         typename hash_access_tag>
void hash_by_key(T_RAND_ACCESS_ITERATOR1 keys_begin,
                 T_RAND_ACCESS_ITERATOR1 keys_end,
                 T_RAND_ACCESS_ITERATOR2 values_begin,
                 T_RAND_ACCESS_ITERATOR3 hash_table_begin,
                 T_RAND_ACCESS_ITERATOR3 hash_table_end,
                 T_HASH_FUNCTOR          hf,
                 bool                    constrained_hash_access,
                 libhu::U32             &max_age);

} // end namespace detail
} // end namespace cuda
} // end namespace backend
} // end namespace detail
} // end namespace libh

#include "hash.inl"


text:
#The MIT License (MIT)
#Copyright (c) 2014 Microsoft Corporation

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

from six.moves.urllib.parse import urlparse
import six

import unittest
import time

import pydocumentdb.document_client as document_client
import pydocumentdb.documents as documents
import pydocumentdb.errors as errors
import pydocumentdb.global_endpoint_manager as global_endpoint_manager
import pydocumentdb.endpoint_discovery_retry_policy as endpoint_discovery_retry_policy
import pydocumentdb.retry_utility as retry_utility
import pydocumentdb.http_constants as http_constants
import test.test_config as test_config

#IMPORTANT NOTES:

#  	Most test cases in this file create collections in your DocumentDB account.
#  	Collections are billing entities.  By running these test cases, you may incur monetary costs on your account.

#  	To Run the test, replace the two member fields (masterKey and host) with values
#   associated with your DocumentDB account.

class Test_globaldb_tests(unittest.TestCase):

    host = test_config._test_config.global_host
    write_location_host = test_config._test_config.write_location_host
    read_location_host = test_config._test_config.read_location_host
    read_location2_host = test_config._test_config.read_location2_host
    masterKey = test_config._test_config.global_masterKey

    write_location = test_config._test_config.write_location
    read_location = test_config._test_config.read_location
    read_location2 = test_config._test_config.read_location2

    test_database_id = 'testdb'
    test_collection_id = 'testcoll'

    def __AssertHTTPFailureWithStatus(self, status_code, sub_status, func, *args, **kwargs):
        """Assert HTTP failure with status.

        :Parameters:
            - `status_code`: int
            - `sub_status`: int
            - `func`: function
        """
        try:
            func(*args, **kwargs)
            self.assertFalse(True, 'function should fail.')
        except errors.HTTPFailure as inst:
            self.assertEqual(inst.status_code, status_code)
            self.assertEqual(inst.sub_status, sub_status)

    @classmethod
    def setUpClass(cls):
        if (cls.masterKey == '[YOUR_KEY_HERE]' or
                cls.host == '[YOUR_GLOBAL_ENDPOINT_HERE]'):
            raise Exception(
                "You must specify your Azure DocumentDB account values for "
                "'masterKey' and 'host' at the top of this class to run the "
                "tests.")

    def setUp(self):
        self.client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})

        # Create the test database only when it's not already present
        query_iterable = self.client.QueryDatabases('SELECT * FROM root r WHERE r.id=\'' + Test_globaldb_tests.test_database_id + '\'')
        it = iter(query_iterable)

        self.test_db = next(it, None)
        if self.test_db is None:
            self.test_db = self.client.CreateDatabase({'id' : Test_globaldb_tests.test_database_id})

        # Create the test collection only when it's not already present
        query_iterable = self.client.QueryCollections(self.test_db['_self'], 'SELECT * FROM root r WHERE r.id=\'' + Test_globaldb_tests.test_collection_id + '\'')
        it = iter(query_iterable)

        self.test_coll = next(it, None)
        if self.test_coll is None:
            self.test_coll = self.client.CreateCollection(self.test_db['_self'], {'id' : Test_globaldb_tests.test_collection_id})

    def tearDown(self):
        # Delete all the documents created by the test case for clean up purposes
        docs = list(self.client.ReadDocuments(self.test_coll['_self']))
        for doc in docs:
            self.client.DeleteDocument(doc['_self'])

    def test_globaldb_read_write_endpoints(self):
        connection_policy = documents.ConnectionPolicy()
        connection_policy.EnableEndpointDiscovery = False

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        document_definition = { 'id': 'doc',
                                'name': 'sample document',
                                'key': 'value'}

        # When EnableEndpointDiscovery is False, WriteEndpoint is set to the endpoint passed while creating the client instance
        created_document = client.CreateDocument(self.test_coll['_self'], document_definition)
        self.assertEqual(client.WriteEndpoint, Test_globaldb_tests.host)

        # Delay to get these resources replicated to read location due to Eventual consistency
        time.sleep(5)

        client.ReadDocument(created_document['_self'])
        content_location = str(client.last_response_headers[http_constants.HttpHeaders.ContentLocation])

        content_location_url = urlparse(content_location)
        host_url = urlparse(Test_globaldb_tests.host)

        # When EnableEndpointDiscovery is False, ReadEndpoint is set to the endpoint passed while creating the client instance
        self.assertEqual(str(content_location_url.hostname), str(host_url.hostname))
        self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.host)

        connection_policy.EnableEndpointDiscovery = True
        document_definition['id'] = 'doc2'

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        # When EnableEndpointDiscovery is True, WriteEndpoint is set to the write endpoint
        created_document = client.CreateDocument(self.test_coll['_self'], document_definition)
        self.assertEqual(client.WriteEndpoint, Test_globaldb_tests.write_location_host)

        # Delay to get these resources replicated to read location due to Eventual consistency
        time.sleep(5)

        client.ReadDocument(created_document['_self'])
        content_location = str(client.last_response_headers[http_constants.HttpHeaders.ContentLocation])

        content_location_url = urlparse(content_location)
        write_location_url = urlparse(Test_globaldb_tests.write_location_host)

        # If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance
        self.assertEqual(str(content_location_url.hostname), str(write_location_url.hostname))
        self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.write_location_host)

    def test_globaldb_endpoint_discovery(self):
        connection_policy = documents.ConnectionPolicy()
        connection_policy.EnableEndpointDiscovery = False

        read_location_client = document_client.DocumentClient(Test_globaldb_tests.read_location_host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        document_definition = { 'id': 'doc',
                                'name': 'sample document',
                                'key': 'value'}

        # Create Document will fail for the read location client since it has EnableEndpointDiscovery set to false, and hence the request will directly go to
        # the endpoint that was used to create the client instance(which happens to be a read endpoint)
        self.__AssertHTTPFailureWithStatus(
            403,
            3,
            read_location_client.CreateDocument,
            self.test_coll['_self'],
            document_definition)

        # Query databases will pass for the read location client as it's a GET operation
        list(read_location_client.QueryDatabases({
            'query': 'SELECT * FROM root r WHERE r.id=@id',
            'parameters': [
                { 'name':'@id', 'value': self.test_db['id'] }
            ]
        }))

        connection_policy.EnableEndpointDiscovery = True
        read_location_client = document_client.DocumentClient(Test_globaldb_tests.read_location_host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        # CreateDocument call will go to the WriteEndpoint as EnableEndpointDiscovery is set to True and client will resolve the right endpoint based on the operation
        created_document = read_location_client.CreateDocument(self.test_coll['_self'], document_definition)
        self.assertEqual(created_document['id'], document_definition['id'])

    def test_globaldb_preferred_locations(self):
        connection_policy = documents.ConnectionPolicy()
        connection_policy.EnableEndpointDiscovery = True

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        document_definition = { 'id': 'doc',
                                'name': 'sample document',
                                'key': 'value'}

        created_document = client.CreateDocument(self.test_coll['_self'], document_definition)
        self.assertEqual(created_document['id'], document_definition['id'])

        # Delay to get these resources replicated to read location due to Eventual consistency
        time.sleep(5)

        client.ReadDocument(created_document['_self'])
        content_location = str(client.last_response_headers[http_constants.HttpHeaders.ContentLocation])

        content_location_url = urlparse(content_location)
        write_location_url = urlparse(Test_globaldb_tests.write_location_host)

        # If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance
        self.assertEqual(str(content_location_url.hostname), str(write_location_url.hostname))
        self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.write_location_host)

        connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        document_definition['id'] = 'doc2'
        created_document = client.CreateDocument(self.test_coll['_self'], document_definition)

        # Delay to get these resources replicated to read location due to Eventual consistency
        time.sleep(5)

        client.ReadDocument(created_document['_self'])
        content_location = str(client.last_response_headers[http_constants.HttpHeaders.ContentLocation])

        content_location_url = urlparse(content_location)
        read_location2_url = urlparse(Test_globaldb_tests.read_location2_host)

        # Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
        self.assertEqual(str(content_location_url.hostname), str(read_location2_url.hostname))
        self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.read_location2_host)

    def test_globaldb_endpoint_assignments(self):
        connection_policy = documents.ConnectionPolicy()
        connection_policy.EnableEndpointDiscovery = False

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        # When EnableEndpointDiscovery is set to False, both Read and Write Endpoints point to endpoint passed while creating the client instance
        self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.host);
        self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.host);

        connection_policy.EnableEndpointDiscovery = True
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        # If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance, write endpoint is set as expected
        self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.write_location_host);
        self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.write_location_host);

        connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        # Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
        self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.write_location_host);
        self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.read_location2_host);

    def test_globaldb_update_locations_cache(self):
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})

        writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
        readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance, write endpoint is set as expected
        self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.write_location_host)

        writable_locations = []
        readable_locations = []

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # If writable_locations and readable_locations are empty, both Read and Write Endpoints point to endpoint passed while creating the client instance
        self.assertEqual(write_endpoint, Test_globaldb_tests.host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.host)

        writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
        readable_locations = []

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # If there are no readable_locations, we use the write endpoint as ReadEndpoint
        self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.write_location_host)

        writable_locations = []
        readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}]

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # If there are no writable_locations, both Read and Write Endpoints point to endpoint passed while creating the client instance
        self.assertEqual(write_endpoint, Test_globaldb_tests.host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.host)

        writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
        readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]

        connection_policy = documents.ConnectionPolicy()
        connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
        self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.read_location2_host)

        writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]
        readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}]

        connection_policy = documents.ConnectionPolicy()
        connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]

        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # Test that the preferred location is chosen from the WriteLocations if it's not present in the ReadLocations
        self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.read_location2_host)

        writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
        readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]

        connection_policy.EnableEndpointDiscovery = False
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)

        write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)

        # If EnableEndpointDiscovery is False, both Read and Write Endpoints point to endpoint passed while creating the client instance
        self.assertEqual(write_endpoint, Test_globaldb_tests.host)
        self.assertEqual(read_endpoint, Test_globaldb_tests.host)

    def test_globaldb_locational_endpoint_parser(self):
        url_endpoint='https://contoso.documents.azure.com:443/'
        location_name='East US'

        # Creating a locational endpoint from the location name using the parser method
        locational_endpoint = global_endpoint_manager._GlobalEndpointManager.GetLocationalEndpoint(url_endpoint, location_name)
        self.assertEqual(locational_endpoint, 'https://contoso-EastUS.documents.azure.com:443/')

        url_endpoint='https://Contoso.documents.azure.com:443/'
        location_name='East US'

        # Note that the host name gets lowercased as the urlparser in Python doesn't retains the casing
        locational_endpoint = global_endpoint_manager._GlobalEndpointManager.GetLocationalEndpoint(url_endpoint, location_name)
        self.assertEqual(locational_endpoint, 'https://contoso-EastUS.documents.azure.com:443/')

    def test_globaldb_endpoint_discovery_retry_policy_mock(self):
        client = document_client.DocumentClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})

        self.OriginalExecuteFunction = retry_utility._ExecuteFunction
        retry_utility._ExecuteFunction = self._MockExecuteFunction

        self.OriginalGetDatabaseAccount = client.GetDatabaseAccount
        client.GetDatabaseAccount = self._MockGetDatabaseAccount

        max_retry_attempt_count = 10
        retry_after_in_milliseconds = 500

        endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy.Max_retry_attempt_count = max_retry_attempt_count
        endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy.Retry_after_in_milliseconds = retry_after_in_milliseconds

        document_definition = { 'id': 'doc',
                                'name': 'sample document',
                                'key': 'value'}

        self.__AssertHTTPFailureWithStatus(
            403,
            3,
            client.CreateDocument,
            self.test_coll['_self'],
            document_definition)

        retry_utility._ExecuteFunction = self.OriginalExecuteFunction

    def _MockExecuteFunction(self, function, *args, **kwargs):
        raise errors.HTTPFailure(403, "Write Forbidden", {'x-ms-substatus' : 3})

    def _MockGetDatabaseAccount(self, url_conection):
        database_account = documents.DatabaseAccount()
        return database_account

if __name__ == '__main__':
    unittest.main()


text:
@interface RACValueTransformer ()
@property (nonatomic, copy) id (^transformBlock)(id value);
@end

@implementation RACValueTransformer

#pragma mark NSValueTransformer

+ (BOOL)allowsReverseTransformation {
	return NO;
}

- (id)transformedValue:(id)value {
    return self.transformBlock(value);
}

#pragma mark API

@synthesize transformBlock;

+ (instancetype)transformerWithBlock:(id (^)(id value))block {
	NSParameterAssert(block != NULL);

	RACValueTransformer *transformer = [[self alloc] init];
	transformer.transformBlock = block;
	return transformer;
}

@end


text:
using namespace streamcon;

struct message {
	char msg_data[1024];
};

class ControlThread : public Thread
{
public:
	Stream& stream;

	ControlThread(Stream& _stream) : stream(_stream) {;}

	void Execute(void *arg) {
		while(1) {
			struct message msg;
			fgets(msg.msg_data, sizeof(message), stdin);
			msg.msg_data[strlen(msg.msg_data) - 1] = 0;
			stream.SendData((char *)&msg, sizeof(message));
			printf("Sent message: %s\n", msg.msg_data);
			stream.GetData((char *)&msg, sizeof(message));
			printf("Recieved message: %s\n", msg.msg_data);
		}
	}
};

class TestClient : public SCTPClient
{
protected:
	ControlThread *thr;
	void OnConnect(Connection &conn) throw()
		{
			std::cout << "Client is connected!\n" << std::endl;
			thr = new ControlThread(conn[0]);
			thr->Start();
		}
	void OnDisconnect() throw()
		{
			delete thr;
			std::cout << "Client is disconnected!\n" << std::endl;
		}
};

int main()
{
	TestClient client;

	while(1) {
		try {
			client.Connect("127.0.0.1", defaultPort, defaultStreams);
		} catch(Connection::ConnectionSevered) {
			std::cout << "Disconnected, retrying in 5 seconds." << std::endl;
			sleep(5);
		} catch(Connection::ConnectionRefused) {
			std::cout << "Refused, retrying in 5 seconds." << std::endl;
			sleep(5);
		}
	}

	return 0;
}


text:
import logger from "console";

export function info(config, msg) {
  if (!config.silent) logger.info(msg);
}

export function handleError(err, recover) {
  let description = err.message || err;
  if (err.name) description = `${err.name}: ${description}`;

  logger.error(description);

  // TODO should this be "err.url || (err.file && err.loc.file) || err.id"?
  if (err.url) {
    logger.error(err.url);
  }

  if (err.loc) {
    logger.error(
      `err.loc.file || err.id )} (${err.loc.line}:${err.loc.column})`
    );
  } else if (err.id) {
    logger.error(err.id);
  }

  if (err.frame) {
    logger.error(err.frame);
  } else if (err.stack) {
    logger.error(err.stack);
  }

  logger.error("");

  if (!recover) process.exit(1);
}


text:
/* TODO: introduce line-wrapping so that it never exceeds the limit. */
/* jscs: disable maximumLineLength */
'use strict';

var configData = require('./speech_client_config');
var extend = require('extend');
var gax = require('google-gax');

var SERVICE_ADDRESS = 'speech.googleapis.com';

var DEFAULT_SERVICE_PORT = 443;

var CODE_GEN_NAME_VERSION = 'gapic/0.1.0';

/**
 * The scopes needed to make gRPC calls to all of the methods defined in
 * this service.
 */
var ALL_SCOPES = [
  'https://www.googleapis.com/auth/cloud-platform'
];

/**
 * Service that implements Google Cloud Speech API.
 *
 * This will be created through a builder function which can be obtained by the module.
 * See the following example of how to initialize the module and how to access to the builder.
 * @see {@link speechApi}
 *
 * @example
 * var speechV1beta1 = require('@google-cloud/speech').v1beta1({
 *   // optional auth parameters.
 * });
 * var api = speechV1beta1.speechApi();
 *
 * @class
 */
function SpeechApi(gaxGrpc, grpcClients, opts) {
  opts = opts || {};
  var servicePath = opts.servicePath || SERVICE_ADDRESS;
  var port = opts.port || DEFAULT_SERVICE_PORT;
  var sslCreds = opts.sslCreds || null;
  var clientConfig = opts.clientConfig || {};
  var appName = opts.appName || 'gax';
  var appVersion = opts.appVersion || gax.version;

  var googleApiClient = [
    appName + '/' + appVersion,
    CODE_GEN_NAME_VERSION,
    'gax/' + gax.version,
    'nodejs/' + process.version].join(' ');

  var defaults = gaxGrpc.constructSettings(
      'google.cloud.speech.v1beta1.Speech',
      configData,
      clientConfig,
      null,
      null,
      {'x-goog-api-client': googleApiClient});

  var speechStub = gaxGrpc.createStub(
      servicePath,
      port,
      grpcClients.speechClient.google.cloud.speech.v1beta1.Speech,
      {sslCreds: sslCreds});
  var speechStubMethods = [
    'syncRecognize',
    'asyncRecognize'
  ];
  speechStubMethods.forEach(function(methodName) {
    this['_' + methodName] = gax.createApiCall(
      speechStub.then(function(speechStub) {
        return speechStub[methodName].bind(speechStub);
      }),
      defaults[methodName]);
  }.bind(this));
}

// Service calls

/**
 * Perform synchronous speech-recognition: receive results after all audio
 * has been sent and processed.
 *
 * @param {Object} request
 *   The request object that will be sent.
 * @param {Object} request.config
 *   [Required] The `config` message provides information to the recognizer
 *   that specifies how to process the request.
 *
 *   This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig}
 * @param {Object} request.audio
 *   [Required] The audio data to be recognized.
 *
 *   This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio}
 * @param {Object=} options
 *   Optional parameters. You can override the default settings for this call, e.g, timeout,
 *   retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
 * @param {function(?Error, ?Object)=} callback
 *   The function which will be called with the result of the API call.
 *
 *   The second parameter to the callback is an object representing [SyncRecognizeResponse]{@link SyncRecognizeResponse}
 * @returns {Promise} - The promise which resolves to the response object.
 *   The promise has a method named "cancel" which cancels the ongoing API call.
 *
 * @example
 *
 * var api = speechV1beta1.speechApi();
 * var config = {};
 * var audio = {};
 * var request = {
 *     config: config,
 *     audio: audio
 * };
 * api.syncRecognize(request).then(function(response) {
 *     // doThingsWith(response)
 * }).catch(function(err) {
 *     console.error(err);
 * });
 */
SpeechApi.prototype.syncRecognize = function(request, options, callback) {
  if (options instanceof Function && callback === undefined) {
    callback = options;
    options = {};
  }
  if (options === undefined) {
    options = {};
  }
  return this._syncRecognize(request, options, callback);
};

/**
 * Perform asynchronous speech-recognition: receive results via the
 * google.longrunning.Operations interface. Returns either an
 * `Operation.error` or an `Operation.response` which contains
 * an `AsyncRecognizeResponse` message.
 *
 * @param {Object} request
 *   The request object that will be sent.
 * @param {Object} request.config
 *   [Required] The `config` message provides information to the recognizer
 *   that specifies how to process the request.
 *
 *   This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig}
 * @param {Object} request.audio
 *   [Required] The audio data to be recognized.
 *
 *   This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio}
 * @param {Object=} options
 *   Optional parameters. You can override the default settings for this call, e.g, timeout,
 *   retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
 * @param {function(?Error, ?Object)=} callback
 *   The function which will be called with the result of the API call.
 *
 *   The second parameter to the callback is an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"}
 * @returns {Promise} - The promise which resolves to the response object.
 *   The promise has a method named "cancel" which cancels the ongoing API call.
 *
 * @example
 *
 * var api = speechV1beta1.speechApi();
 * var config = {};
 * var audio = {};
 * var request = {
 *     config: config,
 *     audio: audio
 * };
 * api.asyncRecognize(request).then(function(response) {
 *     // doThingsWith(response)
 * }).catch(function(err) {
 *     console.error(err);
 * });
 */
SpeechApi.prototype.asyncRecognize = function(request, options, callback) {
  if (options instanceof Function && callback === undefined) {
    callback = options;
    options = {};
  }
  if (options === undefined) {
    options = {};
  }
  return this._asyncRecognize(request, options, callback);
};

function SpeechApiBuilder(gaxGrpc) {
  if (!(this instanceof SpeechApiBuilder)) {
    return new SpeechApiBuilder(gaxGrpc);
  }

  var speechClient = gaxGrpc.load([{
    root: require('google-proto-files')('..'),
    file: 'google/cloud/speech/v1beta1/cloud_speech.proto'
  }]);
  extend(this, speechClient.google.cloud.speech.v1beta1);

  var grpcClients = {
    speechClient: speechClient
  };

  /**
   * Build a new instance of {@link SpeechApi}.
   *
   * @param {Object=} opts - The optional parameters.
   * @param {String=} opts.servicePath
   *   The domain name of the API remote host.
   * @param {number=} opts.port
   *   The port on which to connect to the remote host.
   * @param {grpc.ClientCredentials=} opts.sslCreds
   *   A ClientCredentials for use with an SSL-enabled channel.
   * @param {Object=} opts.clientConfig
   *   The customized config to build the call settings. See
   *   {@link gax.constructSettings} for the format.
   * @param {number=} opts.appName
   *   The codename of the calling service.
   * @param {String=} opts.appVersion
   *   The version of the calling service.
   */
  this.speechApi = function(opts) {
    return new SpeechApi(gaxGrpc, grpcClients, opts);
  };
  extend(this.speechApi, SpeechApi);
}
module.exports = SpeechApiBuilder;
module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS;
module.exports.ALL_SCOPES = ALL_SCOPES;


text:
"""Registry for the available models we can train."""

from gift.models import resnet
from gift.models import wide_resnet

ALL_MODELS = {}

CLASSIFICATION_MODELS = {
    'resnet': resnet.ResNet,
    'wide_resnet': wide_resnet.WideResnet
}

ALL_MODELS.update(CLASSIFICATION_MODELS)

def get_model_class(model_name):
  """Get the corresponding model class based on the model string.

  API:
  model_builder= get_model('fully_connected')
  model = model_builder(hparams, num_classes)

  Args:
    model_name: str; Name of the model, e.g. 'fully_connected'.

  Returns:
    The model architecture (a flax Model) along with its default hparams.
  Raises:
    ValueError if model_name is unrecognized.
  """
  if model_name not in ALL_MODELS.keys():
    raise ValueError('Unrecognized model: {}'.format(model_name))
  return ALL_MODELS[model_name]


text:
.. :changelog:

History
-------

0.7.5 (2018-04-XX)
------------------
* switch to much better yaml parser ``ruamel.yaml``

0.7.4 (2018-04-24)
------------------
* support and require libsass>=0.14.4 #56

0.7.3 (2018-04-17)
------------------
* allow custom importers for sass generation

0.7.2 (2018-04-16)
------------------
* allow custom function mapping for sass generation

0.7.1 (2018-04-08)
------------------
* tweak hash insertion
* correct deploy tag name

0.7.0 (2018-04-08)
------------------
* uprev
* tweak type annotations
* add hash insertion in output names to sass generation
* drop support for python 3.5

0.6.1 (2017-07-12)
------------------
* uprev
* propagate false on logs

0.6.0 (2017-04-18)
------------------
* allow node module resolution of sass imports via ``NM/``
* add size display to sass generation

0.5.2 (2017-02-03)
------------------
* using prettier arrow in logs :-)

0.5.1 (2017-01-17)
------------------
* fix ``--debug vs/ --no-debug``
* fix replace with debug
* add ``DL/`` and ``SRC/`` clever sass import prefixes

0.5.0 (2017-01-14)
------------------
* git tag check on build
* add ``replace`` argument to ``build > sass`` to allow output files to be modified
  with regex find & replace statements.
* adding support for deleting stale files defined in ``.grablib.lock``

0.4.0 (2017-01-02)
------------------
* Add ``build`` extra requirement for setup
* overhall logging
* switch ``verbosity`` cli option to ``--verbose/--quiet``
* package updates

0.3.0 (2016-12-01)
------------------
* lots of major changes
* add ``.grablib.lock``
* move to sass css compilation


text:
/*	$NetBSD: compat_mount.c,v 1.2 2007/07/18 20:10:47 dsl Exp $	*/

#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: compat_mount.c,v 1.2 2007/07/18 20:10:47 dsl Exp $");
#endif /* LIBC_SCCS and not lint */

#define __LIBC12_SOURCE__

#include <sys/types.h>
#include <sys/mount.h>

__warn_references(mount,
    "warning: reference to compatibility mount(); include <sys/mount.h> to generate correct reference")

int	mount(const char *, const char *, int, void *);
int	__mount50(const char *, const char *, int, void *, size_t);

/*
 * Convert old mount() call to new calling convention
 * The kernel will treat length 0 as 'default for the fs'.
 * We need to throw away the +ve response for MNT_GETARGS.
 */
int
mount(const char *type, const char *dir, int flags, void *data)
{
	return __mount50(type, dir, flags, data, 0) == -1 ? -1 : 0;
}