text:
{-# LANGUAGE FlexibleContexts         #-}

module Language.Haskell.Liquid.Bare.Misc
  ( joinVar
  , mkVarExpr
  , vmap
  , runMapTyVars
  , matchKindArgs
  , symbolRTyVar
  , simpleSymbolVar
  , hasBoolResult
  , isKind
  ) where

import           Prelude                               hiding (error)

import           Liquid.GHC.API       as Ghc  hiding (Located, showPpr)

import           Control.Monad.Except                  (MonadError, throwError)
import           Control.Monad.State
import qualified Data.Maybe                            as Mb --(fromMaybe, isNothing)

import qualified Text.PrettyPrint.HughesPJ             as PJ
import qualified Data.List                             as L
import qualified Language.Fixpoint.Types as F
import           Liquid.GHC.Misc
import           Language.Haskell.Liquid.Types.RefType
import           Language.Haskell.Liquid.Types.Types

-- import           Language.Haskell.Liquid.Bare.Env

-- import           Language.Haskell.Liquid.WiredIn       (dcPrefix)

-- TODO: This is where unsorted stuff is for now. Find proper places for what follows.

{-
-- WTF does this function do?
makeSymbols :: (Id -> Bool) -> [Id] -> [F.Symbol] -> BareM [(F.Symbol, Var)]
makeSymbols f vs xs
  = do svs <- M.toList <$> gets varEnv
       return $ L.nub ([ (x,v') | (x,v) <- svs, x `elem` xs, let (v',_,_) = joinVar vs (v,x,x)]
                   ++  [ (F.symbol v, v) | v <- vs, f v, isDataConId v, hasBasicArgs $ varType v ])
    where
      -- arguments should be basic so that autogenerated singleton types are well formed
      hasBasicArgs (ForAllTy _ t) = hasBasicArgs t
      hasBasicArgs (FunTy _ tx t)   = isBaseTy tx && hasBasicArgs t
      hasBasicArgs _              = True

-}

{-
HEAD
freeSymbols :: (F.Reftable r, F.Reftable r1, F.Reftable r2, TyConable c, TyConable c1, TyConable c2)
            => [F.Symbol]
            -> [(a1, Located (RType c2 tv2 r2))]
            -> [(a, Located (RType c1 tv1 r1))]
            -> [Located (RType c tv r)]
            -> [LocSymbol]
freeSymbols xs' xts yts ivs =  [ lx | lx <- Misc.sortNub $ zs ++ zs' ++ zs'' , not (M.member (val lx) knownM) ]
  where
    knownM                  = M.fromList [ (x, ()) | x <- xs' ]
    zs                      = concatMap freeSyms (snd <$> xts)
    zs'                     = concatMap freeSyms (snd <$> yts)
    zs''                    = concatMap freeSyms ivs

-------------------------------------------------------------------------------
freeSyms :: (F.Reftable r, TyConable c) => Located (RType c tv r) -> [LocSymbol]
-------------------------------------------------------------------------------
freeSyms ty    = [ F.atLoc ty x | x <- tySyms ]
  where
    tySyms     = Misc.sortNub $ concat $ efoldReft (\_ _ -> True) False (\_ _ -> []) (const []) (const ()) f (const id) F.emptySEnv [] (val ty)
    f γ _ r xs = let F.Reft (v, _) = F.toReft r in
                 [ x | x <- F.syms r, x /= v, not (x `F.memberSEnv` γ)] : xs

--- ABOVE IS THE T1773 STUFF
--- BELOW IS THE develop-classes STUFF

-- freeSymbols :: (F.Reftable r, F.Reftable r1, F.Reftable r2, TyConable c, TyConable c1, TyConable c2)
--             => [F.Symbol]
--             -> [(a1, Located (RType c2 tv2 r2))]
--             -> [(a, Located (RType c1 tv1 r1))]
--             -> [(Located (RType c tv r))]
--             -> [LocSymbol]
-- freeSymbols xs' xts yts ivs =  [ lx | lx <- Misc.sortNub $ zs ++ zs' ++ zs'' , not (M.member (val lx) knownM) ]
--   where
--     knownM                  = M.fromList [ (x, ()) | x <- xs' ]
--     zs                      = concatMap freeSyms (snd <$> xts)
--     zs'                     = concatMap freeSyms (snd <$> yts)
--     zs''                    = concatMap freeSyms ivs

-- freeSyms :: (F.Reftable r, TyConable c) => Located (RType c tv r) -> [LocSymbol]
-- freeSyms ty    = [ F.atLoc ty x | x <- tySyms ]
--   where
--     tySyms     = Misc.sortNub $ concat $ efoldReft (\_ _ -> True) False (\_ _ -> []) (\_ -> []) (const ()) f (const id) F.emptySEnv [] (val ty)
--     f γ _ r xs = let F.Reft (v, _) = F.toReft r in
--                  [ x | x <- F.syms r, x /= v, not (x `F.memberSEnv` γ)] : xs

-}
-------------------------------------------------------------------------------
-- Renaming Type Variables in Haskell Signatures ------------------------------
-------------------------------------------------------------------------------
runMapTyVars :: Bool -> Type -> SpecType -> (PJ.Doc -> PJ.Doc -> Error) -> Either Error MapTyVarST
runMapTyVars allowTC τ t err = execStateT (mapTyVars allowTC τ t) (MTVST [] err)

data MapTyVarST = MTVST
  { vmap   :: [(Var, RTyVar)]
  , errmsg :: PJ.Doc -> PJ.Doc -> Error
  }

mapTyVars :: Bool -> Type -> SpecType -> StateT MapTyVarST (Either Error) ()
mapTyVars allowTC t (RImpF _ _ _ t' _)
   = mapTyVars allowTC t t'
mapTyVars allowTC (FunTy { ft_arg = τ, ft_res = τ'}) t
  | isErasable τ
  = mapTyVars allowTC τ' t
  where isErasable = if allowTC then isEmbeddedDictType else isClassPred
mapTyVars allowTC (FunTy { ft_arg = τ, ft_res = τ'}) (RFun _ _ t t' _)
   = mapTyVars allowTC τ t >> mapTyVars allowTC τ' t'
mapTyVars allowTC τ (RAllT _ t _)
  = mapTyVars allowTC τ t
mapTyVars allowTC (TyConApp _ τs) (RApp _ ts _ _)
   = zipWithM_ (mapTyVars allowTC) τs (matchKindArgs' τs ts)
mapTyVars _ (TyVarTy α) (RVar a _)
   = do s  <- get
        s' <- mapTyRVar α a s
        put s'
mapTyVars allowTC τ (RAllP _ t)
  = mapTyVars allowTC τ t
mapTyVars allowTC τ (RAllE _ _ t)
  = mapTyVars allowTC τ t
mapTyVars allowTC τ (RRTy _ _ _ t)
  = mapTyVars allowTC τ t
mapTyVars allowTC τ (REx _ _ t)
  = mapTyVars allowTC τ t
mapTyVars _ _ (RExprArg _)
  = return ()
mapTyVars allowTC (AppTy τ τ') (RAppTy t t' _)
  = do  mapTyVars allowTC τ t
        mapTyVars allowTC τ' t'
mapTyVars _ _ (RHole _)
  = return ()
mapTyVars _ k _ | isKind k
  = return ()
mapTyVars allowTC (ForAllTy _ τ) t
  = mapTyVars allowTC τ t
mapTyVars _ hsT lqT
  = do err <- gets errmsg
       throwError (err (F.pprint hsT) (F.pprint lqT))

isKind :: Kind -> Bool
isKind = classifiesTypeWithValues -- TODO:GHC-863 isStarKind k --  typeKind k

mapTyRVar :: MonadError Error m
          => Var -> RTyVar -> MapTyVarST -> m MapTyVarST
mapTyRVar α a s@(MTVST αas err)
  = case lookup α αas of
      Just a' | a == a'   -> return s
              | otherwise -> throwError (err (F.pprint a) (F.pprint a'))
      Nothing             -> return $ MTVST ((α,a):αas) err

matchKindArgs' :: [Type] -> [SpecType] -> [SpecType]
matchKindArgs' ts1' = reverse . go (reverse ts1') . reverse
  where
    go (_:ts1) (t2:ts2) = t2:go ts1 ts2
    go ts      []       | all isKind ts
                        = (ofType <$> ts) :: [SpecType]
    go _       ts       = ts

matchKindArgs :: [SpecType] -> [SpecType] -> [SpecType]
matchKindArgs ts1' = reverse . go (reverse ts1') . reverse
  where
    go (_:ts1) (t2:ts2) = t2:go ts1 ts2
    go ts      []       = ts
    go _       ts       = ts

mkVarExpr :: Id -> F.Expr
mkVarExpr v
  | isFunVar v = F.mkEApp (varFunSymbol v) []
  | otherwise  = F.eVar v -- EVar (symbol v)

varFunSymbol :: Id -> Located F.Symbol
varFunSymbol = dummyLoc . F.symbol . idDataCon

isFunVar :: Id -> Bool
isFunVar v   = isDataConId v && not (null αs) && Mb.isNothing tf
  where
    (αs, t)  = splitForAllTys $ varType v
    tf       = splitFunTy_maybe t

-- the Vars we lookup in GHC don't always have the same tyvars as the Vars
-- we're given, so return the original var when possible.
-- see tests/pos/ResolvePred.hs for an example
joinVar :: [Var] -> (Var, s, t) -> (Var, s, t)
joinVar vs (v,s,t) = case L.find ((== showPpr v) . showPpr) vs of
                       Just v' -> (v',s,t)
                       Nothing -> (v,s,t)

simpleSymbolVar :: Var -> F.Symbol
simpleSymbolVar  = dropModuleNames . F.symbol . showPpr . getName

hasBoolResult :: Type -> Bool
hasBoolResult (ForAllTy _ t) = hasBoolResult t
hasBoolResult (FunTy { ft_res = t} )    | eqType boolTy t = True
hasBoolResult (FunTy { ft_res = t} )    = hasBoolResult t
hasBoolResult _              = False


text:
//---------------------------------------------------------------------
// <copyright file="ODataDeltaKind.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Core
{
    ///
    /// Delta kinds
    ///
    internal enum ODataDeltaKind
    {
        /// None delta
        None,

        /// Delta feed
        Feed,

        /// Delta entry
        Entry,

        /// Delta deleted entry
        DeletedEntry,

        /// Delta link
        Link,

        /// Delta deleted link
        DeletedLink,
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ezbake.data.elastic.common.pojo;

import org.apache.thrift.TException;

import ezbake.data.elastic.thrift.DateHistogramFacet;

public final class DateHistogramFacetPojo {
    private DateFieldPojo field;
    private DateIntervalPojo interval;
    private Integer factor; // optional
    private Short post_zone_hours; // optional
    private Short pre_zone_hours; // optional

    public static DateHistogramFacetPojo fromThrift(DateHistogramFacet thrift) {
        if (thrift == null) {
            return null;
        }

        final DateHistogramFacetPojo pojo = new DateHistogramFacetPojo();
        pojo.field = DateFieldPojo.fromThrift(thrift.getField());
        pojo.interval = DateIntervalPojo.fromThrift(thrift.getInterval());

        if (thrift.isSetFactor()) {
            pojo.factor = thrift.getFactor();
        }

        if (thrift.isSetPost_zone_hours()) {
            pojo.post_zone_hours = thrift.getPost_zone_hours();
        }

        if (thrift.isSetPre_zone_hours()) {
            pojo.pre_zone_hours = thrift.getPre_zone_hours();
        }

        return pojo;
    }

    public static DateHistogramFacet toThrift(DateHistogramFacetPojo pojo) throws TException {
        if (pojo == null) {
            return null;
        }

        final DateHistogramFacet thrift = new DateHistogramFacet();
        thrift.setField(DateFieldPojo.toThrift(pojo.field));
        thrift.setInterval(DateIntervalPojo.toThrift(pojo.interval));

        if (pojo.factor != null) {
            thrift.setFactor(pojo.factor);
        }

        if (pojo.post_zone_hours != null) {
            thrift.setPost_zone_hours(pojo.post_zone_hours);
        }

        if (pojo.pre_zone_hours != null) {
            thrift.setPre_zone_hours(pojo.pre_zone_hours);
        }

        thrift.validate();

        return thrift;
    }
}


text:
"""
This module implements the engine which controls
the Scheduler, Downloader and Spider.
"""
import time

from threaded_spider import logger
from threaded_spider.basic.threadpool import ThreadPool
from threaded_spider.http import Request, Response
from threaded_spider.core.downloader import Downloader
from threaded_spider.core.scheduler import Scheduler
from threaded_spider.core.extracter import Extracter

class Engine(object):

    def __init__(self, crawler):
        self.crawler = crawler
        self.settings = crawler.settings
        self.downloader = Downloader(crawler)
        self.scheduler = Scheduler()
        self.requests_to_be_scheduled = []
        self.extracter = Extracter(crawler)
        self.thread_pool = ThreadPool(minthreads=self.settings.getint('THREAD_NUM', 7),
                                      maxthreads=self.settings.getint('THREAD_NUM', 7),
                                      name='engine_threadpool')
        self.spider = None
        self.running = False

    def start(self):
        """Start the execution engine"""

        assert not self.running, 'Engine already running.'

        self.start_time = time.time()
        self.running = True
        self.thread_pool.start()

    def stop(self, force=False):
        """Stop the execution engine gracefully"""

        assert self.running, 'Engine not running.'
        logger.info('@engine, stopping...')
        # Stop the threadpool and close spider.
        self.thread_pool.stop()
        self.thread_pool.dumpStats()
        self.detach_spider()

        self.running = False
        logger.info('@engine, stopped.')
        logger.info('@engine, unscheduled: %s' % len(self.requests_to_be_scheduled))
        logger.debug('@engine, unscheduled: %r' % self.requests_to_be_scheduled)
        logger.info('@engine, in scheduler: %s' % self.scheduler.mq.qsize())
        logger.debug('@engine, in scheduler: %r' % self.scheduler.mq.queue)
        logger.info('@engine, in downloader: %s' % self.downloader.has_pending_download())

    def attach_spider(self, spider, start_requests=()):
        """Attach a spider to the engine."""
        logger.info('@engine, Spider attached to engine.', spider=spider)
        self.spider = spider
        if callable(start_requests):
            start_requests = start_requests()
        self._start_requests = iter(start_requests)

        self.scheduler.attach_spider(spider)
        self.extracter.attach_spider(spider)

    def detach_spider(self):
        self.extracter.detach_spider()

    def process_next_request(self, spider):
        self._process_next_request(spider)

    def _process_next_request(self, spider):
        """Grab a request object from scheduler and then download a
        response object which is parsed by the spider.
        """
        request = self._process_next_request_from_scheduler(spider)

        if not request and self._start_requests:
            try:
                request = next(self._start_requests)
            except StopIteration:
                self._start_requests = None
            except Exception:
                logger.error(why='@engine, Fail to obtain request from start requests.',
                             spider=spider)
            else:
                logger.info('@engne, schedule a request from start_urls', spider=spider)
                self._schedule(request, spider)

        if self.spider_is_idle(spider):
            logger.info('@engine, Spider is idle.', spider=spider)
            self._spider_idle(spider)

    def _process_next_request_from_scheduler(self, spider):
        self._schedule2()
        request = self.scheduler.next_request()
        if not request:
            return

        def handle_download_output(succeed, result):
            self._handle_download_output(result, request, spider)

        # Error raised by tasks in the thread pool will be logged as
        # `Unhandled Error` by default and not break down the main thread.
        self.call_in_thread_with_callback(handle_download_output, self.download,
                                          request, spider)
        return request

    # Sub-threads use this to schedule later instead of
    # operating on the scheduler queue directly.
    def schedule_later(self, request, spider):
        self.requests_to_be_scheduled.append((request, spider))

    # Main thread use two below to put request to the scheduler queue.
    def _schedule(self, request, spider):
        self.scheduler.enqueue_request(request)

    def _schedule2(self):
        while self.requests_to_be_scheduled:
            try:
                item = self.requests_to_be_scheduled[0]
                self.requests_to_be_scheduled.remove(item)
            except IndexError:
                return

            request, spider = item
            self.scheduler.enqueue_request(request)

    def spider_is_idle(self, spider):
        # Judge whether there is any request to be processed.
        has_unscheduled_request = len(self.requests_to_be_scheduled)
        has_pending_request = self.scheduler.has_pending_requests()
        has_pending_download = self.downloader.has_pending_download()
        has_pending_response = self.extracter.has_pending_response()
        has_pending_task = self.thread_pool.has_pending_task()
        return not any((has_unscheduled_request, has_pending_request,
                        has_pending_download, has_pending_response,
                        has_pending_task))

    def _spider_idle(self, spider):
        self.crawler.stop()

    def call_in_thread(self, func, *args, **kws):
        self.thread_pool.callInThread(func, *args, **kws)

    def call_in_thread_with_callback(self, onResult, func, *args, **kws):
        self.thread_pool.callInThreadWithCallback(onResult, func, *args, **kws)

    def download(self, request, spider):
        if self.crawler.stopped:
                # Immediatelly exit once the crawler receive the stop signal
                logger.warn('Force to exit from downloader when crawler stop. '
                            'Request: %s' % request, spider=spider)
                return

        resp = self.downloader.fetch(request, spider)
        return resp

    def _handle_download_output(self, response, request, spider):
        assert isinstance(response, (Request, Response, type(None))), response
        if isinstance(response, Request):
            self.schedule_later(response, spider)
            return
        elif isinstance(response, type(None)):
            return

        if self.crawler.stopped:
                # Immediatelly exit once the crawler receive the stop signal
                logger.warn('Force to exit from extracter when crawler stop. '
                            'Response: %s' % response, spider=spider)
                return

        self.extracter.enter_extracter(response, request, spider)

        # TODO: Store the items after parsing.


text:
package net.mcft.copy.betterstorage.api.stand;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;

public abstract class ArmorStandEquipHandler implements Comparable<ArmorStandEquipHandler> {

	public final String id;
	public final EnumArmorStandRegion region;
	public final int priority;

	public ArmorStandEquipHandler(String id, EnumArmorStandRegion region, int priority) {
		this.id = id;
		this.region = region;
		this.priority = priority;
	}

	/** Returns if the item (non-null) is valid and can
	 *  be put on the armor stand and equipped by players. */
	public abstract boolean isValidItem(EntityPlayer player, ItemStack item);

	/** Returns the player's equipment for this handler, null if none. */
	public abstract ItemStack getEquipment(EntityPlayer player);

	/** Returns if the player's equipment can be changed to this item (can be null). */
	public abstract boolean canSetEquipment(EntityPlayer player, ItemStack item);

	/** Sets the player's equipment to this item (can be null). */
	public abstract void setEquipment(EntityPlayer player, ItemStack item);

	@Override
	public int compareTo(ArmorStandEquipHandler other) {
		return (other.priority - priority);
	}

}


text:
<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use yii\bootstrap\Modal;
use \kartik\icons\Icon;
use \yii\helpers\Url;

use kartik\builder\Form;
use kartik\widgets\DepDrop;
use kartik\select2\Select2;
use kartik\widgets\DatePicker;
use kartik\widgets\TimePicker;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var searchModel app\models\enrollmentSearch */
/* @var campaign integer */

$this->assetBundles['Consultation'] = new app\assets\AppAsset();
$this->assetBundles['Consultation']->js = [
    'scripts/ConsultationView/Functions.js',
    'scripts/ConsultationView/Click.js'
];

$this->title = Yii::t('app', 'Consultations');
$this->params['breadcrumbs'][] = $this->title;
$this->params['button'] =
        Html::a(Yii::t('app', 'Create Consultation'), ['create', 'cid' => $campaign], ['class' => 'btn btn-success navbar-btn']);
$this->params['campaign'] = $campaign;
?>

    <?=Html::a(Icon::show('file-pdf-o', [], Icon::FA).yii::t('app','All Prescriptions...'),['reports/multiple-prescriptions', 'cid'=>$campaign],
         ['target'=>'_blank', 'class' => 'btn btn-primary pull-right']) ?>

    <?=Html::a(Icon::show('file-pdf-o', [], Icon::FA).yii::t('app','All Letters/Anamnese...'),'#',
         ['id'=>'selectLetterOptions', 'class' => 'btn btn-primary pull-right']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'rowOptions' => function ($model, $key, $index, $column){
                    $c = $this->params['campaign'];
                    return ['consultation-key'=>$model->getTerms()->where("campaign = :cid",["cid"=>$c])->one()->getConsults()->one()->id];
                },
        'columns' => [
            ['class'=> kartik\grid\DataColumn::className(),
                'attribute'=>'student',
                'header'=> Yii::t('app', 'Student'),
                'content' => function ($model, $key, $index, $column){
                    return $model->getStudents()->one()->name;
                }
            ],
            ['class'=> kartik\grid\DataColumn::className(),
                'attribute'=>'classroom',
                'options' => ['style' => 'width:20%'],
                'header'=> Yii::t('app', 'Classroom'),
                'content' => function ($model, $key, $index, $column){
                    return $model->getClassrooms()->one()->name;
                }
            ],

            ['class' => \kartik\grid\BooleanColumn::className(),
                'contentOptions' => ['class' => 'attendedClick cursor-pointer'],
                'header'=> Yii::t('app', 'Attended'),
                'value' => function ($model, $key, $index, $column){
                /* @var $model \app\models\enrollment */
                    $c = $this->params['campaign'];
                    return $model->getTerms()->where("campaign = :cid",["cid"=>$c])->one()->getConsults()->one()->attended;
                },
                'vAlign' => 'middle',
            ],
            ['class' => \kartik\grid\BooleanColumn::className(),
                'contentOptions' => ['class' => 'deliveredClick cursor-pointer'],
                'header'=> Yii::t('app', 'Delivered'),
                'value' => function ($model, $key, $index, $column){
                /* @var $model \app\models\enrollment */
                    $c = $this->params['campaign'];
                    return $model->getTerms()->where("campaign = :cid",["cid"=>$c])->one()->getConsults()->one()->delivered;
                },
                'vAlign' => 'middle',
            ],
            [
                'class' => kartik\grid\DataColumn::className(),
                'label' => yii::t('app', 'Print'),
                'options' => ['style' => 'width:10%'],
                'content' => function($model, $key, $index, $column) {
                    /* @var $model \app\models\enrollment */
                    $cid = $this->params['campaign'];
                    $hemoglobin = $model->getTerms()->where("campaign = :cid",["cid"=>$cid])->one()->getHemoglobins()->where("sample = 1")->one();
                    $sid = $hemoglobin->agreedTerm->enrollments->student;
                    $eid = $hemoglobin->agreedTerm->enrollment;
                    $link = $hemoglobin->isAnemic()
                            ? Html::a(Icon::show('file-text-o', [], Icon::FA).yii::t("app","Prescription"),Url::toRoute(['reports/prescription', 'cid'=>$cid, 'eid' => $model->id]))
                            ."
".Html::a(Icon::show('envelope-o', [], Icon::FA).yii::t('app', 'Letter'), Url::toRoute(['reports/consultation-letter', 'sid' => $sid]))
                            ."
".Html::a(Icon::show('file-text-o', [], Icon::FA).yii::t('app', 'Anamnese'),Url::toRoute(['reports/anamnese','cid'=>$cid, 'eid' => $eid]))
                            : "----------";
                    return $link;
                }
            ]
        ],
        'pjax' => true,
        'pjaxSettings' => [
            'neverTimeout' => true,
            'options' => [
                'id' => 'pjaxConsults'
            ],
        ],
    ]); ?>

<?php
    Modal::begin([
        'size'=>Modal::SIZE_SMALL,
        'id'=>'selectLetterOptionsModal',
        'closeButton'=>false
    ]);
    echo "

";
    //echo Html::label(yii::t('app','School'));
    echo Html::beginForm(['reports/letter-and-anamnese', 'cid'=>$campaign],'POST',['id'=>'form-consultation-letter', 'class'=>'form-vertical']);
    echo Form::widget([
        'formName' => 'consultation-letter-form',
        'columns'=>1,
        'attributes' => [
            'consult-date' => [
                'label'=>yii::t('app', 'Consult Date'),
                'type' => Form::INPUT_WIDGET,
                'widgetClass' => DatePicker::className(),
                'options'=>[
                    'pluginOptions' => ['format' => 'dd/mm/yyyy'],
                ],
            ],
            'consult-time' => [
                'label' => yii::t('app', 'Consult Time'),
                'type' => Form::INPUT_WIDGET,
                'widgetClass' => TimePicker::className(),
                'options'=>[
                    'pluginOptions' =>[
                        'defaultTime' => 'false'
                    ]
                ]
            ],
            'consult-location' => [
                'label'=>yii::t('app', 'Consult Location'),
                'type' => Form::INPUT_TEXT,
            ],
            'actions'=>[
                'type'=>Form::INPUT_RAW,
                'value'=>'
' .
                    Html::button(Yii::t('app', 'Cancel'), ['data-dismiss'=>'modal', 'class'=>'btn btn-danger pull-left btn-actions']) . ' ' .
                    Html::button(Yii::t('app','Generate'), ['id'=>'submit-consultation-letter', 'type'=>'button', 'class'=>'btn btn-success pull-right btn-actions']) .
                '
',
            ],
        ]
    ]);
    echo Html::endForm();
    echo "
";
    echo "
";
    Modal::end();
?>

<?php
    Modal::begin([
        'size' => Modal::SIZE_SMALL,
        'id' => 'updateAttendedModal',
        'closeButton'=>false,
    ]);
    echo "

";
    echo Yii::t("app","Are you sure you want to update?");
    echo "
";
    echo "
";
    echo "
";
    echo Html::button(Yii::t('app', 'Cancel'), ['data-dismiss'=>"modal", 'class' => 'btn btn-danger pull-left'])
        .Html::button(Yii::t('app', 'Confirm'), ['id'=>'updateAttendedModal-confirm', 'class' => 'btn btn-success pull-right']);
    echo "
";
    echo "
";
    echo "

";
    Modal::end();

    Modal::begin([
        'size' => Modal::SIZE_SMALL,
        'id' => 'updateDeliveredModal',
        'closeButton'=>false,
    ]);
    echo "

";
    echo Yii::t("app","Are you sure you want to update?");
    echo "
";
    echo "
";
    echo "
";
    echo Html::button(Yii::t('app', 'Cancel'), ['data-dismiss'=>"modal", 'class' => 'btn btn-danger pull-left'])
        .Html::button(Yii::t('app', 'Confirm'), ['id'=>'updateDeliveredModal-confirm', 'class' => 'btn btn-success pull-right']);
    echo "
";
    echo "
";
    echo "

";
    Modal::end();
?>


text:
FROM ruby:2.5 AS base
RUN apt-get update -qq && apt-get install -y build-essential libcurl4-openssl-dev libpq-dev nodejs
RUN mkdir /grapple-demo
WORKDIR /grapple-demo
COPY Gemfile* /grapple-demo/

# Development server
FROM base AS development
RUN bundle install
COPY . /grapple-demo
ENTRYPOINT ["bin/start"]
CMD ["bin/rails", "server"]

# Production/staging Releases
FROM base AS release
RUN bundle config --global frozen 1 \
	&& bundle install --without development test -j4 --retry 3 \
	# Remove unneeded files (cached *.gem, *.o, *.c)
	&& rm -rf /usr/local/bundle/cache/*.gem \
	&& find /usr/local/bundle/gems/ -name "*.c" -delete \
	&& find /usr/local/bundle/gems/ -name "*.o" -delete

# Add the Rails app
COPY . /grapple-demo

# Precompile assets
RUN RAILS_ENV=production RAILS_RELATIVE_URL_ROOT=/grapple/ bundle exec rake assets:precompile

# Remove folders not needed in resulting image
RUN rm -rf node_modules test /grapple-demo/tmp

ENTRYPOINT ["bin/start"]
CMD ["bin/run"]


text:
#ifndef RMSPROPUPDATER_H
#define RMSPROPUPDATER_H
#include <shogun/optimization/DescendUpdaterWithCorrection.h>
#include <shogun/optimization/LearningRate.h>
namespace shogun
{
/** @brief The class implements the RmsProp method.
 *
 *  \f[
 *	\begin{array}{l}
 *	g_\theta=(1-\lambda){(\frac{ \partial f(\cdot) }{\partial \theta })}^2+\lambda g_\theta\\
 *	d_\theta=\alpha\frac{1}{\sqrt{g_\theta+\epsilon}}\frac{ \partial f(\cdot) }{\partial \theta }\\
 *	\end{array}
 *	\f]
 *
 * where
 * \f$ \frac{ \partial f(\cdot) }{\partial \theta } \f$ is a negative descend direction (eg, gradient) wrt \f$\theta\f$,
 * \f$\lambda\f$ is a decay factor,
 * \f$\epsilon\f$ is used to avoid dividing by 0,
 * \f$ \alpha \f$ is a build-in learning rate
 * \f$d_\theta\f$ is a corrected negative descend direction.
 *
 * where \f$\lambda\f$ is a learning rate.
 */
class RmsPropUpdater: public DescendUpdaterWithCorrection
{
public:
	/* Constructor */
	RmsPropUpdater();

	/** Parameterized Constructor
	 *
	 * @param learning_rate learning_rate
	 * @param epsilon epsilon
	 * @param decay_factor decay_factor
	 */
	RmsPropUpdater(float64_t learning_rate,float64_t epsilon,float64_t decay_factor);

	/* Destructor */
	virtual ~RmsPropUpdater();

	/** Set learning rate
	 *
	 * @param learning_rate learning rate
	 */
	virtual void set_learning_rate(float64_t learning_rate);

	/** Set epsilon
	 *
	 * @param epsilon epsilon
	 */
	virtual void set_epsilon(float64_t epsilon);

	/** Set decay_factor
	 *
	 * @param decay_factor decay factor
	 */
	virtual void set_decay_factor(float64_t decay_factor);

	/** Update a context object to store mutable variables
	 *
	 * This method will be called by
	 * FirstOrderMinimizer::save_to_context()
	 *
	 * @param context a context object
	 */
	virtual void update_context(CMinimizerContext* context);

	/** Return a context object which stores mutable variables
	 * Usually it is used in serialization.
	 *
	 * This method will be called by
	 * FirstOrderMinimizer::load_from_context(CMinimizerContext* context)
	 *
	 * @return a context object
	 */
	virtual void load_from_context(CMinimizerContext* context);

	/** Update the target variable based on the given negative descend direction
	 *
	 * Note that this method will update the target variable in place.
	 * This method will be called by FirstOrderMinimizer::minimize()
	 *
	 * @param variable_reference a reference of the target variable
	 * @param raw_negative_descend_direction the negative descend direction given the current value
	 * @param learning_rate learning rate
	 */
	virtual void update_variable(SGVector<float64_t> variable_reference,
		SGVector<float64_t> raw_negative_descend_direction, float64_t learning_rate);
protected:
	/** Get the negative descend direction given current variable  and gradient
	 *
	 * It will be called at update_variable()
	 *
	 * @param variable current variable (eg, \f$\theta\f$)
	 * @param gradient current gradient (eg, \f$ \frac{ \partial f(\cdot) }{\partial \theta }\f$)
	 * @param idx the index of the variable
	 * @param learning_rate learning rate (for RmsProp, learning_rate is NOT used because there is a build-in learning_rate)
	 *
	 * @return negative descend direction (that is, \f$d_\theta\f$)
	 */
	virtual float64_t get_negative_descend_direction(float64_t variable,
		float64_t gradient, index_t idx, float64_t learning_rate);

	/** learning_rate \f$\alpha\f$ at iteration */
	float64_t m_build_in_learning_rate;

	/** \f$ \epsilon \f$ */
	float64_t m_epsilon;

	/** decay term \f$ \lambda \f$ */
	float64_t m_decay_factor;

	/** \f$ g_\theta \f$ */
	SGVector<float64_t> m_gradient_accuracy;
private:
	/**  Init */
	void init();
};

}
#endif


text:
package org.apache.shindig.common.servlet;

import junit.framework.TestCase;

public class UserAgentTest extends TestCase {
  private UserAgent getUaEntry(String version) {
    return new UserAgent(UserAgent.Browser.OTHER, version);
  }

  public void testVersionNumberParsingStandard() {
    assertEquals(3D, getUaEntry("3").getVersionNumber());
  }

  public void testVersionNumberParsingStandardDecimal() {
    assertEquals(3.1415, getUaEntry("3.1415").getVersionNumber());
  }

  public void testVersionNumberParsingMultiPart() {
    assertEquals(3.1, getUaEntry("3.1.5").getVersionNumber());
  }

  public void testVersionNumberParsingAlphaSuffix() {
    assertEquals(4.5, getUaEntry("4.5beta2").getVersionNumber());
  }

  public void testVersionNumberParsingEmbeddedInTheMiddle() {
    assertEquals(1.5, getUaEntry("beta 1.5 rc 5").getVersionNumber());
  }
}


text:
@interface SubSystemThree : NSObject

- (void)MethodThree;

@end


text:
release_hdr := $(shell sh -c './mkreleasehdr.sh')
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')
OPTIMIZATION?=
DEPENDENCY_TARGETS=hiredis linenoise leveldb

# Default settings
STD=-std=c99 -pedantic
WARN=-Wall
OPT=$(OPTIMIZATION)

PREFIX?=/usr/local
INSTALL_BIN=$(PREFIX)/bin
INSTALL=install

# Default allocator
ifeq ($(uname_S),Linux)
	MALLOC=jemalloc
else
	MALLOC=libc
endif

# Backwards compatibility for selecting an allocator
ifeq ($(USE_TCMALLOC),yes)
	MALLOC=tcmalloc
endif

ifeq ($(USE_TCMALLOC_MINIMAL),yes)
	MALLOC=tcmalloc_minimal
endif

ifeq ($(USE_JEMALLOC),yes)
	MALLOC=jemalloc
endif

# Override default settings if possible
-include .make-settings

MALLOC=libc
FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS)
FINAL_LDFLAGS=$(LDFLAGS) $(REDIS_LDFLAGS) $(DEBUG)
FINAL_LIBS=-lm -lstdc++
DEBUG=-g -ggdb

ifeq ($(uname_S),SunOS)
	INSTALL=cp -pf
	FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6
	FINAL_LIBS+= -ldl -lnsl -lsocket -lpthread
else ifeq ($(uname_S),Darwin)

else
	FINAL_LDFLAGS+= -rdynamic
	FINAL_LIBS+= -pthread
endif

# Include paths to dependencies
FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/leveldb/include

ifeq ($(MALLOC),tcmalloc)
	FINAL_CFLAGS+= -DUSE_TCMALLOC
	FINAL_LIBS+= -ltcmalloc
endif

ifeq ($(MALLOC),tcmalloc_minimal)
	FINAL_CFLAGS+= -DUSE_TCMALLOC
	FINAL_LIBS+= -ltcmalloc_minimal
endif

ifeq ($(MALLOC),jemalloc)
	DEPENDENCY_TARGETS+= jemalloc
	FINAL_CFLAGS+= -DUSE_JEMALLOC -I../deps/jemalloc/include
	FINAL_LIBS+= ../deps/jemalloc/lib/libjemalloc.a -ldl
endif

REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS)
REDIS_LD=$(QUIET_LINK)$(CC) $(FINAL_LDFLAGS)
REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL)

CCCOLOR="\033[34m"
LINKCOLOR="\033[34;1m"
SRCCOLOR="\033[33m"
BINCOLOR="\033[37;1m"
MAKECOLOR="\033[32;1m"
ENDCOLOR="\033[0m"
define V
endef
ifndef V
#QUIET_CC = @printf '    %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2;
#QUIET_LINK = @printf '    %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2;
#QUIET_INSTALL = @printf '    %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2;
endif

REDIS_SERVER_NAME=redis-server
REDIS_SERVER_OBJ=adlist.o ae.o anet.o dict.o ds.o redis.o sds.o zmalloc.o sha1.o release.o networking.o util.o object.o db.o config.o multi.o debug.o syncio.o endianconv.o slowlog.o rand.o memtest.o crc64.o setproctitle.o replication.o
REDIS_CLI_NAME=redis-cli
REDIS_CLI_OBJ=anet.o sds.o adlist.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o
REDIS_BENCHMARK_NAME=redis-benchmark
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o sds.o adlist.o zmalloc.o redis-benchmark.o

all: $(REDIS_SERVER_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME)
	@echo ""
	@echo "Hint: To run 'make test' is a good idea ;)"
	@echo ""

.PHONY: all

# Deps (use make dep to generate this)
include Makefile.dep

dep:
	$(REDIS_CC) -MM *.c > Makefile.dep

.PHONY: dep

persist-settings: distclean
	echo STD=$(STD) >> .make-settings
	echo WARN=$(WARN) >> .make-settings
	echo OPT=$(OPT) >> .make-settings
	echo MALLOC=$(MALLOC) >> .make-settings
	echo CFLAGS=$(CFLAGS) >> .make-settings
	echo LDFLAGS=$(LDFLAGS) >> .make-settings
	echo REDIS_CFLAGS=$(REDIS_CFLAGS) >> .make-settings
	echo REDIS_LDFLAGS=$(REDIS_LDFLAGS) >> .make-settings
	echo PREV_FINAL_CFLAGS=$(FINAL_CFLAGS) >> .make-settings
	echo PREV_FINAL_LDFLAGS=$(FINAL_LDFLAGS) >> .make-settings
	-(cd ../deps && $(MAKE) $(DEPENDENCY_TARGETS))

.PHONY: persist-settings

# Prerequisites target
.make-prerequisites:
	@touch $@

# Clean everything, persist settings and build dependencies if anything changed
ifneq ($(strip $(PREV_FINAL_CFLAGS)), $(strip $(FINAL_CFLAGS)))
.make-prerequisites: persist-settings
endif

ifneq ($(strip $(PREV_FINAL_LDFLAGS)), $(strip $(FINAL_LDFLAGS)))
.make-prerequisites: persist-settings
endif

# redis-server
$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/leveldb/libleveldb.a ../deps/hiredis/libhiredis.a  $(FINAL_LIBS)

# redis-cli
$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS)

# redis-benchmark
$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ)
	$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS)

# Because the jemalloc.h header is generated as a part of the jemalloc build,
# building it should complete before building any other object. Instead of
# depending on a single artifact, build all dependencies first.
%.o: %.c .make-prerequisites
	$(REDIS_CC) -c $<

clean:
	rm -rf $(REDIS_SERVER_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html

.PHONY: clean

distclean: clean
	-(cd ../deps && $(MAKE) distclean)
	-(rm -f .make-*)

.PHONY: distclean

test: $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME)
	@(cd ..; ./runtest)

check: test

lcov:
	$(MAKE) gcov
	@(set -e; cd ..; ./runtest --clients 1)
	@geninfo -o redis.info .
	@genhtml --legend -o lcov-html redis.info

.PHONY: lcov

bench: $(REDIS_BENCHMARK_NAME)
	./$(REDIS_BENCHMARK_NAME)

32bit:
	@echo ""
	@echo "WARNING: if it fails under Linux you probably need to install libc6-dev-i386"
	@echo ""
	$(MAKE) CFLAGS="-m32" LDFLAGS="-m32"

gcov:
	$(MAKE) REDIS_CFLAGS="-fprofile-arcs -ftest-coverage -DCOVERAGE_TEST" REDIS_LDFLAGS="-fprofile-arcs -ftest-coverage"

noopt:
	$(MAKE) OPTIMIZATION="-O0"

valgrind:
	$(MAKE) OPTIMIZATION="-O0" MALLOC="libc"

src/help.h:
	@../utils/generate-command-help.rb > help.h

install: all
	@mkdir -p $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_BENCHMARK_NAME) $(INSTALL_BIN)
	$(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN)


text:
'use strict';

import './lp.html';


text:
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.windowsazure.management.mediaservices;

import com.microsoft.windowsazure.core.ServiceClient;
import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials;
import com.microsoft.windowsazure.management.configuration.ManagementConfiguration;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.http.impl.client.HttpClientBuilder;

public class MediaServicesManagementClientImpl extends ServiceClient<MediaServicesManagementClient> implements MediaServicesManagementClient {
    private String apiVersion;

    /**
    * Gets the API version.
    * @return The ApiVersion value.
    */
    public String getApiVersion() {
        return this.apiVersion;
    }

    private URI baseUri;

    /**
    * Gets the URI used as the base for all cloud service requests.
    * @return The BaseUri value.
    */
    public URI getBaseUri() {
        return this.baseUri;
    }

    private SubscriptionCloudCredentials credentials;

    /**
    * Gets subscription credentials which uniquely identify Microsoft Azure
    * subscription. The subscription ID forms part of the URI for every
    * service call.
    * @return The Credentials value.
    */
    public SubscriptionCloudCredentials getCredentials() {
        return this.credentials;
    }

    private int longRunningOperationInitialTimeout;

    /**
    * Gets or sets the initial timeout for Long Running Operations.
    * @return The LongRunningOperationInitialTimeout value.
    */
    public int getLongRunningOperationInitialTimeout() {
        return this.longRunningOperationInitialTimeout;
    }

    /**
    * Gets or sets the initial timeout for Long Running Operations.
    * @param longRunningOperationInitialTimeoutValue The
    * LongRunningOperationInitialTimeout value.
    */
    public void setLongRunningOperationInitialTimeout(final int longRunningOperationInitialTimeoutValue) {
        this.longRunningOperationInitialTimeout = longRunningOperationInitialTimeoutValue;
    }

    private int longRunningOperationRetryTimeout;

    /**
    * Gets or sets the retry timeout for Long Running Operations.
    * @return The LongRunningOperationRetryTimeout value.
    */
    public int getLongRunningOperationRetryTimeout() {
        return this.longRunningOperationRetryTimeout;
    }

    /**
    * Gets or sets the retry timeout for Long Running Operations.
    * @param longRunningOperationRetryTimeoutValue The
    * LongRunningOperationRetryTimeout value.
    */
    public void setLongRunningOperationRetryTimeout(final int longRunningOperationRetryTimeoutValue) {
        this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeoutValue;
    }

    private AccountOperations accounts;

    /**
    * @return The AccountsOperations value.
    */
    public AccountOperations getAccountsOperations() {
        return this.accounts;
    }

    /**
    * Initializes a new instance of the MediaServicesManagementClientImpl class.
    *
    * @param httpBuilder The HTTP client builder.
    * @param executorService The executor service.
    */
    private MediaServicesManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) {
        super(httpBuilder, executorService);
        this.accounts = new AccountOperationsImpl(this);
        this.apiVersion = "2011-10-01";
        this.longRunningOperationInitialTimeout = -1;
        this.longRunningOperationRetryTimeout = -1;
    }

    /**
    * Initializes a new instance of the MediaServicesManagementClientImpl class.
    *
    * @param httpBuilder The HTTP client builder.
    * @param executorService The executor service.
    * @param credentials Required. Gets subscription credentials which uniquely
    * identify Microsoft Azure subscription. The subscription ID forms part of
    * the URI for every service call.
    * @param baseUri Required. Gets the URI used as the base for all cloud
    * service requests.
    */
    @Inject
    public MediaServicesManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) {
        this(httpBuilder, executorService);
        if (credentials == null) {
            throw new NullPointerException("credentials");
        } else {
            this.credentials = credentials;
        }
        if (baseUri == null) {
            try {
                this.baseUri = new URI("https://management.core.windows.net");
            }
            catch (URISyntaxException ex) {
            }
        } else {
            this.baseUri = baseUri;
        }
    }

    /**
    * Initializes a new instance of the MediaServicesManagementClientImpl class.
    *
    * @param httpBuilder The HTTP client builder.
    * @param executorService The executor service.
    * @param credentials Required. Gets subscription credentials which uniquely
    * identify Microsoft Azure subscription. The subscription ID forms part of
    * the URI for every service call.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    */
    public MediaServicesManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException {
        this(httpBuilder, executorService);
        if (credentials == null) {
            throw new NullPointerException("credentials");
        }
        this.credentials = credentials;
        this.baseUri = new URI("https://management.core.windows.net");
    }

    /**
    * Initializes a new instance of the MediaServicesManagementClientImpl class.
    *
    * @param httpBuilder The HTTP client builder.
    * @param executorService The executor service.
    * @param credentials Required. Gets subscription credentials which uniquely
    * identify Microsoft Azure subscription. The subscription ID forms part of
    * the URI for every service call.
    * @param baseUri Required. Gets the URI used as the base for all cloud
    * service requests.
    * @param apiVersion Required. Gets the API version.
    * @param longRunningOperationInitialTimeout Required. Gets or sets the
    * initial timeout for Long Running Operations.
    * @param longRunningOperationRetryTimeout Required. Gets or sets the retry
    * timeout for Long Running Operations.
    */
    public MediaServicesManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials, URI baseUri, String apiVersion, int longRunningOperationInitialTimeout, int longRunningOperationRetryTimeout) {
        this(httpBuilder, executorService);
        this.credentials = credentials;
        this.baseUri = baseUri;
        this.apiVersion = apiVersion;
        this.longRunningOperationInitialTimeout = longRunningOperationInitialTimeout;
        this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout;
    }

    /**
    * Initializes a new instance of the MediaServicesManagementClientImpl class.
    *
    * @param httpBuilder The HTTP client builder.
    * @param executorService The executor service.
    */
    protected MediaServicesManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) {
        return new MediaServicesManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri(), this.getApiVersion(), this.getLongRunningOperationInitialTimeout(), this.getLongRunningOperationRetryTimeout());
    }
}


text:
import React from "react"
import { Modal } from "../../../components/CommonElement"
import { connect } from "react-redux"
import { getTranslate } from 'react-localize-redux'
import * as transferActions from "../../../actions/transferActions"
import * as converter from "../../../utils/converter"
import * as validators from "../../../utils/validators"
import { FeeDetail } from "../../../components/CommonElement"
import Tx from "../../../services/tx"
import * as accountActions from '../../../actions/accountActions'
import constants from "../../../services/constants";

@connect((store) => {
    const account = store.account.account
    const wallet = store.account.wallet;
    const translate = getTranslate(store.locale)
    const tokens = store.tokens.tokens
    const transfer = store.transfer
    const ethereum = store.connection.ethereum
    const global = store.global

    return {
        translate, transfer, tokens, account, ethereum, global, wallet
    }
})
export default class ConfirmModal extends React.Component {
    constructor() {
        super()
        this.state = {
            err: "",
            isFetchGas: false,
            gasLimit: 0,
            gasPrice: 0,
            isConfirmingTx: false
        }
        this.confirmingTimer = null;
    }

    componentDidMount = () => {
        this.setState({
            isFetchGas: true,
            gasLimit: this.getMaxGasTransfer(),
            gasPrice: this.props.transfer.gasPrice
        })

        this.getGasTransfer()
    }

    componentWillUnmount() {
        clearTimeout(this.confirmingTimer);
    }

    getMaxGasTransfer = () => {
        const transfer = this.props.transfer;
        const specialGasLimit = constants.SPECIAL_TRANSFER_GAS_LIMIT[transfer.tokenSymbol];

        if (!specialGasLimit) {
            return transfer.gas_limit;
        }

        return specialGasLimit;
    };

    getFormParams = () => {
        var tokenSymbol = this.props.transfer.tokenSymbol
        var address = this.props.account.address
        var destAddress = this.props.transfer.destAddress
        var destEthName = this.props.transfer.destEthName;
        var tokenDecimal = this.props.tokens[tokenSymbol].decimals
        var tokenAddress = this.props.tokens[tokenSymbol].address
        var amount = converter.stringToHex(this.props.transfer.amount, tokenDecimal)
        var ethereum = this.props.ethereum
        var nonce = this.props.account.getUsableNonce()
        var gas = converter.numberToHex(this.state.gasLimit)
        var gasPrice = converter.numberToHex(converter.gweiToWei(this.state.gasPrice))
        var keystring = this.props.account.keystring
        var type = this.props.account.type
        var password = ""

        return {
            tokenSymbol, address, destEthName, destAddress, tokenDecimal, amount, tokenAddress, nonce, ethereum, gas, gasPrice, keystring, type, password
        }
    }

    async getGasTransfer() {
        var txObj
        var { tokenSymbol, address, destAddress, tokenDecimal, amount, tokenAddress, ethereum } = this.getFormParams()
        if (tokenSymbol === "TUSD" || tokenSymbol === "EURS") {
            this.setState({ isFetchGas: false })
            return
        }
        try {
            var fromAddr = !validators.verifyAccount(address) ? address : "0x3cf628d49ae46b49b210f0521fbd9f82b461a9e1"
            if (tokenSymbol === 'ETH') {
                txObj = {
                    from: fromAddr,
                    value: amount,
                    to: destAddress
                }
                var gas = await ethereum.call("estimateGas", txObj)
                if (gas > 21000) {
                    gas = Math.round(gas * 120 / 100)
                }
                this.setState({
                    gasLimit: gas,
                    isFetchGas: false
                })

            } else {
                var data = await ethereum.call("sendTokenData", tokenAddress, amount, destAddress)
                txObj = {
                    from: fromAddr,
                    value: "0x0",
                    to: tokenAddress,
                    data: data
                }

                gas = await ethereum.call("estimateGas", txObj)
                //addition 15k gas for transfer token
                gas = Math.round((gas + 15000) * 120 / 100)
                this.setState({
                    gasLimit: gas,
                    isFetchGas: false
                })
            }
        } catch (err) {
            console.log(err)
            this.setState({
                isFetchGas: false
            })
        }
    }

    async clickTransfer() {
        const wallet = this.props.wallet;

        if (this.state.isConfirmingTx) return

        this.setState({
            err: "",
            isConfirmingTx: true
        })

        if (this.props.account.type === 'walletconnect') {
            this.confirmingTimer = setTimeout(() => {
                this.setState({ isConfirmingTx: false })
            }, constants.TX_CONFIRMING_TIMEOUT);
        }

        try {

            var { formId, ethereum, address, tokenAddress, amount, destAddress, nonce, gas, gasPrice, keystring, type, password, tokenSymbol } = this.getFormParams()

            var callFunc = tokenSymbol === "ETH" ? "sendEtherFromAccount" : "sendTokenFromAccount"

            var txHash = await wallet.broadCastTx(callFunc, formId, ethereum, address,
                tokenAddress, amount,
                destAddress.toLowerCase(), nonce, gas,
                gasPrice, keystring, type, password)

            //notify server
            try {
                var notiService = this.props.global.notiService
                notiService.callFunc("setNewTx", { hash: txHash })
            } catch (e) {
                console.log(e)
            }

            this.props.global.analytics.callTrack("trackCoinTransfer", tokenSymbol);
            this.props.global.analytics.callTrack("completeTrade", txHash, "kyber", "transfer");

            var data = { amount, tokenSymbol, destAddress }
            const tx = new Tx(
                txHash, address, gas, gasPrice, nonce, "pending", "transfer", data)

            this.props.dispatch(accountActions.incManualNonceAccount(address))
            this.props.dispatch(accountActions.updateAccount(ethereum, this.props.account))

            this.props.dispatch(transferActions.doTransactionComplete(tx))
            this.props.dispatch(transferActions.finishTransfer())

            //go to the next step
            this.props.dispatch(transferActions.forwardTransferPath())
        } catch (err) {
            console.log(err)
            this.setState({ err: err.toString(), isConfirmingTx: false })
        }
    }

    msgHtml = () => {
        if (this.state.isConfirmingTx && this.props.account.type !== 'privateKey') {
            return
{this.props.translate("modal.waiting_for_confirmation") || "Waiting for confirmation from your wallet"}

        } else {
            return ""
        }
    }

    errorHtml = () => {
        if (this.state.err) {
            return (
                <React.Fragment>

                        {this.state.err}

                </React.Fragment>
            )
        }

        return ""
    }

    closeModal = () => {
        if (this.state.isConfirmingTx) return
        this.props.dispatch(transferActions.resetTransferPath())
    }

    recap = () => {
        var { tokenSymbol, destAddress, destEthName } = this.getFormParams()
        var amount = this.props.transfer.amount.toString()
        return (

                    {this.props.translate("transaction.about_to_transfer") || "You are about to transfer"}

                            {amount.slice(0, 7)}{amount.length > 7 ? '...' : ''} {tokenSymbol}

{this.props.translate("transaction.to") || "to"}

                        {destEthName && (

{destEthName}

                        )}

{destAddress.slice(0, 7)}...{destAddress.slice(-5)}

        )
    }

    contentModal = () => {
        return (

{this.props.translate("modal.confirm_transfer_title") || "Transfer Confirm"}

                                    {this.recap()}
                                    <FeeDetail
                                        translate={this.props.translate}
                                        gasPrice={this.state.gasPrice}
                                        gas={this.state.gasLimit}
                                        isFetchingGas={this.state.isFetchGas}

                                    />

                                {this.errorHtml()}

{this.msgHtml()}

                                {this.props.translate("modal.cancel" || "Cancel")}

{this.props.translate("modal.confirm").toLocaleUpperCase() || "Confirm".toLocaleUpperCase()}

        )
    }

    render() {
        return (
            <Modal className={{
                base: 'reveal medium confirm-modal',
                afterOpen: 'reveal medium confirm-modal'
            }}
                isOpen={true}
                onRequestClose={this.closeModal}
                contentLabel="confirm modal"
                content={this.contentModal()}
                size="medium"
            />
        )
    }
}


text:
package cells

//--------------------
// IMPORTS
//--------------------

import (
	"sync"
	"time"

	"github.com/tideland/golib/errors"
	"github.com/tideland/golib/identifier"
	"github.com/tideland/golib/logger"
	"github.com/tideland/golib/loop"
	"github.com/tideland/golib/monitoring"
)

//--------------------
// CONNECTIONS
//--------------------

// connections manages the connections to connected
// cells.
type connections struct {
	mutex sync.RWMutex
	cells []*cell
}

// newConnections creates an instance of the
// connection manager.
func newConnections() *connections {
	return &connections{
		cells: []*cell{},
	}
}

// add adds a new cell with a given identifier to the
// connections.
func (cs *connections) add(c *cell) {
	cs.mutex.Lock()
	defer cs.mutex.Unlock()
	for _, csc := range cs.cells {
		if csc == c {
			return
		}
	}
	cs.cells = append(cs.cells, c)
}

// remove deletes the identified cell.
func (cs *connections) remove(id string) {
	cs.mutex.Lock()
	defer cs.mutex.Unlock()
	remaining := []*cell{}
	for _, csc := range cs.cells {
		if csc.id != id {
			remaining = append(remaining, csc)
		}
	}
	cs.cells = remaining
}

// ids returns the identifiers of the connected cells.
func (cs *connections) ids() []string {
	var ids []string
	for _, csc := range cs.cells {
		ids = append(ids, csc.id)
	}
	return ids
}

// do executes the passed function for all connected cells
// and collects potential errors.
func (cs *connections) do(f func(c *cell) error) error {
	cs.mutex.RLock()
	defer cs.mutex.RUnlock()
	var errs []error
	for _, csc := range cs.cells {
		if err := f(csc); err != nil {
			errs = append(errs, err)
		}
	}
	switch len(errs) {
	case 0:
		return nil
	case 1:
		return errs[0]
	default:
		return errors.Collect(errs...)
	}
}

//--------------------
// CELL
//--------------------

// cell for event processing.
type cell struct {
	env                *environment
	id                 string
	measuringID        string
	queue              Queue
	behavior           Behavior
	emitters           *connections
	subscribers        *connections
	recoveringNumber   int
	recoveringDuration time.Duration
	loop               loop.Loop
}

// newCell create a new cell around a behavior.
func newCell(env *environment, id string, behavior Behavior) (*cell, error) {
	logger.Infof("cell '%s' starts", id)
	// Init cell runtime.
	c := &cell{
		env:         env,
		id:          id,
		measuringID: identifier.Identifier("cells", env.id, "cell", id),
		queue:       env.createQueue(),
		behavior:    behavior,
		emitters:    newConnections(),
		subscribers: newConnections(),
	}
	// Set configuration.
	if brf, ok := behavior.(BehaviorRecoveringFrequency); ok {
		number, duration := brf.RecoveringFrequency()
		if duration.Seconds()/float64(number) < 0.1 {
			number = minRecoveringNumber
			duration = minRecoveringDuration
		}
		c.recoveringNumber = number
		c.recoveringDuration = duration
	} else {
		c.recoveringNumber = minRecoveringNumber
		c.recoveringDuration = minRecoveringDuration
	}
	// Init behavior.
	if err := behavior.Init(c); err != nil {
		return nil, errors.Annotate(err, ErrCellInit, errorMessages, id)
	}
	// Start backend.
	c.loop = loop.GoRecoverable(c.backendLoop, c.checkRecovering, id)
	return c, nil
}

// Environment implements the Cell interface.
func (c *cell) Environment() Environment {
	return c.env
}

// ID implements the Cell interface.
func (c *cell) ID() string {
	return c.id
}

// Emit implements the Cell interface.
func (c *cell) Emit(event Event) error {
	return c.SubscribersDo(func(cs Subscriber) error {
		return cs.ProcessEvent(event)
	})
}

// EmitNew implements the Cell interface.
func (c *cell) EmitNew(topic string, payload interface{}) error {
	event, err := NewEvent(topic, payload)
	if err != nil {
		return err
	}
	return c.Emit(event)
}

// ProcessEvent implements the Subscriber interface.
func (c *cell) ProcessEvent(event Event) error {
	return c.queue.Emit(event)
}

// ProcessNewEvent implements the Subscriber interface.
func (c *cell) ProcessNewEvent(topic string, payload Payload) error {
	event, err := NewEvent(topic, payload)
	if err != nil {
		return err
	}
	return c.ProcessEvent(event)
}

// SubscribersDo implements the Subscriber interface.
func (c *cell) SubscribersDo(f func(s Subscriber) error) error {
	return c.subscribers.do(func(sc *cell) error { return f(Subscriber(sc)) })
}

// stop terminates the cell.
func (c *cell) stop() error {
	// Terminate connactions to emitters and subscribers.
	c.emitters.do(func(ec *cell) error {
		ec.subscribers.remove(c.id)
		return nil
	})
	c.subscribers.do(func(sc *cell) error {
		sc.emitters.remove(c.id)
		return nil
	})
	// Stop own backend.
	c.queue.Close()
	err := c.loop.Stop()
	if err != nil {
		logger.Errorf("cell '%s' stopped with error: %v", c.id, err)
	} else {
		logger.Infof("cell '%s' stopped", c.id)
	}
	return err
}

// backendLoop is the backend for the processing of messages.
func (c *cell) backendLoop(l loop.Loop) error {
	totalCellsID := identifier.Identifier("cells", c.env.ID(), "total-cells")
	monitoring.IncrVariable(totalCellsID)
	defer monitoring.DecrVariable(totalCellsID)

	for {
		select {
		case <-l.ShallStop():
			return c.behavior.Terminate()
		case event := <-c.queue.Events():
			if event == nil {
				panic("received illegal nil event!")
			}
			measuring := monitoring.BeginMeasuring(c.measuringID)
			err := c.behavior.ProcessEvent(event)
			measuring.EndMeasuring()
			if err != nil {
				logger.Errorf("cell %q processed event %q with error: %v", c.id, event.Topic(), err)
				return err
			}
		}
	}
}

// checkRecovering checks if the cell may recover after a panic. It will
// signal an error and let the cell stop working if there have been 12 recoverings
// during the last minute or the behaviors Recover() signals, that it cannot
// handle the error.
func (c *cell) checkRecovering(rs loop.Recoverings) (loop.Recoverings, error) {
	logger.Warningf("recovering cell %q after error: %v", c.id, rs.Last().Reason)
	// Check frequency.
	if rs.Frequency(c.recoveringNumber, c.recoveringDuration) {
		err := errors.New(ErrRecoveredTooOften, errorMessages, rs.Last().Reason)
		logger.Errorf("recovering frequency of cell %q too high", c.id)
		return nil, err
	}
	// Try to recover.
	if err := c.behavior.Recover(rs.Last().Reason); err != nil {
		err := errors.Annotate(err, ErrEventRecovering, errorMessages, rs.Last().Reason)
		logger.Errorf("recovering of cell %q failed: %v", c.id, err)
		return nil, err
	}
	logger.Infof("successfully recovered cell %q", c.id)
	return rs.Trim(c.recoveringNumber), nil
}

// EOF