text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * @copyright DharmaTech  (c) 2009
 * $Id$
 *
 */

require_once 'Engage/Report/Form/List.php';

/**
 *  Generate a walk list
 */
class Engage_Report_Form_WalkList extends Engage_Report_Form_List {
  function __construct() {

    parent::__construct();

    //  Walk list columns
    $this->_columns = array(
      $this->_demoTable =>
      array(
        'dao' => 'CRM_Contact_DAO_Contact',
        'fields' =>
        array(
          $this->_demoLangCol =>
          array(
            'type' => CRM_Report_Form::OP_STRING,
            'required' => TRUE,
            'title' => ts('Language'),
          ),
        ),
        'filters' =>
        array(
          $this->_demoLangCol =>
          array(
            'title' => ts('Language'),
            'operatorType' => CRM_Report_Form::OP_SELECT,
            'type' => CRM_Report_Form::OP_STRING,
            'options' => $this->_languages,
          ),
        ),
        'grouping' => 'contact-fields',
      ),
      $this->_coreInfoTable =>
      array(
        'dao' => 'CRM_Contact_DAO_Contact',
        'fields' =>
        array(
          $this->_coreTypeCol =>
          array(
            'type' => CRM_Report_Form::OP_STRING,
            'required' => TRUE,
            'title' => ts('Constituent Type'),
          ),
          $this->_coreOtherCol =>
          array(
            'type' => CRM_Report_Form::OP_STRING,
            'required' => TRUE,
            'title' => ts('Other Name'),
          ),
        ),
        'filters' =>
        array(
          $this->_coreTypeCol =>
          array(
            'title' => ts('Constituent Type'),
            'operatorType' => CRM_Report_Form::OP_SELECT,
            'type' => CRM_Report_Form::OP_STRING,
            'options' => $this->_contactType,
          ),
        ),
        'grouping' => 'contact-fields',
      ),
      'civicrm_contact' =>
      array(
        'dao' => 'CRM_Contact_DAO_Contact',
        'fields' =>
        array(
          'gender_id' =>
          array('title' => ts('Sex'),
            'required' => TRUE,
          ),
          'birth_date' =>
          array('title' => ts('Age'),
            'required' => TRUE,
            'type' => CRM_Report_Form::OP_INT,
          ),
          'id' =>
          array('title' => ts('Contact ID'),
            'required' => TRUE,
          ),
          'display_name' =>
          array('title' => ts('Contact Name'),
            'required' => TRUE,
            'no_repeat' => TRUE,
          ),
        ),
        'filters' =>
        array(
          'gender_id' =>
          array('title' => ts('Sex'),
            'operatorType' => CRM_Report_Form::OP_SELECT,
            'type' => CRM_Report_Form::OP_STRING,
            'options' => array('' => '') + CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
          ),
          'sort_name' =>
          array('title' => ts('Contact Name'),
            'operator' => 'like',
          ),
        ),
        'grouping' => 'contact-fields',
        'order_bys' =>
        array('sort_name' => array('title' => ts('Contact Name'),
            'required' => TRUE,
          )),
      ),
      'civicrm_address' =>
      array(
        'dao' => 'CRM_Core_DAO_Address',
        'fields' =>
        array(
          'street_number' =>
          array(
            'required' => TRUE,
            'title' => ts('Street#'),
          ),
          'street_name' =>
          array('title' => ts('Street Name'),
            'nodisplay' => TRUE,
            'required' => TRUE,
          ),
          'street_address' =>
          array(
            'required' => TRUE,
            'title' => ts('Street Address'),
          ),
          'street_unit' =>
          array(
            'required' => TRUE,
            'title' => ts('Apt.'),
          ),
          'city' =>
          array('required' => TRUE),
          'postal_code' =>
          array(
            'title' => 'Zip',
            'required' => TRUE,
          ),
          'state_province_id' =>
          array('title' => ts('State/Province'),
            'required' => TRUE,
          ),
          'country_id' =>
          array('title' => ts('Country'),
          ),
        ),
        'filters' =>
        array(
          'street_address' => NULL,
          'city' => NULL,
          'postal_code' => array('title' => 'Zip'),
        ),
        'grouping' => 'location-fields',
      ),
      'civicrm_phone' =>
      array(
        'dao' => 'CRM_Core_DAO_Phone',
        'fields' =>
        array(
          'phone' => array('default' => TRUE,
            'required' => TRUE,
          )),
        'grouping' => 'location-fields',
      ),
      'civicrm_email' =>
      array(
        'dao' => 'CRM_Core_DAO_Email',
        'fields' =>
        array('email' => NULL),
        'grouping' => 'location-fields',
      ),
      $this->_voterInfoTable =>
      array(
        'dao' => 'CRM_Contact_DAO_Contact',
        'fields' =>
        array(
          $this->_partyCol =>
          array(
            'type' => CRM_Report_Form::OP_STRING,
            'required' => TRUE,
            'title' => ts('Party Reg'),
          ),
          $this->_vhCol =>
          array(
            'type' => CRM_Report_Form::OP_STRING,
            'required' => TRUE,
            'title' => ts('VH'),
          ),
        ),
        'filters' => array(),
        'grouping' => 'contact-fields',
      ),
      'civicrm_group' =>
      array(
        'dao' => 'CRM_Contact_DAO_GroupContact',
        'alias' => 'cgroup',
        'filters' =>
        array(
          'gid' =>
          array(
            'name' => 'group_id',
            'title' => ts('Group'),
            'operatorType' => CRM_Report_Form::OP_MULTISELECT,
            'group' => TRUE,
            'options' => CRM_Core_PseudoConstant::group(),
          ),
        ),
      ),
      'civicrm_contribution_lastcont' =>
      array(
        'dao' => 'CRM_Contribute_DAO_Contribution',
      ),
      'civicrm_contribution_cont' =>
      array(
        'dao' => 'CRM_Contribute_DAO_Contribution',
        'alias' => 'cont',
        'fields' =>
        array(
          'receive_date' => array('default' => TRUE, 'title' => 'Last Receipt'),
          'total_amount' => array(
            'default' => TRUE, 'title' => 'Amount received',
          ),
        ),
      ),
    );
  }

  /**
   *  Generate WHERE clauses for SQL SELECT
   *  FIXME: deal with age filter
   */
  function where() {
    $clauses = array("{$this->_aliases['civicrm_address']}.id IS NOT NULL");

    foreach ($this->_columns as $tableName => $table) {
      //echo "where: table name $tableName
";

      //  Treatment of normal filters
      if (array_key_exists('filters', $table)) {
        foreach ($table['filters'] as $fieldName => $field) {
          //echo "   field name $fieldName
";
          $clause = NULL;

          if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
            $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
            $from     = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
            $to       = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);

            $clause = $this->dateClause($field['name'], $relative, $from, $to);
          }
          elseif ($fieldName == $this->_demoLangCol) {
            if (!empty($this->_params[$this->_demoLangCol . '_value'])) {
              $clause = "{$field['dbAlias']}='" . $this->_params[$this->_demoLangCol . '_value'] . "'";
            }
          }
          else {
            $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
            if ($op == 'mand') {
              $clause = TRUE;
            }
            elseif ($op) {
              $clause = $this->whereClause($field,
                $op,
                CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
                CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
                CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
              );
            }
          }
          //var_dump($clause);
          if (!empty($clause)) {
            if (!empty($field['group'])) {
              $clauses[] = $this->engageWhereGroupClause($clause);
            }
            else {
              $clauses[] = $clause;
            }
          }
        }
      }
    }

    if (empty($clauses)) {
      $this->_where = "WHERE ( 1 ) ";
    }
    else {
      $this->_where = "WHERE " . implode(' AND ', $clauses);
    }
  }

  /**
   *  Process submitted form
   */
  function postProcess() {
    parent::postProcess();
  }

  function alterDisplay(&$rows) {

    if ($this->_outputMode == 'print' || $this->_outputMode == 'pdf') {
      $this->executePrintmode($rows);
      return;
    }
    // custom code to alter rows
    //var_dump($rows);
    $genderList = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
    $entryFound = FALSE;
    foreach ($rows as $rowNum => $row) {
      // handle state province
      if (array_key_exists('civicrm_address_state_province_id', $row)) {
        if ($value = $row['civicrm_address_state_province_id']) {
          $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value);
        }
        $entryFound = TRUE;
      }

      // handle country
      if (array_key_exists('civicrm_address_country_id', $row)) {
        if ($value = $row['civicrm_address_country_id']) {
          $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value);
        }
        $entryFound = TRUE;
      }

      // Handle contactType
      if (!empty($row[$this->_coreInfoTable . '_' . $this->_coreTypeCol])) {
        $rows[$rowNum][$this->_coreInfoTable . '_' . $this->_coreTypeCol] = $this->hexOne2str($rows[$rowNum][$this->_coreInfoTable . '_' . $this->_coreTypeCol]);
        $entryFound = TRUE;
      }

      // date of birth to age
      if (!empty($row['civicrm_contact_birth_date'])) {
        $rows[$rowNum]['civicrm_contact_birth_date'] = $this->dob2age($row['civicrm_contact_birth_date'] . " 00:00:00");
        $entryFound = TRUE;
      }

      // gender label
      if (!empty($row['civicrm_contact_gender_id'])) {
        $rows[$rowNum]['civicrm_contact_gender_id'] = $genderList[$row['civicrm_contact_gender_id']];
        $entryFound = TRUE;
      }

      //  Abbreviate party registration to first letter
      if (!empty($row["{$this->_voterInfoTable}_{$this->_partyCol}"])) {
        $rows[$rowNum]["{$this->_voterInfoTable}_{$this->_partyCol}"] = substr($row["{$this->_voterInfoTable}_{$this->_partyCol}"], 0, 1);
        $entryFound = TRUE;
      }

      // skip looking further in rows, if first row itself doesn't
      // have the column we need
      if (!$entryFound) {
        break;
      }
    }

    // make sure column order is same as in print mode
    $columnOrder = array(
      'civicrm_address_street_number',
      'civicrm_address_street_unit',
      'civicrm_contact_display_name',
      'civicrm_phone_phone',
      'civicrm_contact_birth_date',
      'civicrm_contact_gender_id',
      $this->_demoTable . '_' . $this->_demoLangCol,
      $this->_voterInfoTable . '_' . $this->_partyCol,
      $this->_voterInfoTable . '_' . $this->_vhCol,
      $this->_coreInfoTable . '_' . $this->_coreTypeCol,
      'civicrm_contact_id',
    );
    $tempHeaders = $this->_columnHeaders;
    $this->_columnHeaders = array();
    foreach ($columnOrder as $col) {
      if (array_key_exists($col, $tempHeaders)) {
        $this->_columnHeaders[$col] = $tempHeaders[$col];
        unset($tempHeaders[$col]);
      }
    }
    $this->_columnHeaders = $this->_columnHeaders + $tempHeaders;
  }

  function executePrintmode($rows) {
    //only get these last contribution related variables in print mode if selected on previous form
    if (array_key_exists('civicrm_contribution_cont_receive_date', $rows[0])) {
      $receiveDate = ', date_received   DATE';
    }
    if (array_key_exists('civicrm_contribution_cont_total_amount', $rows[0])) {
      $contAmount = ' , total_amount FLOAT';
    }
    //  Separate out fields and build a temporary table
    $tempTable = "WalkList_" . uniqid();
    $sql = "CREATE TEMPORARY TABLE {$tempTable}" . " ( id              INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
                  street_name     VARCHAR(255),
                  s_street_number VARCHAR(32),
                  i_street_number INT,
                  odd             TINYINT,
                  apt_number      VARCHAR(32),
                  city            VARCHAR(64),
                  state           VARCHAR(32),
                  zip             VARCHAR(32),
                  name            VARCHAR(255),
                  phone           VARCHAR(255),
                  age             INT,
                  sex             VARCHAR(16),
                  lang            CHAR(2),
                  party           CHAR(1),
                  vh              CHAR(1),
                  contact_type    VARCHAR(128),
                  other_name      VARCHAR(128),
                  contact_id      INT
                  $receiveDate $contAmount
                  )
                 ENGINE=HEAP
                 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
    CRM_Core_DAO::executeQuery($sql);

    $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');

    foreach ($rows as $key => $value) {

      $dob  = $value['civicrm_contact_birth_date'];
      $age  = empty($dob) ? 0 : $this->dob2age($dob);
      if (!empty($value['civicrm_contact_gender_id'])){
        $sex  = $gender[CRM_Utils_Array::value('civicrm_contact_gender_id', $value)];
      }
      $sex  = empty($sex) ? '' : $sex;
      $lang = strtoupper(substr($value[$this->_demoTable . '_' . $this->_demoLangCol], 0, 2
        ));
      $party       = substr($value["{$this->_voterInfoTable}_{$this->_partyCol}"], 0, 1);
      $vh          = substr($value["{$this->_voterInfoTable}_{$this->_vhCol}"], 0, 1);
      $contactType = $value[$this->_coreInfoTable . '_' . $this->_coreTypeCol];
      $on          = $value[$this->_coreInfoTable . '_' . $this->_coreOtherCol];
      $otherName   = empty($on) ? 0 : "'{$on}'";
      $type        = '';
      if (!empty($contactType)) {
        $type = $this->hexOne2str($contactType);
      }
      $contact_id = (int)$value['civicrm_contact_id'];

      $state = '';
      if (!empty($value['civicrm_address_state_province_id'])) {
        $state = CRM_Core_PseudoConstant::stateProvince(
          $value['civicrm_address_state_province_id']
        );
      }

      $sStreetNumber = $value['civicrm_address_street_number'];
      $iStreetNumber = $value['civicrm_address_street_number'] ? (int)$value['civicrm_address_street_number'] : 0;
      $odd           = $value['civicrm_address_street_number'] ? ((int)$value['civicrm_address_street_number'] % 2) : 0;
      $apt_number    = $value['civicrm_address_street_number'] ? $value['civicrm_address_street_number'] : '';
      $phone_number  = $value['civicrm_phone_phone'] ? $value['civicrm_phone_phone'] : '';
      $query         = "INSERT INTO {$tempTable} SET
                       street_name     = %1,
                       s_street_number = %2,
                       i_street_number = %3,
                       odd             = %4,
                       apt_number      = %5,
                       city            = %6,
                       state           = %7,
                       zip             = %8,
                       name            = %9,
                       phone           = %10,
                       age             = %11,
                       sex             = %12,
                       lang            = %13,
                       party           = %14,
                       vh              = %15,
                       contact_type    = %16,
                       other_name      = %17,
                       contact_id      = %18";
      $params = array(
        1 => array($value['civicrm_address_street_name'] ? $value['civicrm_address_street_name'] : '', 'String'),
        2 => array((String )$sStreetNumber, 'String'),
        3 => array($iStreetNumber, 'Integer'),
        4 => array($odd, 'Integer'),
        5 => array((String) $apt_number , 'String'),
        6 => array($value['civicrm_address_city'] ? $value['civicrm_address_city'] : '', 'String'),
        7 => array((String) $state , 'String'),
        8 => array($value['civicrm_address_postal_code'] ? $value['civicrm_address_postal_code'] : '', 'String'),
        9 => array($value['civicrm_contact_display_name'] ? $value['civicrm_contact_display_name'] : '', 'String'),
        10 => array((String)  $phone_number, 'String'),
        11 => array($age, 'Integer'),
        12 => array((String) $sex, 'String'),
        13 => array((String) $lang, 'String'),
        14 => array((String) $party, 'String'),
        15 => array((String) $vh, 'String'),
        16 => array((String) $type, 'String'),
        17 => array((String) $otherName, 'String'),
        18 => array((String) $contact_id, 'Integer'),
      );

      if (!empty($contAmount)) {
        $query       .= ", total_amount = %19";
        $total_amount = $value['civicrm_contribution_cont_total_amount'] ? $value['civicrm_contribution_cont_total_amount'] : 0;
        $params[19]   = array($total_amount, 'Money');
      }
      if (!empty($receiveDate)) {
        $query        .= ",date_received  = %20";
        $date_received = $value['civicrm_contribution_cont_receive_date'] ? CRM_Utils_Date::isoToMysql($value['civicrm_contribution_cont_receive_date']) : NULL;
        $params[20]    = array($date_received, 'Timestamp');
      }
      CRM_Core_DAO::executeQuery($query, $params);
    }

    //  With the data normalized and in a table, we can
    //  retrieve it in the order we need to present it
    $query = "SELECT * FROM {$tempTable} ORDER BY state, city, zip,
                  street_name, odd, i_street_number, apt_number";
    $dao = CRM_Core_DAO::executeQuery($query);

    //  Initialize output state
    $first       = TRUE;
    $state       = '';
    $city        = '';
    $zip         = '';
    $street_name = '';
    $odd         = '';
    $pageRow     = 0;
    $reportDate  = date('F j, Y');

    $pdfRows     = array();
    $groupRows   = array();
    $groupCounts = 0;

    $pdfHeaders = array('s_street_number' => array('title' => 'STREET#'),
      'apt_number' => array('title' => 'APT'),
      'name' => array('title' => 'Name'),
      'phone' => array('title' => 'PHONE'),
      'age' => array('title' => 'AGE'),
      'sex' => array('title' => 'SEX'),
      'lang' => array('title' => 'Lang'),
      'party' => array('title' => 'Party'),
      'vh' => array('title' => 'VH'),
      'contact_type' => array('title' => 'Constituent Type'),
      'note' => array('title' => 'NOTES'),
      'rcode' => array('title' => 'RESPONSE CODES'),
      'status' => array('title' => 'STATUS'),
      'contact_id' => array(
        'title' => 'ID',
        'class' => 'width=7%',
      ),
    );

    if (variable_get('civicrm_engage_groupbreak_street', "1") != 1) {
      $pdfHeaders['street_name']['title'] = 'Street';
    }
    if ($receiveDate) {
      $pdfHeaders['date_received'] = array('title' => 'Last donation Date');
    }
    if ($contAmount) {
      $pdfHeaders['total_amount'] = array('title' => 'Last donation');
    }

    $groupInfo = array(
      'date' => $reportDate,
      'descr' => empty($this->_groupDescr) ? '' : "
Group {$this->_groupDescr}",
    );

    while ($dao->fetch()) {

      if (strtolower($state) != strtolower($dao->state)
        || (variable_get('civicrm_engage_groupbreak_city', "1") == 1 && strtolower($city) != strtolower($dao->city))
        || (variable_get('civicrm_engage_groupbreak_zip', "1") == 1 && strtolower($zip) != strtolower($dao->zip))
        || (variable_get('civicrm_engage_groupbreak_street', "1") == 1 && strtolower($street_name) != strtolower($dao->street_name))
        || (variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1 && $odd != $dao->odd)
        || $pageRow > variable_get('civicrm_engage_lines_per_group', "6") - 1
      ) {
        $state       = $dao->state;
        $city        = $dao->city;
        $zip         = $dao->zip;
        $street_name = $dao->street_name;
        $odd         = $dao->odd;
        $pageRow     = 0;
        $groupRow['city_zip'] = '';
        $groupRow['org'] = $this->_orgName;
        if (variable_get('civicrm_engage_groupbreak_street', "1") == 1) {
          $groupRow['street_name'] = $street_name;
        }
        if (variable_get('civicrm_engage_groupbreak_city', "1") == 1) {
          $groupRow['city_zip'] .= $city . ', ';
        }
        $groupRow['city_zip'] .= $state;
        //don't give zip or odd-even if not grouped on
        if (variable_get('civicrm_engage_groupbreak_zip', "1") == 1) {
          $groupRow['city_zip'] .= ' ' . $zip;
        }
        if (variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1) {
          $groupRow['odd'] = $odd ? 'Odd' : 'Even';
        }
        $groupCounts++;
        $groupRows[$groupCounts] = $groupRow;
      }

      // if admin settings have been defined to specify not to canvas people for a period change date to specified text
      if (variable_get('civicrm_engage_no_canvas_period', "0") > 0 && $dao->date_received > 0
        && ((strtotime("now") - strtotime($dao->date_received)) / 60 / 60 / 24 / 30) < variable_get('civicrm_engage_no_canvas_period', "0")
      ) {
        $dao->date_received = variable_get('civicrm_engage_no_canvass_text', "Do Not Canvass");
      }

      $pdfRow = array();
      foreach ($pdfHeaders as $k => $v) {
        if (property_exists($dao, $k)) {
          if ($k == 'name' && $dao->other_name) {
            $pdfRow[$k] = $dao->$k . "
" . $dao->other_name;
            continue;
          }
          $pdfRow[$k] = $dao->$k;
        }
        else {
          $pdfRow[$k] = "";
        }
      }

      $pdfRows[$groupCounts][] = $pdfRow;

      $pageRow++;
    }
    if (variable_get('civicrm_engage_group_per_page', "1")) {
      $this->assign('newgroupdiv', 'class="page"');
    }
    $this->assign('pageTotal', $groupCounts);
    $this->assign('pdfHeaders', $pdfHeaders);
    $this->assign('groupInfo', $groupInfo);
    $this->assign('pdfRows', $pdfRows);
    $this->assign('groupRows', $groupRows);
  }
}


text:
<?php

namespace LTBAuctioneer\Auctioneer\Builder;

use Exception;
use LTBAuctioneer\Auctioneer\AuctionState;
use LTBAuctioneer\Auctioneer\Builder\Auctioneer;
use Utipd\CurrencyLib\CurrencyUtil;
use LTBAuctioneer\Debug\Debug;

/*
* AuctionStateBuilder
* Builds the auction state from a series of transactions in order
*/
class AuctionStateBuilder
{

    protected $meta_info = [];

    ////////////////////////////////////////////////////////////////////////

    public function __construct() {
    }

    // we assume transactions were provided in order
    public function buildAuctionStateFromTransactions($transactions, $auction, $meta_info) {
        // clear state
        $this->auction_state = null;
        $this->auctioneer = null;

        $this->setAuction($auction);
        $this->setMetaInfo($meta_info);

        foreach($transactions as $transaction) {
            $this->applyTransaction($transaction);
        }

        return $this->serializeState($this->finalizeState($this->getState()));
    }

    ////////////////////////////////////////////////////////////////////////

    protected function setMetaInfo($meta_info) {
        $this->meta_info = $meta_info;
    }

    protected function now() {
        if (isset($this->meta_info['now'])) { return $this->meta_info['now']; }
        return time();
    }

    protected function hasStarted($timestamp) {
        return ($timestamp >= $this->auction['startDate']);
    }

    protected function hasEnded($timestamp) {
        return ($timestamp >= $this->auction['endDate']);
    }

    protected function buildAuctionTimePhase($timestamp) {
#        Debug::trace("hasEnded() == ".Debug::desc($this->hasEnded())."",__FILE__,__LINE__,$this);
        if (!$this->hasStarted($timestamp)) { return 'prebid'; }
        if ($this->hasEnded($timestamp)) { return 'ended'; }
        return 'live';
    }

    protected function setAuction($auction) {
        $this->auction = $auction;
    }

    ////////////////////////////////////////////////////////////////////////

    protected function applyTransaction($transaction) {
        if ($transaction['classification'] == 'incoming') { return $this->applyIncomingTransactionToState($transaction); }
        if ($transaction['classification'] == 'outgoing') { return $this->applyOutgoingTransactionToState($transaction); }
        throw new Exception("Invalid transaction classification: ".Debug::desc($transaction['classification'])."", 1);
    }

    protected function applyIncomingTransactionToState($transaction) {
#        Debug::trace("\$transaction: ".$transaction['blockId'],__FILE__,__LINE__,$this);
        switch (true) {
            case $this->isBTCTransaction($transaction):
                # incoming BTC transaction
                $this->handleIncomingBTC($transaction);
                break;

            case $this->hasBiddingAsset($transaction):
                # incoming bidding asset transaction
                $this->handleIncomingBiddingAsset($transaction);
                break;

            default:
                # other, probably a prize token
                $this->handleUknownIncomingAsset($transaction);
                break;
        }

    }

    ////////////////////////////////////////////////////////////////////////
    // Bidding Asset

    protected function handleIncomingBiddingAsset($transaction) {
#       Debug::trace("handleIncomingBiddingAsset $transaction=".json_encode($transaction, 192),__FILE__,__LINE__,$this);
        $state = $this->getStateAtBlockAndTime($transaction['blockId'], $transaction['timestamp'], $transaction['isMempool']);
        $token_amount = $transaction['quantity'];

        $state->addLog("Received ".CurrencyUtil::satoshisToNumber($token_amount)." {$transaction['asset']}");

        if (!$state['bidTokenFeeSatisfied']) {
#            Debug::trace("applyToBidTokenFee",__FILE__,__LINE__,$this);
            $token_amount = $this->applyToBidTokenFee($token_amount, $state);
#            Debug::trace("after applyToBidTokenFee token_amount: $token_amount",__FILE__,__LINE__,$this);
            $this->refreshActiveStatus($state);
        }

        // bug here - if token amount is lowered, the whole bid is applied

        if ($token_amount > 0) {
#            Debug::trace("applyBid with token amount: $token_amount",__FILE__,__LINE__,$this);
            $this->applyBid($transaction, $token_amount);
        }

    }

    protected function applyToBidTokenFee($token_amount, AuctionState $state) {
        $amount_left = $this->auction['bidTokenFeeRequired'] - $state['bidTokenFeeApplied'];
        $amount_applied = min($amount_left, $token_amount);

        if ($amount_applied > 0) {
            $state->addLog("Applied ".CurrencyUtil::satoshisToNumber($amount_applied)." {$this->auction['bidTokenType']} to requirement of ".CurrencyUtil::satoshisToNumber($this->auction['bidTokenFeeRequired']));

            $state['bidTokenFeeApplied'] = $state['bidTokenFeeApplied'] + $amount_applied;

            if ($state['bidTokenFeeApplied'] >= $this->auction['bidTokenFeeRequired']) {
                $state['bidTokenFeeSatisfied'] = true;
                $state->addLog("{$this->auction['bidTokenType']} fee was paid");
            } else {
                $state->addLog("{$this->auction['bidTokenType']} fee remaining: ".CurrencyUtil::satoshisToNumber($this->auction['bidTokenFeeRequired'] - $state['bidTokenFeeApplied']));
            }
        }

        return $token_amount - $amount_applied;
    }

    ////////////////////////////////////////////////////////////////////////
    // BTC

    protected function handleIncomingBTC($transaction) {
        $state = $this->getStateAtBlockAndTime($transaction['blockId'], $transaction['timestamp'], $transaction['isMempool']);
        $token_amount = $transaction['quantity'];

        $state->addLog("Received ".CurrencyUtil::satoshisToNumber($token_amount)." BTC");

        if (!$state['btcFeeSatisfied']) {
            $token_amount = $this->applyToBTCFee($token_amount, $state);
            $this->refreshActiveStatus($state);
        } else {
            $state->addLog("Did not apply BTC to fee, because it was already paid");
        }
    }

    protected function applyToBTCFee($token_amount, AuctionState $state) {
        $amount_left = $this->auction['btcFeeRequired'] - $state['btcFeeApplied'];
        $amount_applied = min($amount_left, $token_amount);
        $state['btcFeeApplied'] = $state['btcFeeApplied'] + $amount_applied;

        $state->addLog("Applied ".CurrencyUtil::satoshisToNumber($amount_applied)." to BTC fee requirement of ".CurrencyUtil::satoshisToNumber($this->auction['btcFeeRequired']));

        if ($state['btcFeeApplied'] >= $this->auction['btcFeeRequired']) {
            $state['btcFeeSatisfied'] = true;
            $state->addLog("BTC fee was paid");
        } else {
            $state->addLog("BTC fee remaining: ".CurrencyUtil::satoshisToNumber($this->auction['btcFeeRequired'] - $state['btcFeeApplied']));
        }

        return $token_amount - $amount_applied;
    }

    ////////////////////////////////////////////////////////////////////////
    // Prize Token

    protected function handleIncomingPrizeToken($transaction) {
        $state = $this->getStateAtBlockAndTime($transaction['blockId'], $transaction['timestamp'], $transaction['isMempool']);
        $token_amount = $transaction['quantity'];

        $state->addLog("Received ".CurrencyUtil::satoshisToNumber($token_amount)." {$transaction['asset']} prize token");

        // apply
        // Debug::trace("\$state['prizeTokensSatisfied']=".Debug::desc($state['prizeTokensSatisfied'])."",__FILE__,__LINE__,$this);
        if (!$state['prizeTokensSatisfied']) {
            // prizeTokensApplied
            $prize_token_info = $this->auction->findPrizeTokenRequiredInfo($transaction['asset']);
            // echo "\$prize_token_info:\n".json_encode($prize_token_info, 192)."\n";
            $token_amount = $this->applyPrizeToken($token_amount, $prize_token_info, $state);

            // refresh the auction is now active
            $this->refreshActiveStatus($state);

        }

        if ($token_amount) {
            // extra prize token... hmmm...
            $state->addLog("Received ".CurrencyUtil::satoshisToNumber($token_amount)." {$transaction['asset']} extra prize token that I don't know what to do with.");
        }

    }

    protected function applyPrizeToken($token_amount, $prize_token_info, AuctionState $state) {
        $token = $prize_token_info['token'];
        $amount_left = $prize_token_info['amount'] - $state->getPrizeTokenAppliedAmount($token);
        $amount_applied = min($amount_left, $token_amount);
#        Debug::trace("\$amount_left=".Debug::desc($amount_left)." \$amount_applied=".Debug::desc($amount_applied)."",__FILE__,__LINE__,$this);

        if ($amount_applied > 0) {
            $state->addLog("Applied ".CurrencyUtil::satoshisToNumber($amount_applied)." {$token} to requirement of ".CurrencyUtil::satoshisToNumber($prize_token_info['amount']));

            $state->setPrizeTokenAppliedAmount($token, $state->getPrizeTokenAppliedAmount($token) + $amount_applied);

            if ($state->getPrizeTokenAppliedAmount($token) >= $prize_token_info['amount']) {
                $state->addLog("Sufficient amount of {$token} was received");

                if ($state->prizeTokensAreSatisfied($this->auction['prizeTokensRequired'])) {
                    $state['prizeTokensSatisfied'] = true;
                    $state->addLog("All prize tokens received");
                } else {
                    $state->addLog("There are still prize tokens needed");
                }
            } else {
                $state->addLog("Still need to receive ".CurrencyUtil::satoshisToNumber($prize_token_info['amount'] - $state->getPrizeTokenAppliedAmount($token))." {$token}");
            }
        }

        return $token_amount - $amount_applied;
    }

    ////////////////////////////////////////////////////////////////////////
    // active status

    protected function refreshActiveStatus(AuctionState $state) {
        $previous_active_status = $state['active'];
        $active_status = ($state['bidTokenFeeSatisfied'] AND $state['btcFeeSatisfied'] AND $state['prizeTokensSatisfied']);
#        Debug::trace("\$active_status=".Debug::desc($active_status)."",__FILE__,__LINE__,$this);

        if ($previous_active_status != $active_status) {
            $state->addLog("State active flag updated to ".Debug::desc($active_status)."");
        }

        $state['active'] = $active_status;
    }

    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////
    // Bidding

    protected function applyBid($transaction, $token_amount) {
        $state = $this->getStateAtBlockAndTime($transaction['blockId'], $transaction['timestamp'], $transaction['isMempool']);

        // convert any prebids if we are ready before processing bids
        $state = $this->getAuctioneer()->convertPrebidsIfReady($state);

        $state->ensureAccountAt($transaction['source'], $transaction['id']);
        $account = $state->getAccount($transaction['source']);
        $bid_status = $this->determineBidStatus($transaction);
        $account->addBalance($token_amount, $transaction['asset'], $bid_status);

        $state->addLog("Added {$bid_status} bid of ".CurrencyUtil::satoshisToNumber($token_amount)." for {$account['address']} to {$state['timePhase']} auction");

        $state = $this->getAuctioneer()->updateAllBids($state);
    }

    protected function determineBidStatus($transaction) {
        switch (true) {
            case ($transaction['timestamp'] < $this->auction['startDate']):
                return 'prebid';
                break;

            // case ($this->auction['active'] == false):
            //     // if the auction is not active, treat all bids like a prebid
            //     return 'prebid';
            //     break;

            case ($transaction['timestamp'] >= $this->auction['endDate']):
                return 'late';
                break;
        }

        return 'live';
    }

    protected function getAuctioneer() {
        if (!isset($this->auctioneer)) {
            $this->auctioneer = new Auctioneer($this->auction);
        }
        return $this->auctioneer;
    }

    /////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

    protected function applyOutgoingTransactionToState($transaction) {
        // throw new Exception("Unimplemented", 1);
        // nothing yet
    }

    protected function hasBiddingAsset($transaction) {
        return $transaction['asset'] == $this->auction['bidTokenType'];
    }

    protected function isBTCTransaction($transaction) {
        return $transaction['asset'] == 'BTC';
    }

    protected function handleUknownIncomingAsset($transaction) {
#       Debug::trace("handleUknownIncomingAsset",__FILE__,__LINE__,$this);
        if ($prize_token_info = $this->auction->findPrizeTokenRequiredInfo($transaction['asset'])) {
            $this->handleIncomingPrizeToken($transaction, $prize_token_info);
        } else {
            $state = $this->getStateAtBlockAndTime($transaction['blockId'], $transaction['timestamp'], $transaction['isMempool']);
            $state->addLog("Received ".CurrencyUtil::satoshisToNumber($transaction['quantity'])." of {$transaction['asset']}.  This token is not recognized by this auction.");
        }
    }

    protected function isPrizeToken($token) {
        return ($this->auction->findPrizeTokenRequiredInfo($token) ? true : false);
    }

    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////
    // State

    protected function getState() {
        if (!isset($this->auction_state)) {
            $this->auction_state = new AuctionState();
        }
        return $this->auction_state;
    }

    protected function getStateAtBlockAndTime($block_id, $timestamp, $is_mempool) {
        $state = $this->getState();
        $state['hasMempoolTransactions'] = false;

        if ($is_mempool) {
            if ($block_id AND $block_id > 0) { throw new Exception("Unexpected block_id of ".Debug::desc($block_id)." for mempool transaction", 1); }
            // this is a mempool transaction
            $block_id = $this->meta_info['blockHeight'];
            $state['hasMempoolTransactions'] = true;
            $timestamp = $this->now();

#            Debug::trace("\$state['hasMempoolTransactions']=".Debug::desc($state['hasMempoolTransactions'])."",__FILE__,__LINE__,$this);
        } else {
#            Debug::trace("\$state['hasMempoolTransactions']=".Debug::desc($state['hasMempoolTransactions'])."",__FILE__,__LINE__,$this);
            if (!$block_id) { throw new Exception("Unexpected block_id of ".Debug::desc($block_id)." for non-mempool transaction", 1); }
        }

        $state->setBlockId($block_id);
        $state['timePhase'] = $this->buildAuctionTimePhase($timestamp);
        return $state;
    }

    protected function finalizeState($state) {
        if (!$state) { return $state; }
        // update the state status based on the current time (not the last transaction)
        $state['timePhase'] = $this->buildAuctionTimePhase($this->now());
#       Debug::trace("finalizeState this->now()=".Debug::desc(date("Y-m-d H:i:s", $this->now()))." \$state['timePhase']=".Debug::desc($state['timePhase'])."",__FILE__,__LINE__,$this);

        // convert any prebids if the auction ended with prebids
        $state = $this->getAuctioneer()->convertPrebidsIfReady($state);

        // bring bids up to date
        $this->getAuctioneer()->updateAllBids($state);

        // bring payouts up to date
        $this->getAuctioneer()->updateAllPayouts($state, $this->meta_info['blockHeight']);

        return $state;
    }

    protected function serializeState(AuctionState $state=null) {
        if ($state === null) { return null; }
        return $state->serialize();
    }

}

// ########################################################################
// auction:
//   id                   : 101
//   name                 : "Auction One"
//   slug                 : "auction-one"
//   description          : "Best auction ever"
//   create            : 2014-07-31
//   startDate            : 2014-08-01 00:00:00
//   endDate              : 2014-08-05 00:00:00
//   minStartingBid       : 1000
//   bidTokenType         : "LTBCOIN"
//   minBidIncrement      : 1000
//   # startingBounty     : 0

//   bidTokenFeeRequired  : 1000
//   btcFeeRequired       : 0.05

//   winningTokenQuantity : 1
//   winningTokenType     : "SPONSOR"

//   auctionAddress   : "1AUCTION01"

// ########################################################################
// transactions:
//   -
//     auctionId      : 101
//     transactionId  : 5001
//     blockId        : 6001

//     classification : incoming

//     source         : 1OWNER01__________________________
//     destination    : 1AUCTION01
//     asset          : LTBCOIN
//     quantity       : 1000
//     status         : valid
//     tx_hash        : HASH01________________________________
    // timestamp      : 2014-08-04 00:00:00

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableSuperClasses #-}

module T10592 where

import Data.Kind (Type)
import Prelude (Bool(True,False),Integer,Ordering)
import qualified Prelude

--------------------
-- class hierarchy

class Boolean (Logic a) => Eq a where
    type Logic a :: Type
    (==) :: a -> a -> Logic a

    (/=) :: a -> a -> Logic a
    a/=b = not (a==b)

class Eq a => POrd a where
    inf :: a -> a -> a

class POrd a => MinBound a where
    minBound :: a

class POrd a => Lattice a where
    sup :: a -> a -> a

class (Lattice a, MinBound a) => Bounded a where
    maxBound :: a

class Bounded a => Complemented a where
    not :: a -> a

class Bounded a => Heyting a where
    infixr 3 ==>
    (==>) :: a -> a -> a

class (Complemented a, Heyting a) => Boolean a

(||) :: Boolean a => a -> a -> a
(||) = sup

(&&) :: Boolean a => a -> a -> a
(&&) = inf

--------------------
-- Bool instances
-- (these work fine)

instance Eq Bool where
    type Logic Bool = Bool
    (==) = (Prelude.==)

instance POrd Bool where
    inf True  True  = True
    inf _     _     = False

instance MinBound Bool where
    minBound = False

instance Lattice Bool where
    sup False False = False
    sup _     _     = True

instance Bounded Bool where
    maxBound = True

instance Complemented Bool where
    not True  = False
    not False = True

instance Heyting Bool where
    False ==> _ = True
    True  ==> a = a

instance Boolean Bool

--------------------
-- Integer instances
-- (these work fine)

instance Eq Integer where
    type Logic Integer = Bool
    (==) = (Prelude.==)

instance POrd Integer where
    inf = Prelude.min

instance Lattice Integer where
    sup = Prelude.max

--------------------
-- function instances
-- (these cause GHC to loop)

instance Eq b => Eq (a -> b) where
    type Logic (a -> b) = a -> Logic b
    f==g = \a -> f a == g a

instance POrd b => POrd (a -> b) where
    inf f g = \a -> inf (f a) (g a)

instance MinBound b => MinBound (a -> b) where
    minBound = \_ -> minBound

instance Lattice b => Lattice (a -> b) where
    sup f g = \a -> sup (f a) (g a)

instance Bounded b => Bounded (a -> b) where
    maxBound = \_ -> maxBound

instance Complemented b => Complemented (a -> b) where
    not f = \a -> not (f a)

instance Heyting b => Heyting (a -> b) where
    f ==> g = \a -> f a ==> g a

instance Boolean b => Boolean (a -> b)


text:
Page({
  data:{
    // text:"这是一个页面"
    configs:{}
  },
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数
      var configs = wx.getStorageSync('configs');
      this.setData({configs:configs});
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  },
  switchChange:function(e){
    var id = e.target.id;
    var configs = this.data.configs;
    var config = configs[id];
    if(!config){
      config = new Object();
      configs[id] = config;
    }
    config.state = e.detail.value;
    this.setData ({configs : configs});
    wx.setStorageSync('configs',configs);
  },

  sliderChange:function(e){
    var id = e.target.id;
    var configs = this.data.configs;
    var config = configs[id];
    if(!config){
      config = new Object();
      configs[id] = config;
    }
    config.time = e.detail.value;
    this.setData ({configs : configs});
    wx.setStorageSync('configs',configs);
  },
  radioChange:function(e){
    var id = e.target.id;
    var configs = this.data.configs;
    var config = configs[id];
    if(!config){
      config = new Object();
      configs[id] = config;
    }
    config.voice = e.detail.value;
    this.setData ({configs : configs});
    wx.setStorageSync('configs',configs);
  }
})


text:
import nomad.api.exceptions

from nomad.api.base import Requester

class Deployment(Requester):

    """
    The /deployment endpoints are used to query for and interact with deployments.

    https://www.nomadproject.io/docs/http/deployments.html
    """
    ENDPOINT = "deployment"

    def __init__(self, **kwargs):
        super(Deployment, self).__init__(**kwargs)

    def __str__(self):
        return "{0}".format(self.__dict__)

    def __repr__(self):
        return "{0}".format(self.__dict__)

    def __getattr__(self, item):
        msg = "{0} does not exist".format(item)
        raise AttributeError(msg)

    def __contains__(self, item):

        try:
            d = self.get_deployment(item)
            return True
        except nomad.api.exceptions.URLNotFoundNomadException:
            return False

    def __getitem__(self, item):

        try:
            d = self.get_deployment(item)

            if d["ID"] == item:
                return d
        except nomad.api.exceptions.URLNotFoundNomadException:
            raise KeyError

    def get_deployment(self, id):
        """ This endpoint reads information about a specific deployment by ID.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        return self.request(id, method="get").json()

    def get_deployment_allocations(self, id):
        """ This endpoint lists the allocations created or modified for the given deployment.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
            returns: list of dicts
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        return self.request("allocations", id, method="get").json()

    def fail_deployment(self, id):
        """ This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop
            creating allocations as part of the deployment or to cause a rollback to a previous job version.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        fail_json = {"DeploymentID": id}
        return self.request("fail", id, json=fail_json, method="post").json()

    def pause_deployment(self, id, pause):
        """ This endpoint is used to pause or unpause a deployment.
            This is done to pause a rolling upgrade or resume it.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
              - pause, Specifies whether to pause or resume the deployment.
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        pause_json = {"Pause": pause,
                      "DeploymentID": id}
        return self.request("pause", id, json=pause_json, method="post").json()

    def promote_deployment_all(self, id, all=True):
        """ This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
            the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
              - all, Specifies whether all task groups should be promoted.
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        promote_all_json = {"All": all,
                            "DeploymentID": id}
        return self.request("promote", id, json=promote_all_json, method="post").json()

    def promote_deployment_groups(self, id, groups=list()):
        """ This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
            the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
              - groups, (list) Specifies a particular set of task groups that should be promoted
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        promote_groups_json = {"Groups": groups,
                               "DeploymentID": id}
        return self.request("promote", id, json=promote_groups_json, method="post").json()

    def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()):
        """ This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
            cases, automatic detection of allocation health may not be desired. As such those task groups can be marked
            with an upgrade policy that uses health_check = "manual". Those allocations must have their health marked
            manually using this endpoint. Marking an allocation as healthy will allow the rolling upgrade to proceed.
            Marking it as failed will cause the deployment to fail.

           https://www.nomadproject.io/docs/http/deployments.html

            arguments:
              - id
              - healthy_allocations, Specifies the set of allocation that should be marked as healthy.
              - unhealthy_allocations,  Specifies the set of allocation that should be marked as unhealthy.
            returns: dict
            raises:
              - nomad.api.exceptions.BaseNomadException
              - nomad.api.exceptions.URLNotFoundNomadException
        """
        allocations = {"HealthyAllocationIDs": healthy_allocations,
                       "UnHealthyAllocationIDs": unhealthy_allocations,
                       "DeploymentID": id}
        return self.request("allocation-health", id, json=allocations, method="post").json()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>mathcomp-real-closed: Error 🔥</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / extra-dev

dev / mathcomp-real-closed - 1.1.2

            « Up

              mathcomp-real-closed

                1.1.2
                Error 🔥

📅  (2022-05-10 21:30:59 UTC)

Context

# Packages matching: installed
# Name                # Installed # Synopsis
base-bigarray         base
base-threads          base
base-unix             base
conf-findutils        1           Virtual package relying on findutils
conf-gmp              4           Virtual package relying on a GMP lib system installation
coq                   dev         Formal proof management system
dune                  3.1.1       Fast, portable, and opinionated build system
ocaml                 4.13.1      The OCaml compiler (virtual package)
ocaml-base-compiler   4.13.1      Official release 4.13.1
ocaml-config          2           OCaml Switch Configuration
ocaml-options-vanilla 1           Ensure that OCaml is compiled with no special options enabled
ocamlfind             1.9.3       A library manager for OCaml
zarith                1.12        Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Cyril Cohen <cyril.cohen@inria.fr>"
homepage: "https://github.com/math-comp/real-closed"
dev-repo: "git+https://github.com/math-comp/real-closed.git"
bug-reports: "https://github.com/math-comp/real-closed/issues"
license: "CECILL-B"
synopsis: "Mathematical Components Library on real closed fields"
description: """
This library contains definitions and theorems about real closed
fields, with a construction of the real closure and the algebraic
closure (including a proof of the fundamental theorem of
algebra). It also contains a proof of decidability of the first
order theory of real closed field, through quantifier elimination."""
build: [make "-j%{jobs}%" ]
install: [make "install"]
depends: [
  "coq" { (>= "8.10" & < "8.16~") | (= "dev") }
  "coq-mathcomp-ssreflect" { (>= "1.12.0" & < "1.15~") | (= "dev")  }
  "coq-mathcomp-algebra" { (>= "1.12.0" & < "1.15~") | (= "dev")  }
  "coq-mathcomp-field" { (>= "1.12.0" & < "1.15~") | (= "dev")  }
  "coq-mathcomp-bigenough" {>= "1.0.0"}
]
tags: [
  "keyword:real closed field"
  "logpath:mathcomp.real_closed"
]
authors: [
  "Cyril Cohen"
  "Assia Mahboubi"
]
url {
  src: "https://github.com/math-comp/real-closed/archive/1.1.2.tar.gz"
  checksum: "sha256=84e0ddf33dbbc249287dfc8fc7874d433c79cee2b335f32b6476a46a71376892"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-mathcomp-real-closed.1.1.2 coq.dev

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-real-closed.1.1.2 coq.dev

Return code

0

Duration

21 m 59 s

Install 🚀

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-real-closed.1.1.2 coq.dev

Return code

7936

Duration

1 m 49 s

Output

# Packages matching: installed
# Name                 # Installed # Synopsis
base-bigarray          base
base-threads           base
base-unix              base
conf-findutils         1           Virtual package relying on findutils
conf-gmp               4           Virtual package relying on a GMP lib system installation
coq                    dev         Formal proof management system
coq-mathcomp-algebra   dev         Mathematical Components Library on Algebra
coq-mathcomp-bigenough dev         A small library to do epsilon - N reasonning
coq-mathcomp-field     dev         Mathematical Components Library on Fields
coq-mathcomp-fingroup  dev         Mathematical Components Library on finite groups
coq-mathcomp-solvable  dev         Mathematical Components Library on finite groups (II)
coq-mathcomp-ssreflect dev         Small Scale Reflection
dune                   3.1.1       Fast, portable, and opinionated build system
ocaml                  4.13.1      The OCaml compiler (virtual package)
ocaml-base-compiler    4.13.1      Official release 4.13.1
ocaml-config           2           OCaml Switch Configuration
ocaml-options-vanilla  1           Ensure that OCaml is compiled with no special options enabled
ocamlfind              1.9.3       A library manager for OCaml
zarith                 1.12        Implements arithmetic and logical operations over arbitrary-precision integers
[NOTE] Package coq is already installed (current version is dev).
The following actions will be performed:
  - install coq-mathcomp-real-closed 1.1.2
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/1: [coq-mathcomp-real-closed.1.1.2: http]
[coq-mathcomp-real-closed.1.1.2] downloaded from https://github.com/math-comp/real-closed/archive/1.1.2.tar.gz
Processing  1/1:
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/2: [coq-mathcomp-real-closed: make]
+ /home/bench/.opam/opam-init/hooks/sandbox.sh "build" "make" "-j4" (CWD=/home/bench/.opam/ocaml-base-compiler.4.13.1/.opam-switch/build/coq-mathcomp-real-closed.1.1.2)
- coq_makefile -f _CoqProject -o Makefile.coq
- make --no-print-directory -f Makefile.coq
- COQDEP VFILES
- COQC theories/polyorder.v
- COQC theories/ordered_qelim.v
- COQC theories/mxtens.v
- COQC theories/cauchyreals.v
- COQC theories/polyrcf.v
- File "./theories/ordered_qelim.v", line 719, characters 0-80:
- Warning:
- SSReflect: cannot obtain new equations out of
-   (is_true (rterm _t_ && rterm _t1_))
- Did you write an extra [] in the intro pattern? [spurious-ssr-injection,ssr]
- File "./theories/ordered_qelim.v", line 719, characters 0-80:
- Warning:
- SSReflect: cannot obtain new equations out of
-   (is_true (rterm _t_ && rterm _t1_))
- Did you write an extra [] in the intro pattern? [spurious-ssr-injection,ssr]
- File "./theories/ordered_qelim.v", line 719, characters 0-80:
- Warning:
- SSReflect: cannot obtain new equations out of
-   (is_true (rterm _t_ && rterm _t1_))
- Did you write an extra [] in the intro pattern? [spurious-ssr-injection,ssr]
- File "./theories/ordered_qelim.v", line 719, characters 0-80:
- Warning:
- SSReflect: cannot obtain new equations out of
-   (is_true (rformula _f_))
- Did you write an extra [] in the intro pattern? [spurious-ssr-injection,ssr]
- File "./theories/cauchyreals.v", line 881, characters 24-32:
- Warning: Notation iota_add is deprecated since mathcomp 1.13.0.
- Use iotaD instead. [deprecated-syntactic-definition,deprecated]
- File "./theories/cauchyreals.v", line 881, characters 24-32:
- Warning: Notation iota_add is deprecated since mathcomp 1.13.0.
- Use iotaD instead. [deprecated-syntactic-definition,deprecated]
- File "./theories/cauchyreals.v", line 881, characters 24-32:
- Warning: Notation iota_add is deprecated since mathcomp 1.13.0.
- Use iotaD instead. [deprecated-syntactic-definition,deprecated]
- COQC theories/qe_rcf_th.v
- COQC theories/realalg.v
- File "./theories/qe_rcf_th.v", line 296, characters 45-46:
- Error:
- In environment
- R : rcfType
- R0 : realDomainType
- s : R0
- n : nat
- The term "2" has type "GRing.Zmodule.sort ?t"
- while it is expected to have type "nat".
-
- make[2]: *** [Makefile.coq:791: theories/qe_rcf_th.vo] Error 1
- make[2]: *** Waiting for unfinished jobs....
- make[1]: *** [Makefile.coq:408: all] Error 2
- make: *** [Makefile:15: invoke-coqmakefile] Error 2
[ERROR] The compilation of coq-mathcomp-real-closed failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build make -j4".
#=== ERROR while compiling coq-mathcomp-real-closed.1.1.2 =====================#
# context              2.0.10 | linux/x86_64 | ocaml-base-compiler.4.13.1 | file:///home/bench/run/opam-coq-archive/released
# path                 ~/.opam/ocaml-base-compiler.4.13.1/.opam-switch/build/coq-mathcomp-real-closed.1.1.2
# command              ~/.opam/opam-init/hooks/sandbox.sh build make -j4
# exit-code            2
# env-file             ~/.opam/log/coq-mathcomp-real-closed-17270-335865.env
# output-file          ~/.opam/log/coq-mathcomp-real-closed-17270-335865.out
### output ###
# [...]
# In environment
# R : rcfType
# R0 : realDomainType
# s : R0
# n : nat
# The term "2" has type "GRing.Zmodule.sort ?t"
# while it is expected to have type "nat".
#
# make[2]: *** [Makefile.coq:791: theories/qe_rcf_th.vo] Error 1
# make[2]: *** Waiting for unfinished jobs....
# make[1]: *** [Makefile.coq:408: all] Error 2
# make: *** [Makefile:15: invoke-coqmakefile] Error 2
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-mathcomp-real-closed 1.1.2
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment
'opam install -y -v coq-mathcomp-real-closed.1.1.2 coq.dev' failed.

Installation size

No files were installed.

Uninstall 🧹

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
/*=============================================================================
VideoCore OS Abstraction Layer - memory pool support
=============================================================================*/

#ifndef VCOS_MEMPOOL_H
#define VCOS_MEMPOOL_H

#ifdef __cplusplus
extern "C" {
#endif

#include "vcos_types.h"
#include "pthreads/vcos_platform.h"

/** \file
  *
  * Memory pools - variable sized allocator.
  *
  * A very basic memory pool API.
  *
  * This interface is deliberately not thread safe - clients should add
  * their own locking, if required.
  *
  *
  * \fixme: Add fixed-size allocator.
  *
  */

/** Initialize a memory pool. The control data is taken from the memory
  * supplied itself.
  *
  * Note: the dmalloc pool uses the memory supplied for its control
  * area. This is probably a bit broken, as it stops you creating
  * a pool in some "special" area of memory, while leaving the control
  * information in normal memory.
  *
  * @param pool  Pointer to pool object.
  *
  * @param name  Name for the pool. Used for diagnostics.
  *
  * @param start Starting address. Must be at least 8byte aligned.
  *
  * @param size  Size of pool in bytes.
  *
  * @return VCOS_SUCCESS if pool was created.
  */
VCOS_INLINE_DECL
VCOS_STATUS_T vcos_mempool_create(VCOS_MEMPOOL_T *pool, const char *name, void *start, VCOS_UNSIGNED size);

/** Allocate some memory from a pool. If no memory is available, it
  * returns NULL.
  *
  * @param pool Pool to allocate from
  * @param len  Length of memory to allocate
  *
  */
VCOS_INLINE_DECL
void *vcos_mempool_alloc(VCOS_MEMPOOL_T *pool, VCOS_UNSIGNED len);

/** Free some memory back to a pool.
  *
  * @param pool Pool to return to
  * @param mem Memory to return
  */
VCOS_INLINE_DECL
void vcos_mempool_free(VCOS_MEMPOOL_T *pool, void *mem);

/** Deinitialize a memory pool.
  *
  * @param pool Pool to return to
  */
VCOS_INLINE_DECL
void vcos_mempool_delete(VCOS_MEMPOOL_T *pool);

#ifdef __cplusplus
}
#endif
#endif


text:
<SageTVPlugin>
  <Name>Season-Episode display for Malore Recordings</Name>
  <Identifier>maloreseasonepisode</Identifier>
  <Description>Season-Episode Display for Malore Recordings.  Requires SeasonNumber and EpisodeNumber metadata tags, as generated by the Phoenix API (or others).</Description>
  <Author>Fuzzy</Author>
  <CreationDate>2010-06-29</CreationDate>
  <ModificationDate>2010.06.29</ModificationDate>
  <Version>1.0.0</Version>
  <PluginType>STVI</PluginType>
  <ReleaseNotes>1.0.0 - Initial Release</ReleaseNotes>
  <Screenshot>http://dl.dropbox.com/u/8593871/Malore_SeasonEpisode.jpg</Screenshot>
  <Dependency>
    <STV>SageTV7</STV>
    <MinVersion>7.0</MinVersion>
 </Dependency><Package>
    <PackageType>STVI</PackageType>
   <Location>http://dl.dropbox.com/u/8593871/Malore_SeasonEpisode.zip</Location>
    <MD5>69CC4439D2336FC8848BA48E647444BC</MD5>
  </Package>
  <STVImport>Malore_SeasonEpisode.stvi</STVImport>
</SageTVPlugin>


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 320854;
var summary = 'o.hasOwnProperty("length") should not lie when o has function in proto chain';
var actual = '';
var expect = '';

printBugNumber(BUGNUMBER);
printStatus (summary);

var o = {__proto__:function(){}};

expect = false;
actual = o.hasOwnProperty('length')

  reportCompare(expect, actual, summary);


text:
import React, {Component} from 'react';
import './../App.css';
import plus_open from './../img/plus-open.png'

class SavedItem extends Component {
  constructor(props) {
      super(props);
      this.state = {
          open: false
      };
  }
  opentext(id) {

      this.setState({open: !this.state.open});

  }

  componentWillReceiveProps() {
    this.setState({open: false}) // close all open text snippets
  }

  htmldecode(input) {
      var doc = new DOMParser().parseFromString(input, "text/html");
      return doc.documentElement.textContent;
  }

    render() {

        return (

                    {this.props.data.thumbnail !== false &&

}

                    {this.props.data.title}

                  {this.props.data.body_html !== false &&  this.opentext(this.props.data.id)} role="presentation" src={plus_open}/>} {this.props.data.subreddit} | {this.props.data.domain} | {this.props.data.author} | {this.props.data.time}

Comments

                {this.state.open === true &&

}

        )

    }

}

export default SavedItem;


text:
package com.insightml.models;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esotericsoftware.kryo.KryoException;
import com.insightml.data.FeaturesConfig;
import com.insightml.data.samples.Sample;
import com.insightml.models.general.CVLearner;
import com.insightml.models.meta.MajorityVoteLearner;
import com.insightml.utils.Arguments;
import com.insightml.utils.Check;
import com.insightml.utils.IArguments;
import com.insightml.utils.Regex;
import com.insightml.utils.io.serialization.Serialization;
import com.insightml.utils.types.AbstractClass;

public final class ArgumentParser extends AbstractClass {
	private static final Logger LOG = LoggerFactory.getLogger(ArgumentParser.class);

	private ArgumentParser() {
	}

	public static <S extends Sample, E, O> ILearner<S, E, O>[] parseLearners(final IArguments arguments,
			final ArgumentParserContext context) {
		final List<ILearner<?, ?, ?>> learners = new LinkedList<>();
		for (int i = 1;; ++i) {
			if (!arguments.containsKey("l" + i)) {
				break;
			}
			final Arguments argSelection = new Arguments();
			for (final Entry<String, Serializable> entry : arguments.entrySet()) {
				final String key = entry.getKey();
				if (key.startsWith("l" + i + "-")) {
					argSelection.set(key.substring(3), entry.getValue());
				} else if (!key.startsWith("l") || !Regex.contains(key, Pattern.compile("^l[0-9]-"))) {
					argSelection.set(key, entry.getValue());
				}
			}
			final ILearner<?, ?, ?> learner = parseLearner(arguments.toString("l" + i), argSelection, context);
			learners.add(learner);
		}
		Check.argument(learners.size() > 0);
		return learners.toArray(new ILearner[learners.size()]);
	}

	public static ILearner<?, ?, ?> parseLearner(final String learner, final IArguments arguments,
			final ArgumentParserContext context) {
		return new LearnerProxy<>(learner, arguments, context);
	}

	private static final class LearnerProxy<S extends Sample, E, O> implements ILearner<S, E, O>, Serializable {

		private static final long serialVersionUID = 4485063208928711429L;

		private final String learner;
		private final IArguments arguments;
		private final ArgumentParserContext context;

		LearnerProxy(final String learner, final IArguments arguments, final ArgumentParserContext context) {
			this.learner = learner;
			this.arguments = arguments;
			this.context = context;
		}

		@Override
		public String getName() {
			return resolve().getName();
		}

		@Override
		public LearnerArguments arguments() {
			return resolve().arguments();
		}

		@Override
		public IArguments getOriginalArguments() {
			return arguments;
		}

		@Override
		public IModelPipeline<S, O> run(final Iterable<S> data, final Iterable<S> unlabled,
				final FeaturesConfig<? extends S, O> config, final int labelIndex,
				final ILearnerPipeline<S, O> learnerPipe) {
			final ILearner<S, E, O> resolved = resolve();
			if (context == null || !cacheModel(resolved)) {
				return resolved.run(data, unlabled, config, labelIndex, learnerPipe);
			}
			final File file = new File(context.getModelCacheDirectory() + "/model_" + resolved.getName() + "_"
					+ data.hashCode() + "_" + config.hashCode() + "_" + arguments.toString("features", "all"));
			if (file.exists()) {
				LOG.info("Loading model from {}", file);
				try {
					return Serialization.get().unserialize(file, ModelPipelineContainer.class).model;
				} catch (final Throwable e) {
					e.printStackTrace();
				}
			}
			LOG.info("Could not find model in {}, creating new", file);
			file.getParentFile().mkdirs();
			final IModelPipeline<S, O> model = resolved.run(data, unlabled, config, labelIndex, learnerPipe);
			if (file.getName().length() < 255) {
				try {
					Serialization.get().serialize(file, new ModelPipelineContainer<>(model));
				} catch (final KryoException e) {
					LOG.error("{}", e.getMessage(), e);
				}
			}
			return model;
		}

		@Override
		public IModel<S, O> run(final LearnerInput<? extends S, ? extends E> input) {
			final ILearner<S, E, O> resolved = resolve();
			if (context == null || !cacheModel(resolved)) {
				return resolved.run(input.getTrain(), input.valid, input.config, input.labelIndex);
			}
			final File file = new File(context.getModelCacheDirectory() + "/model_" + resolved.getName() + "_"
					+ input.hashCode() + "_" + arguments.toString("features", "all"));
			if (file.exists()) {
				LOG.info("Loading model from {}", file);
				try {
					return Serialization.get().unserialize(file, ModelContainer.class).model;
				} catch (final Throwable e) {
					e.printStackTrace();
				}
			}
			LOG.info("Could not find model in {}, creating new", file);
			file.getParentFile().mkdirs();
			final IModel<S, O> model = resolved.run(input.getTrain(), input.valid, input.config, input.labelIndex);
			Serialization.get().serialize(file, new ModelContainer<>(model));
			return model;
		}

		private boolean cacheModel(final ILearner<S, E, O> resolved) {
			return !(resolved instanceof MajorityVoteLearner);
		}

		private ILearner<S, E, O> resolve() {
			if (learner.endsWith(".csv")) {
				try {
					return (ILearner<S, E, O>) new CVLearner(learner, 0);
				} catch (final IOException e) {
					throw new UncheckedIOException(e);
				}
			}
			final String name = learner.toLowerCase(Locale.ENGLISH);
			return (ILearner<S, E, O>) LearnerRepository.get(name, arguments);
		}
	}

	static final class ModelContainer<S extends Sample, O> implements Serializable {
		private static final long serialVersionUID = 7889769800205553825L;

		private IModel<S, O> model;

		ModelContainer() {
		}

		public ModelContainer(final IModel<S, O> model) {
			this.model = model;
		}
	}

	static final class ModelPipelineContainer<S extends Sample, O> implements Serializable {
		private static final long serialVersionUID = -4546730350632751985L;

		private IModelPipeline<S, O> model;

		ModelPipelineContainer() {
		}

		public ModelPipelineContainer(final IModelPipeline<S, O> model) {
			this.model = model;
		}
	}
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2008 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
 */
#ifndef COMMAND_LINE_H
#define COMMAND_LINE_H

#include <string>
#include <sstream>
#include <list>

#include "callback.h"

namespace ns3 {

/**
 * \brief parse command-line arguments
 * \ingroup core
 *
 * Instances of this class can be used to parse command-line
 * arguments: users can register new arguments with
 * CommandLine::AddValue but the most important functionality
 * provided by this class is that it can be used to set the
 * 'initial value' of every attribute in the system with the
 * \verbatim
 *   --TypeIdName::AttributeName=value
 * \endverbatim
 * syntax and it can be used to set the value of every GlobalValue
 * in the system with the
 * \verbatim
 *   --GlobalValueName=value
 * \endverbatim
 * syntax.
 */
class CommandLine
{
public:
  CommandLine ();
  CommandLine (const CommandLine &cmd);
  CommandLine &operator = (const CommandLine &cmd);
  ~CommandLine ();

  /**
   * \param name the name of the user-supplied argument
   * \param help some help text used by --PrintHelp
   * \param value a reference to the variable where the
   *        value parsed will be stored (if no value
   *        is parsed, this variable is not modified).
   */
  template <typename T>
  void AddValue (const std::string &name,
                 const std::string &help,
                 T &value);

  /**
   * \param name the name of the user-supplied argument
   * \param help some help text used by --PrintHelp
   * \param callback a callback function that will be invoked to parse
   * and collect the value.  This normally used by language bindings.
   */
  void AddValue (const std::string &name,
                 const std::string &help,
                 Callback<bool, std::string> callback);

  /**
   * \param argc the 'argc' variable: number of arguments (including the
   *        main program name as first element).
   * \param argv the 'argv' variable: a null-terminated array of strings,
   *        each of which identifies a command-line argument.
   *
   * Obviously, this method will parse the input command-line arguments and
   * will attempt to handle them all.
   */
  void Parse (int argc, char *argv[]) const;
private:
  class Item
  {
public:
    std::string m_name;
    std::string m_help;
    virtual ~Item ();
    virtual bool Parse (std::string value) = 0;
  };
  template <typename T>
  class UserItem : public Item
  {
public:
    virtual bool Parse (std::string value);
    T *m_valuePtr;
  };
  class CallbackItem : public Item
  {
public:
    virtual bool Parse (std::string value);
    Callback<bool, std::string> m_callback;
  };

  void HandleArgument (std::string name, std::string value) const;
  void PrintHelp (void) const;
  void PrintGlobals (void) const;
  void PrintAttributes (std::string type) const;
  void PrintGroup (std::string group) const;
  void PrintTypeIds (void) const;
  void PrintGroups (void) const;
  void Copy (const CommandLine &cmd);
  void Clear (void);

  typedef std::list<Item *> Items;
  Items m_items;
};

} // namespace ns3

namespace ns3 {

template <typename T>
void
CommandLine::AddValue (const std::string &name,
                       const std::string &help,
                       T &value)
{
  UserItem<T> *item = new UserItem<T> ();
  item->m_name = name;
  item->m_help = help;
  item->m_valuePtr = &value;
  m_items.push_back (item);
}

template <typename T>
bool
CommandLine::UserItem<T>::Parse (std::string value)
{
  std::istringstream iss;
  iss.str (value);
  iss >> (*m_valuePtr);
  return !iss.bad () && !iss.fail ();
}

} // namespace ns3

#endif /* COMMAND_LINE_H */


text:
layout: post
title: Release of 1.2.2
subtitle: Patch release
date: 2021-03-23T12:00:00+00:00
categories:
  - Releases
---

JSXGraph version v1.2.2 contains a few improvements and bug fixes, see <https://github.com/jsxgraph/jsxgraph/blob/master/CHANGELOG.md>.

Enjoy,

Matthias Ehmann, Michael Gerhäuser, Carsten Miller, Andreas Walter, and Alfred Wassermann


text:
import {NgModule} from '@angular/core';
import {ProgressBarService} from '../services/progress-bar.service';
import {MaterialModule} from './material.module';
import {TranslateModule} from '@ngx-translate/core';

@NgModule({
  declarations: [],
  exports: [
    MaterialModule,
    TranslateModule
  ],
  providers: [ProgressBarService]
})

export class SharedModule {
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.util.polling;

import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.implementation.PollContextRequiredException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * INTERNAL PACKAGE PRIVATE CLASS
 *
 * Default implementation of {@link SyncPoller} that uses blocking reactor call underneath.
 * The DefaultSyncPoller is not thread safe but we make every attempt to be safe in cases
 * it is possible to be so, e.g. by using volatile and copying context.
 *
 * @param <T> The type of poll response value
 * @param <U> The type of the final result of the long running operation
 */
final class DefaultSyncPoller<T, U> implements SyncPoller<T, U> {
    private final ClientLogger logger = new ClientLogger(DefaultSyncPoller.class);
    private final Duration defaultPollInterval;
    private final Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation;
    private final BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation;
    private final Function<PollingContext<T>, Mono<U>> fetchResultOperation;
    private final PollResponse<T> activationResponse;
    private volatile PollingContext<T> terminalPollContext;
    private final PollingContext<T> pollingContext = new PollingContext<>();

    /**
     * Creates DefaultSyncPoller.
     *
     * @param pollInterval the polling interval.
     * @param syncActivationOperation the operation to synchronously activate (start) the long running operation,
     *     this operation will be called with a new {@link PollingContext}.
     * @param pollOperation the operation to poll the current state of long running operation, this parameter
     *     is required and the operation will be called with current {@link PollingContext}.
     * @param cancelOperation a {@link Function} that represents the operation to cancel the long running operation
     *     if service supports cancellation, this parameter is required and if service does not support cancellation
     *     then the implementer should return Mono.error with an error message indicating absence of cancellation
     *     support, the operation will be called with current {@link PollingContext}.
     * @param fetchResultOperation a {@link Function} that represents the  operation to retrieve final result of
     *     the long running operation if service support it, this parameter is required and operation will be called
     *     current {@link PollingContext}, if service does not have an api to fetch final result and if final result
     *     is same as final poll response value then implementer can choose to simply return value from provided
     *     final poll response.
     */
    DefaultSyncPoller(Duration pollInterval,
                             Function<PollingContext<T>, PollResponse<T>> syncActivationOperation,
                             Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation,
                             BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation,
                             Function<PollingContext<T>, Mono<U>> fetchResultOperation) {
        Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null.");
        if (pollInterval.compareTo(Duration.ZERO) <= 0) {
            throw logger.logExceptionAsWarning(new IllegalArgumentException(
                "Negative or zero value for 'defaultPollInterval' is not allowed."));
        }
        this.defaultPollInterval = pollInterval;
        Objects.requireNonNull(syncActivationOperation, "'syncActivationOperation' cannot be null.");
        this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null.");
        this.cancelOperation = Objects.requireNonNull(cancelOperation, "'cancelOperation' cannot be null.");
        this.fetchResultOperation = Objects.requireNonNull(fetchResultOperation,
            "'fetchResultOperation' cannot be null.");
        this.activationResponse = syncActivationOperation.apply(this.pollingContext);
        //
        this.pollingContext.setOnetimeActivationResponse(this.activationResponse);
        this.pollingContext.setLatestResponse(this.activationResponse);
    }

    @Override
    public PollResponse<T> poll() {
        PollResponse<T> response = this.pollOperation
            .apply(this.pollingContext)
            .block();
        this.pollingContext.setLatestResponse(response);
        if (response.getStatus().isComplete()) {
            this.terminalPollContext = this.pollingContext.copy();
        }
        return response;
    }

    @Override
    public PollResponse<T> waitForCompletion() {
        PollingContext<T> currentTerminalPollContext = this.terminalPollContext;
        if (currentTerminalPollContext != null) {
            return currentTerminalPollContext.getLatestResponse();
        } else {
            PollingContext<T> context = this.pollingContext.copy();
            AsyncPollResponse<T, U> finalAsyncPollResponse = pollingLoop(context)
                    .blockLast();
            PollResponse<T> response = toPollResponse(finalAsyncPollResponse);
            this.terminalPollContext = context;
            return response;
        }
    }

    @Override
    public PollResponse<T> waitForCompletion(Duration timeout) {
        PollingContext<T> currentTerminalPollContext = this.terminalPollContext;
        if (currentTerminalPollContext != null) {
            return currentTerminalPollContext.getLatestResponse();
        } else {
            PollingContext<T> context = this.pollingContext.copy();
            AsyncPollResponse<T, U> finalAsyncPollResponse = pollingLoop(context)
                    .timeout(timeout)
                    .blockLast();
            PollResponse<T> response = toPollResponse(finalAsyncPollResponse);
            this.terminalPollContext = context;
            return response;
        }
    }

    @Override
    public PollResponse<T> waitUntil(LongRunningOperationStatus statusToWaitFor) {
        Objects.requireNonNull(statusToWaitFor, "'statusToWaitFor' cannot be null.");
        PollingContext<T> currentTerminalPollContext = this.terminalPollContext;
        if (currentTerminalPollContext != null
                && currentTerminalPollContext.getLatestResponse().getStatus() == statusToWaitFor) {
            return currentTerminalPollContext.getLatestResponse();
        } else {
            PollingContext<T> context = this.pollingContext.copy();
            AsyncPollResponse<T, U> asyncPollResponse = pollingLoop(context)
                .takeUntil(apr -> matchStatus(apr, statusToWaitFor))
                .last()
                .switchIfEmpty(Mono.error(new NoSuchElementException("Polling completed without receiving the given"
                        + "status '" + statusToWaitFor + "'.")))
                .block();
            PollResponse<T> response = toPollResponse(asyncPollResponse);
            if (response.getStatus().isComplete()) {
                this.terminalPollContext = context;
            }
            return response;
        }
    }

    @Override
    public PollResponse<T> waitUntil(Duration timeout, LongRunningOperationStatus statusToWaitFor) {
        Objects.requireNonNull(timeout, "'timeout' cannot be null.");
        if (timeout.toNanos() <= 0) {
            throw logger.logExceptionAsWarning(new IllegalArgumentException(
                "Negative or zero value for timeout is not allowed."));
        }
        Objects.requireNonNull(statusToWaitFor, "'statusToWaitFor' cannot be null.");
        PollingContext<T> currentTerminalPollContext = this.terminalPollContext;
        if (currentTerminalPollContext != null
                && currentTerminalPollContext.getLatestResponse().getStatus() == statusToWaitFor) {
            return currentTerminalPollContext.getLatestResponse();
        } else {
            PollingContext<T> context = this.pollingContext.copy();
            AsyncPollResponse<T, U> asyncPollResponse = pollingLoop(context)
                    .takeUntil(apr -> matchStatus(apr, statusToWaitFor))
                    .last()
                    .timeout(timeout)
                    .switchIfEmpty(Mono.error(new NoSuchElementException("Polling completed without receiving the given"
                            + "status '" + statusToWaitFor + "'.")))
                    .block();
            PollResponse<T> response = toPollResponse(asyncPollResponse);
            if (response.getStatus().isComplete()) {
                this.terminalPollContext = context;
            }
            return response;
        }
    }

    @Override
    public U getFinalResult() {
        PollingContext<T> currentTerminalPollContext = this.terminalPollContext;
        if (currentTerminalPollContext != null) {
            return this.fetchResultOperation
                .apply(currentTerminalPollContext)
                .block();
        } else {
            PollingContext<T> context = this.pollingContext.copy();
            AsyncPollResponse<T, U> finalAsyncPollResponse = pollingLoop(context)
                    .blockLast();
            this.terminalPollContext = context;
            return finalAsyncPollResponse.getFinalResult().block();
        }
    }

    @Override
    public void cancelOperation() {
        PollingContext<T> context1 = this.pollingContext.copy();
        if (context1.getActivationResponse() == context1.getLatestResponse()) {
            this.cancelOperation.apply(context1, context1.getActivationResponse())
                .block();
        } else {
            try {
                this.cancelOperation.apply(null, this.activationResponse).block();
            } catch (PollContextRequiredException crp) {
                PollingContext<T> context2 = this.pollingContext.copy();
                pollingLoop(context2)
                    .next()
                    .block();
                this.cancelOperation
                    .apply(context2, this.activationResponse)
                    .block();
            }
        }
    }

    private static <T, U> PollResponse<T> toPollResponse(AsyncPollResponse<T, U> asyncPollResponse) {
        return new PollResponse<>(asyncPollResponse.getStatus(),
            asyncPollResponse.getValue(),
            asyncPollResponse.getRetryAfter());
    }

    private boolean matchStatus(AsyncPollResponse<T, U> currentPollResponse,
                                LongRunningOperationStatus statusToWaitFor) {
        if (currentPollResponse == null || statusToWaitFor == null) {
            return false;
        }
        if (statusToWaitFor == currentPollResponse.getStatus()) {
            return true;
        }
        return false;
    }

    private Flux<AsyncPollResponse<T, U>> pollingLoop(PollingContext<T> pollingContext) {
        return Flux.using(
            // Create a Polling Context per subscription
            () -> pollingContext,
            // Do polling
            // set|read to|from context as needed, reactor guarantee thread-safety of cxt object.
            cxt -> Mono.defer(() -> pollOperation.apply(cxt))
                    .delaySubscription(getDelay(cxt.getLatestResponse()))
                    .switchIfEmpty(Mono.error(new IllegalStateException("PollOperation returned Mono.empty().")))
                    .repeat()
                    .takeUntil(currentPollResponse -> currentPollResponse.getStatus().isComplete())
                    .concatMap(currentPollResponse -> {
                        cxt.setLatestResponse(currentPollResponse);
                        return Mono.just(new AsyncPollResponse<>(cxt,
                                this.cancelOperation,
                                this.fetchResultOperation));
                    }),
            cxt -> { });
    }

    /**
     * Get the duration to wait before making next poll attempt.
     *
     * @param pollResponse the poll response to retrieve delay duration from
     * @return the delay
     */
    private Duration getDelay(PollResponse<T> pollResponse) {
        Duration retryAfter = pollResponse.getRetryAfter();
        if (retryAfter == null) {
            return this.defaultPollInterval;
        } else {
            return retryAfter.compareTo(Duration.ZERO) > 0
                    ? retryAfter
                    : this.defaultPollInterval;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\Generator\Resolver\Parameter\Chainable;

use Nelmio\Alice\Generator\Resolver\ChainableParameterResolverInterface;
use Nelmio\Alice\NotCallableTrait;
use Nelmio\Alice\Parameter;
use Nelmio\Alice\ParameterBag;

class FakeChainableParameterResolver implements ChainableParameterResolverInterface
{
    use NotCallableTrait;

    /**
     * @inheritdoc
     */
    public function canResolve(Parameter $parameter): bool
    {
        $this->__call(__FUNCTION__, func_get_args());
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Parameter $parameter,
        ParameterBag $unresolvedParameters,
        ParameterBag $resolvedParameters
    ): ParameterBag
    {
        $this->__call(__FUNCTION__, func_get_args());
    }
}