text:
.. EN-Revision: none
.. _zend.validate.set.date:

Date
====

``Zend\Validate\Date`` erlaubt es zu prüfen ob ein angegebener Wert ein Datum enthält. Diese Prüfung prüft auch
lokalisierte Eingaben.

.. _zend.validate.set.date.options:

Unterstützte Optionen für Zend\Validate\Date
--------------------------------------------

Die folgenden Optionen werden für ``Zend\Validate\Date`` unterstützt:

- **format**: Setzt das Format welches verwendet wird um das Datum zu schreiben.

- **locale**: Setzt das Gebietsschema welches verwendet wird um Datumswerte zu prüfen.

.. _zend.validate.set.date.basic:

Standardmäßige Datumsprüfung
----------------------------

Der einfachste Weg um ein Datum zu prüfen ist die Verwendung des Standardmäßigen Datumsformats. Dieses wird
verwendet wenn kein Gebietsschema und kein Format angegeben werden.

.. code-block:: .validator.
   :linenos:

   $validator = new Zend\Validate\Date();

   $validator->isValid('2000-10-10');   // Gibt true zurück
   $validator->isValid('10.10.2000'); // Gibt false zurück

Das standardmäßige Datumsformat für ``Zend\Validate\Date`` ist 'yyyy-MM-dd'.

.. _zend.validate.set.date.formats:

Selbst definierte Datumsprüfung
-------------------------------

``Zend\Validate\Date`` unterstützt auch selbst definierte Datumsformate. Wenn man solch ein Datum prüfen will
muss man die Option ``format`` verwenden.

.. code-block:: .validator.
   :linenos:

   $validator = new Zend\Validate\Date(array('format' => 'yyyy'));

   $validator->isValid('2010'); // Gibt true zurück
   $validator->isValid('May');  // Gibt false zurück

Natürlich kann man ``format`` und ``locale`` kombinieren. In diesem Fall kann man lokalisierte Monats- oder
Tagesnamen verwenden.

.. code-block:: .validator.
   :linenos:

   $validator = new Zend\Validate\Date(array('format' => 'yyyy MMMM', 'locale' => 'de'));

   $validator->isValid('2010 Dezember'); // Gibt true zurück
   $validator->isValid('2010 June');     // Gibt false zurück


text:
<?php
namespace Chamilo\Application\Calendar\Extension\Google\Service;

use Chamilo\Application\Calendar\Extension\Google\CalendarProperties;
use Chamilo\Application\Calendar\Extension\Google\EventResultSet;
use Chamilo\Application\Calendar\Extension\Google\Repository\CalendarRepository;

/**
 *
 * @package Chamilo\Application\Calendar\Extension\Google\Service
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class CalendarService
{
    const PARAM_AUTHORIZATION_CODE = 'code';

    /**
     *
     * @var \Chamilo\Application\Calendar\Extension\Google\Repository\CalendarRepository
     */
    private $calendarRepository;

    /**
     *
     * @param \Chamilo\Application\Calendar\Extension\Google\Repository\CalendarRepository $calendarRepository
     */
    public function __construct(CalendarRepository $calendarRepository)
    {
        $this->calendarRepository = $calendarRepository;
    }

    /**
     *
     * @return \Chamilo\Application\Calendar\Extension\Google\Repository\CalendarRepository
     */
    public function getCalendarRepository()
    {
        return $this->calendarRepository;
    }

    /**
     *
     * @param \Chamilo\Application\Calendar\Extension\Google\Repository\CalendarRepository $calendarRepository
     */
    public function setCalendarRepository(CalendarRepository $calendarRepository)
    {
        $this->calendarRepository = $calendarRepository;
    }

    /**
     *
     * @return \Chamilo\Application\Calendar\Storage\DataClass\AvailableCalendar[]
     */
    public function getOwnedCalendars()
    {
        $ownedCalendarsCacheService = new OwnedCalendarsCacheService($this->getCalendarRepository());
        return $ownedCalendarsCacheService->getOwnedCalendars();
    }

    /**
     *
     * @return boolean
     */
    public function login($authenticationCode = null)
    {
        return $this->getCalendarRepository()->login($authenticationCode);
    }

    /**
     *
     * @return boolean
     */
    public function logout()
    {
        return $this->getCalendarRepository()->logout();
    }

    /**
     *
     * @param string $calendarIdentifier
     * @param integer $fromDate
     * @param integer $toDate
     * @return \Chamilo\Application\Calendar\Extension\Google\EventResultSet
     */
    public function getEventsForCalendarIdentifierAndBetweenDates($calendarIdentifier, $fromDate, $toDate)
    {
        $eventsCacheService = new EventsCacheService($this->getCalendarRepository());
        $googleCalendarEvents = $eventsCacheService->getEventsForCalendarIdentifierAndBetweenDates(
            $calendarIdentifier,
            $fromDate,
            $toDate);

        return new EventResultSet(
            $this->getCalendarProperties(
                $googleCalendarEvents->getSummary(),
                $googleCalendarEvents->getDescription(),
                $googleCalendarEvents->getTimeZone()),
            $googleCalendarEvents->getItems());
    }

    /**
     *
     * @param string $summary
     * @param string $description
     * @param string $timeZone
     * @return \Chamilo\Application\Calendar\Extension\Google\CalendarProperties
     */
    private function getCalendarProperties($summary, $description, $timeZone)
    {
        return new CalendarProperties($summary, $description, $timeZone);
    }

    /**
     *
     * @return boolean
     */
    public function isAuthenticated()
    {
        return $this->getCalendarRepository()->hasAccessToken();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace frontend\models\base;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the base model class for table "beidema_form".
 *
 * @property string $name
 * @property string $mobile
 * @property string $address
 * @property string $marry
 * @property string $child
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 * @property integer $id
 */
class BeidemaForm extends \yii\db\ActiveRecord
{
    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['name', 'marry', 'child'], 'string', 'max' => 64],
            [['mobile'], 'string', 'max' => 16],
            [['address'], 'string', 'max' => 256]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'beidema_form';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => Yii::t('app', 'Name'),
            'mobile' => Yii::t('app', 'Mobile'),
            'address' => Yii::t('app', 'Address'),
            'marry' => Yii::t('app', 'Marry'),
            'child' => Yii::t('app', 'Child'),
            'status' => Yii::t('app', '状态'),
            'id' => Yii::t('app', 'ID'),
        ];
    }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \backend\models\BeidemaFormQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \backend\models\BeidemaFormQuery(get_called_class());
    }
}


text:
package com.gelvt.gofdp.mediator;

/**
 * 键盘映射管理器
 * @author: Elvin Zeng
 * @date: 17-8-8
 */
public class KeyMapManager extends EventHandler {

    public KeyMapManager(EventBus eventBus) {
        super(eventBus);
    }

    @Override
    public void handle(Object message) {
        String key = message.toString();
        System.out.println("你按下了:" + key);
        if ("alt+d".equals(key)){
            getEventBus().post("main_form_event", "hideWindow");
        }else if ("alt+s".equals(key)){
            getEventBus().post("main_form_event", "showWindow");
        }
    }
}


text:
#include <apr_pools.h>

#include "serf.h"
#include "serf_bucket_util.h"

typedef struct {
    serf_bucket_t *stream;
} barrier_context_t;

SERF_DECLARE(serf_bucket_t *) serf_bucket_barrier_create(
    serf_bucket_t *stream,
    serf_bucket_alloc_t *allocator)
{
    barrier_context_t *ctx;

    ctx = serf_bucket_mem_alloc(allocator, sizeof(*ctx));
    ctx->stream = stream;

    return serf_bucket_create(&serf_bucket_type_barrier, allocator, ctx);
}

static apr_status_t serf_barrier_read(serf_bucket_t *bucket,
                                     apr_size_t requested,
                                     const char **data, apr_size_t *len)
{
    barrier_context_t *ctx = bucket->data;

    return serf_bucket_read(ctx->stream, requested, data, len);
}

static apr_status_t serf_barrier_readline(serf_bucket_t *bucket,
                                         int acceptable, int *found,
                                         const char **data, apr_size_t *len)
{
    barrier_context_t *ctx = bucket->data;

    return serf_bucket_readline(ctx->stream, acceptable, found, data, len);
}

static apr_status_t serf_barrier_peek(serf_bucket_t *bucket,
                                     const char **data,
                                     apr_size_t *len)
{
    barrier_context_t *ctx = bucket->data;

    return serf_bucket_peek(ctx->stream, data, len);
}

static void serf_barrier_destroy(serf_bucket_t *bucket)
{
    /* The intent of this bucket is not to let our wrapped buckets be
     * destroyed. */

    /* The option is for us to go ahead and 'eat' this bucket now,
     * or just ignore the deletion entirely.
     */
    serf_default_destroy_and_data(bucket);
}

SERF_DECLARE_DATA const serf_bucket_type_t serf_bucket_type_barrier = {
    "BARRIER",
    serf_barrier_read,
    serf_barrier_readline,
    serf_default_read_iovec,
    serf_default_read_for_sendfile,
    serf_default_read_bucket,
    serf_barrier_peek,
    serf_barrier_destroy,
};


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once($CFG->dirroot.'/mod/scorm/datamodels/scormlib.php');
require_once($CFG->dirroot.'/mod/scorm/datamodels/sequencinglib.php');

function scorm_seq_overall ($scoid, $userid, $request, $attempt) {
    $seq = scorm_seq_navigation($scoid, $userid, $request, $attempt);
    if ($seq->navigation) {
        if ($seq->termination != null) {
            $seq = scorm_seq_termination($scoid, $userid, $seq);
        }
        if ($seq->sequencing != null) {
            $seq = scorm_seq_sequencing($scoid, $userid, $seq);
            if ($seq->sequencing == 'exit') { // Return the control to the LTS.
                return 'true';
            }
        }
        if ($seq->delivery != null) {
            $seq = scorm_sequencing_delivery($scoid, $userid, $seq);
            $seq = scorm_content_delivery_environment ($seq, $userid);
        }
    }
    if ($seq->exception != null) {
        $seq = scorm_sequencing_exception($seq);
    }
    return 'true';
}

function scorm_seq_navigation ($scoid, $userid, $request, $attempt=0) {
    global $DB;

    // Sequencing structure.
    $seq = new stdClass();
    $seq->currentactivity = scorm_get_sco($scoid);
    $seq->traversaldir = null;
    $seq->nextactivity = null;
    $seq->deliveryvalid = null;
    $seq->attempt = $attempt;

    $seq->identifiedactivity = null;
    $seq->delivery = null;
    $seq->deliverable = false;
    $seq->active = scorm_seq_is('active', $scoid, $userid);
    $seq->suspended = scorm_seq_is('suspended', $scoid, $userid);
    $seq->navigation = null;
    $seq->termination = null;
    $seq->sequencing = null;
    $seq->target = null;
    $seq->endsession = null;
    $seq->exception = null;
    $seq->reachable = true;
    $seq->prevact = true;

    $sco = scorm_get_sco($scoid);

    switch ($request) {
        case 'start_':
            if (empty($seq->currentactivity)) {
                $seq->navigation = true;
                $seq->sequencing = 'start';
            } else {
                $seq->exception = 'NB.2.1-1'; // Sequencing session already begun.
            }
        break;
        case 'resumeall_':
            if (empty($seq->currentactivity)) {
                // TODO: I think it's suspend instead of suspendedactivity.
                if ($track = $DB->get_record('scorm_scoes_track',
                    array('scoid' => $scoid, 'userid' => $userid, 'element' => 'suspendedactivity'))) {

                    $seq->navigation = true;
                    $seq->sequencing = 'resumeall';
                } else {
                    $seq->exception = 'NB.2.1-3'; // No suspended activity found.
                }
            } else {
                $seq->exception = 'NB.2.1-1'; // Sequencing session already begun.
            }
        break;
        case 'continue_':
        case 'previous_':
            if (!empty($seq->currentactivity)) {
                $sco = $seq->currentactivity;
                if ($sco->parent != '/') {
                    if ($parentsco = scorm_get_parent($sco)) {

                        if (isset($parentsco->flow) && ($parentsco->flow == true)) { // I think it's parentsco.
                            // Current activity is active!
                            if (scorm_seq_is('active', $sco->id, $userid)) {
                                if ($request == 'continue_') {
                                    $seq->navigation = true;
                                    $seq->termination = 'exit';
                                    $seq->sequencing = 'continue';
                                } else {
                                    if (!isset($parentsco->forwardonly) || ($parentsco->forwardonly == false)) {
                                        $seq->navigation = true;
                                        $seq->termination = 'exit';
                                        $seq->sequencing = 'previous';
                                    } else {
                                        $seq->exception = 'NB.2.1-5'; // Violates control mode.
                                    }
                                }
                            }
                        }

                    }
                }
            } else {
                $seq->exception = 'NB.2.1-2'; // Current activity not defined.
            }
        break;
        case 'forward_':
        case 'backward_':
            $seq->exception = 'NB.2.1-7'; // None to be done, behavior not defined.
        break;
        case 'exit_':
        case 'abandon_':
            if (!empty($seq->currentactivity)) {
                // Current activity is active !
                $seq->navigation = true;
                $seq->termination = substr($request, 0, -1);
                $seq->sequencing = 'exit';
            } else {
                $seq->exception = 'NB.2.1-2'; // Current activity not defined.
            }
        case 'exitall_':
        case 'abandonall_':
        case 'suspendall_':
            if (!empty($seq->currentactivity)) {
                $seq->navigation = true;
                $seq->termination = substr($request, 0, -1);
                $seq->sequencing = 'exit';
            } else {
                $seq->exception = 'NB.2.1-2'; // Current activity not defined.
            }
        break;
        default: // Example {target=<STRING>}choice.
            if ($targetsco = $DB->get_record('scorm_scoes', array('scorm' => $sco->scorm, 'identifier' => $request))) {
                if ($targetsco->parent != '/') {
                    $seq->target = $request;
                } else {
                    if ($parentsco = scorm_get_parent($targetsco)) {
                        if (!isset($parentsco->choice) || ($parentsco->choice == true)) {
                            $seq->target = $request;
                        }
                    }
                }
                if ($seq->target != null) {
                    if (empty($seq->currentactivity)) {
                        $seq->navigation = true;
                        $seq->sequencing = 'choice';
                    } else {
                        if (!$sco = scorm_get_sco($scoid)) {
                            return $seq;
                        }
                        if ($sco->parent != $targetsco->parent) {
                            $ancestors = scorm_get_ancestors($sco);
                            $commonpos = scorm_find_common_ancestor($ancestors, $targetsco);
                            if ($commonpos !== false) {
                                if ($activitypath = array_slice($ancestors, 0, $commonpos)) {
                                    foreach ($activitypath as $activity) {
                                        if (scorm_seq_is('active', $activity->id, $userid) &&
                                            (isset($activity->choiceexit) && ($activity->choiceexit == false))) {
                                            $seq->navigation = false;
                                            $seq->termination = null;
                                            $seq->sequencing = null;
                                            $seq->target = null;
                                            $seq->exception = 'NB.2.1-8'; // Violates control mode.
                                            return $seq;
                                        }
                                    }
                                } else {
                                    $seq->navigation = false;
                                    $seq->termination = null;
                                    $seq->sequencing = null;
                                    $seq->target = null;
                                    $seq->exception = 'NB.2.1-9';
                                }
                            }
                        }
                        // Current activity is active !
                        $seq->navigation = true;
                        $seq->sequencing = 'choice';
                    }
                } else {
                    $seq->exception = 'NB.2.1-10';  // Violates control mode.
                }
            } else {
                $seq->exception = 'NB.2.1-11';  // Target activity does not exists.
            }
        break;
    }
    return $seq;
}

function scorm_seq_termination ($seq, $userid) {
    if (empty($seq->currentactivity)) {
        $seq->termination = false;
        $seq->exception = 'TB.2.3-1';
        return $seq;
    }

    $sco = $seq->currentactivity;

    if ((($seq->termination == 'exit') || ($seq->termination == 'abandon')) && !$seq->active) {
        $seq->termination = false;
        $seq->exception = 'TB.2.3-2';
        return $seq;
    }
    switch ($seq->termination) {
        case 'exit':
            scorm_seq_end_attempt($sco, $userid, $seq);
            $seq = scorm_seq_exit_action_rules($seq, $userid);
            do {
                $exit = false;// I think this is false. Originally this was true.
                $seq = scorm_seq_post_cond_rules($seq, $userid);
                if ($seq->termination == 'exitparent') {
                    if ($sco->parent != '/') {
                        $sco = scorm_get_parent($sco);
                        $seq->currentactivity = $sco;
                        $seq->active = scorm_seq_is('active', $sco->id, $userid);
                        scorm_seq_end_attempt($sco, $userid, $seq);
                        $exit = true; // I think it's true. Originally this was false.
                    } else {
                        $seq->termination = false;
                        $seq->exception = 'TB.2.3-4';
                        return $seq;
                    }
                }
            } while (($exit == false) && ($seq->termination == 'exit'));
            if ($seq->termination == 'exit') {
                $seq->termination = true;
                return $seq;
            }
        case 'exitall':
            if ($seq->active) {
                scorm_seq_end_attempt($sco, $userid, $seq);
            }
            // Terminate Descendent Attempts Process.

            if ($ancestors = scorm_get_ancestors($sco)) {
                foreach ($ancestors as $ancestor) {
                    scorm_seq_end_attempt($ancestor, $userid, $seq);
                    $seq->currentactivity = $ancestor;
                }
            }

            $seq->active = scorm_seq_is('active', $seq->currentactivity->id, $userid);
            $seq->termination = true;
            $seq->sequencing = 'exit';
        break;
        case 'suspendall':
            if (($seq->active) || ($seq->suspended)) {
                scorm_seq_set('suspended', $sco->id, $userid, $attempt);
            } else {
                if ($sco->parent != '/') {
                    $parentsco = scorm_get_parent($sco);
                    scorm_seq_set('suspended', $parentsco->id, $userid, $attempt);
                } else {
                    $seq->termination = false;
                    $seq->exception = 'TB.2.3-3';
                }
            }
            if ($ancestors = scorm_get_ancestors($sco)) {
                foreach ($ancestors as $ancestor) {
                    scorm_seq_set('active', $ancestor->id, $userid, $attempt, false);
                    scorm_seq_set('suspended', $ancestor->id, $userid, $attempt);
                    $seq->currentactivity = $ancestor;
                }
                $seq->termination = true;
                $seq->sequencing = 'exit';
            } else {
                $seq->termination = false;
                $seq->exception = 'TB.2.3-5';
            }
        break;
        case 'abandon':
            scorm_seq_set('active', $sco->id, $userid, $attempt, false);
            $seq->active = null;
            $seq->termination = true;
        break;
        case 'abandonall':
            if ($ancestors = scorm_get_ancestors($sco)) {
                foreach ($ancestors as $ancestor) {
                    scorm_seq_set('active', $ancestor->id, $userid, $attempt, false);
                    $seq->currentactivity = $ancestor;
                }
                $seq->termination = true;
                $seq->sequencing = 'exit';
            } else {
                $seq->termination = false;
                $seq->exception = 'TB.2.3-6';
            }
        break;
        default:
            $seq->termination = false;
            $seq->exception = 'TB.2.3-7';
        break;
    }
    return $seq;
}

function scorm_seq_end_attempt($sco, $userid, $seq) {
    global $DB;
    if (scorm_is_leaf($sco)) {
        if (!isset($sco->tracked) || ($sco->tracked == 1)) {
            if (!scorm_seq_is('suspended', $sco->id, $userid)) {
                if (!isset($sco->completionsetbycontent) || ($sco->completionsetbycontent == 0)) {
                    if (!scorm_seq_is('attemptprogressstatus', $sco->id, $userid, $seq->attempt)) {
                        $incomplete = $DB->get_field('scorm_scoes_track', 'value',
                                                        array('scoid' => $sco->id,
                                                                'userid' => $userid,
                                                                'element' => 'cmi.completion_status'));
                        if ($incomplete != 'incomplete') {
                            scorm_seq_set('attemptprogressstatus', $sco->id, $userid, $seq->attempt);
                            scorm_seq_set('attemptcompletionstatus', $sco->id, $userid, $seq->attempt);
                        }
                    }
                }
                if (!isset($sco->objectivesetbycontent) || ($sco->objectivesetbycontent == 0)) {
                    if ($objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $sco->id))) {
                        foreach ($objectives as $objective) {
                            if ($objective->primaryobj) {
                                if (!scorm_seq_is('objectiveprogressstatus', $sco->id, $userid, $seq->attempt)) {
                                    scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $seq->attempt);
                                    scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, $seq->attempt);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else if ($children = scorm_get_children($sco)) {
        $suspended = false;
        foreach ($children as $child) {
            if (scorm_seq_is('suspended', $child, $userid, $seq->attempt)) {
                $suspended = true;
                break;
            }
        }
        if ($suspended) {
            scorm_seq_set('suspended', $sco, $userid, $seq->attempt);
        } else {
            scorm_seq_set('suspended', $sco, $userid, $seq->attempt, false);
        }
    }
    scorm_seq_set('active', $sco->id, $userid, $seq->attempt, false);
    scorm_seq_overall_rollup($sco, $userid, $seq);
}

function scorm_seq_is($what, $scoid, $userid, $attempt=0) {
    global $DB;

    // Check if passed activity $what is active.
    $active = false;
    if ($track = $DB->get_record('scorm_scoes_track',
            array('scoid' => $scoid, 'userid' => $userid, 'attempt' => $attempt, 'element' => $what))) {
        $active = true;
    }
    return $active;
}

function scorm_seq_set($what, $scoid, $userid, $attempt=0, $value='true') {
    global $DB;

    $sco = scorm_get_sco($scoid);

    // Set passed activity to active or not.
    if ($value == false) {
        $DB->delete_records('scorm_scoes_track', array('scoid' => $scoid, 'userid' => $userid,
                                                        'attempt' => $attempt, 'element' => $what));
    } else {
        scorm_insert_track($userid, $sco->scorm, $sco->id, $attempt, $what, $value);
    }

    // Update grades in gradebook.
    $scorm = $DB->get_record('scorm', array('id' => $sco->scorm));
    scorm_update_grades($scorm, $userid, true);
}

function scorm_evaluate_condition ($rollupruleconds, $sco, $userid) {
    global $DB;

    $res = false;

    if (strpos($rollupruleconds, 'and ')) {
        $rollupruleconds = array_filter(explode(' and ', $rollupruleconds));
        $conditioncombination = 'all';
    } else {
        $rollupruleconds = array_filter(explode(' or ', $rollupruleconds));
        $conditioncombination = 'or';
    }
    foreach ($rollupruleconds as $rolluprulecond) {
        $notflag = false;
        if (strpos($rolluprulecond, 'not') !== false) {
            $rolluprulecond = str_replace('not', '', $rolluprulecond);
            $notflag = true;
        }
        $conditionarray['condition'] = $rolluprulecond;
        $conditionarray['notflag'] = $notflag;
        $conditions[] = $conditionarray;
    }
    foreach ($conditions as $condition) {
        $checknot = true;
        $res = false;
        if ($condition['notflag']) {
            $checknot = false;
        }
        switch ($condition['condition']) {
            case 'satisfied':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectivesatisfiedstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectiveprogressstatus'));
                    if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                        $res = true;
                    }
                }
                break;

            case 'objectiveStatusKnown':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectiveprogressstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $res = true;
                }
                break;

            case 'notobjectiveStatusKnown':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectiveprogressstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $res = true;
                }
                break;

            case 'objectiveMeasureKnown':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectivemeasurestatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $res = true;
                }
                break;

            case 'notobjectiveMeasureKnown':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectivemeasurestatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $res = true;
                }
                break;

            case 'completed':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'attemptcompletionstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $r = $DB->get_record('scorm_scoes_track',
                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'attemptprogressstatus'));
                    if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                        $res = true;
                    }
                }
                break;

            case 'attempted':
                $attempt = $DB->get_field('scorm_scoes_track', 'attempt',
                                            array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'x.start.time'));
                if ($checknot && $attempt > 0) {
                    $res = true;
                } else if (!$checknot && $attempt <= 0) {
                    $res = true;
                }
                break;

            case 'attemptLimitExceeded':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'activityprogressstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $r = $DB->get_record('scorm_scoes_track',
                                            array('scoid' => $sco->id, 'userid' => $userid,
                                                    'element' => 'limitconditionattemptlimitcontrol'));
                    if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                        if ($r = $DB->get_field('scorm_scoes_track', 'attempt', array('scoid' => $sco->id, 'userid' => $userid)) &&
                            $r2 = $DB->get_record('scorm_scoes_track', array('scoid' => $sco->id, 'userid' => $userid,
                                                                                'element' => 'limitconditionattemptlimit')) ) {

                            if ($checknot && ($r->value >= $r2->value)) {
                                $res = true;
                            } else if (!$checknot && ($r->value < $r2->value)) {
                                $res = true;
                            }
                        }
                    }
                }
                break;

            case 'activityProgressKnown':
                $r = $DB->get_record('scorm_scoes_track',
                                        array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'activityprogressstatus'));
                if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                    $r = $DB->get_record('scorm_scoes_track',
                                            array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'attemptprogressstatus'));
                    if ((!isset($r->value) && !$checknot) || (isset($r->value) && ($r->value == $checknot))) {
                        $res = true;
                    }
                }
                break;
        }

        if ($conditioncombination == 'all' && !$res) {
            break;
        } else if ($conditioncombination == 'or' && $res) {
            break;
        }
    }

    return $res;
}

function scorm_check_activity ($activity, $userid) {
    $act = scorm_seq_rules_check($activity, 'disabled');
    if ($act != null) {
        return true;
    }
    if (scorm_limit_cond_check ($activity, $userid)) {
        return true;
    }
    return false;
}

function scorm_limit_cond_check ($activity, $userid) {
    global $DB;

    if (isset($activity->tracked) && ($activity->tracked == 0)) {
        return false;
    }

    if (scorm_seq_is('active', $activity->id, $userid) || scorm_seq_is('suspended', $activity->id, $userid)) {
        return false;
    }

    if (!isset($activity->limitcontrol) || ($activity->limitcontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'activityattemptcount'));
        if (scorm_seq_is('activityprogressstatus', $activity->id, $userid) && ($r->value >= $activity->limitattempt)) {
            return true;
        }
    }

    if (!isset($activity->limitabsdurcontrol) || ($activity->limitabsdurcontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'activityabsoluteduration'));
        if (scorm_seq_is('activityprogressstatus', $activity->id, $userid) && ($r->value >= $activity->limitabsduration)) {
            return true;
        }
    }

    if (!isset($activity->limitexpdurcontrol) || ($activity->limitexpdurcontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'activityexperiencedduration'));
        if (scorm_seq_is('activityprogressstatus', $activity->id, $userid) && ($r->value >= $activity->limitexpduration)) {
            return true;
        }
    }

    if (!isset($activity->limitattabsdurcontrol) || ($activity->limitattabsdurcontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'attemptabsoluteduration'));
        if (scorm_seq_is('activityprogressstatus', $activity->id, $userid) && ($r->value >= $activity->limitattabsduration)) {
            return true;
        }
    }

    if (!isset($activity->limitattexpdurcontrol) || ($activity->limitattexpdurcontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'attemptexperiencedduration'));
        if (scorm_seq_is('activityprogressstatus', $activity->id, $userid) && ($r->value >= $activity->limitattexpduration)) {
            return true;
        }
    }

    if (!isset($activity->limitbegincontrol) || ($activity->limitbegincontrol == 1)) {
        $r = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $activity->id, 'userid' => $userid, 'element' => 'begintime'));
        if (isset($activity->limitbegintime) && time() >= $activity->limitbegintime) {
            return true;
        }
    }

    if (!isset($activity->limitbegincontrol) || ($activity->limitbegincontrol == 1)) {
        if (isset($activity->limitbegintime) && time() < $activity->limitbegintime) {
            return true;
        }
    }

    if (!isset($activity->limitendcontrol) || ($activity->limitendcontrol == 1)) {
        if (isset($activity->limitendtime) && time() > $activity->limitendtime) {
            return true;
        }
    }
    return false;
}

function scorm_seq_rules_check ($sco, $action) {
    global $DB;
    $act = null;

    if ($rules = $DB->get_records('scorm_seq_ruleconds', array('scoid' => $sco->id, 'action' => $action))) {
        foreach ($rules as $rule) {
            if ($act = scorm_seq_rule_check($sco, $rule)) {
                return $act;
            }
        }
    }
    return $act;

}

function scorm_seq_rule_check ($sco, $rule) {
    global $DB;

    $bag = Array();
    $cond = '';
    $ruleconds = $DB->get_records('scorm_seq_rulecond', array('scoid' => $sco->id, 'ruleconditionsid' => $rule->id));
    foreach ($ruleconds as $rulecond) {
        if ($rulecond->operator == 'not') {
            if ($rulecond->cond != 'unknown' ) {
                $rulecond->cond = 'not'.$rulecond->cond;
            }
        }
         $bag[] = $rulecond->cond;
    }
    if (empty($bag)) {
        $cond = 'unknown';
        return $cond;
    }

    if ($rule->conditioncombination == 'all') {
        foreach ($bag as $con) {
                $cond = $cond.' and '.$con;
        }
    } else {
        foreach ($bag as $con) {
            $cond = $cond.' or '.$con;
        }
    }
    return $cond;
}

function scorm_seq_overall_rollup($sco, $userid, $seq) {
    if ($ancestors = scorm_get_ancestors($sco)) {
        foreach ($ancestors as $ancestor) {
            if (!scorm_is_leaf($ancestor)) {
                scorm_seq_measure_rollup($sco, $userid, $seq->attempt);
            }
            scorm_seq_objective_rollup($sco, $userid, $seq->attempt);
            scorm_seq_activity_progress_rollup($sco, $userid, $seq);
        }
    }
}

function scorm_seq_measure_rollup($sco, $userid, $attempt = 0) {
    global $DB;

    $totalmeasure = 0; // Check if there is something similar in the database.
    $valid = false; // Same as in the last line.
    $countedmeasures = 0; // Same too.
    $targetobjective = null;
    $objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $sco->id));

    foreach ($objectives as $objective) {
        if ($objective->primaryobj == true) { // Objective contributes to rollup.
            $targetobjective = $objective;
            break;
        }

    }
    if ($targetobjective != null) {
        $children = scorm_get_children($sco);
        if (!empty ($children)) {
            foreach ($children as $child) {
                $child = scorm_get_sco ($child);
                if (!isset($child->tracked) || ($child->tracked == 1)) {
                    $rolledupobjective = null;// We set the rolled up activity to undefined.
                    $objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $child->id));
                    foreach ($objectives as $objective) {
                        if ($objective->primaryobj == true) {// Objective contributes to rollup I'm using primaryobj field, but not.
                            $rolledupobjective = $objective;
                            break;
                        }
                    }
                    if ($rolledupobjective != null) {
                        $child = scorm_get_sco($child->id);
                        $countedmeasures = $countedmeasures + ($child->measureweight);
                        if (!scorm_seq_is('objectivemeasurestatus', $sco->id, $userid, $attempt)) {
                            $normalizedmeasure = $DB->get_record('scorm_scoes_track',
                                array('scoid' => $child->id, 'userid' => $userid, 'element' => 'objectivenormalizedmeasure'));
                            $totalmeasure = $totalmeasure + (($normalizedmeasure->value) * ($child->measureweight));
                            $valid = true;
                        }
                    }
                }
            }
        }

        if (!$valid) {
            scorm_seq_set('objectivemeasurestatus', $sco->id, $userid, $attempt, false);
        } else {
            if ($countedmeasures > 0) {
                scorm_seq_set('objectivemeasurestatus', $sco->id, $userid, $attempt);
                $val = $totalmeasure / $countedmeasures;
                scorm_seq_set('objectivenormalizedmeasure', $sco->id, $userid, $attempt, $val);
            } else {
                scorm_seq_set('objectivemeasurestatus', $sco->id, $userid, $attempt, false);
            }
        }
    }
}

function scorm_seq_objective_rollup($sco, $userid, $attempt = 0) {
    global $DB;

    scorm_seq_objective_rollup_measure($sco, $userid, $attempt);
    scorm_seq_objective_rollup_rules($sco, $userid, $attempt);
    scorm_seq_objective_rollup_default($sco, $userid, $attempt);

    /*
    if ($targetobjective->satisfiedbymeasure) {
        scorm_seq_objective_rollup_measure($sco, $userid);
    }
    else{
        if ((scorm_seq_rollup_rule_check($sco, $userid, 'incomplete'))
             || (scorm_seq_rollup_rule_check($sco, $userid, 'completed'))) {
            scorm_seq_objective_rollup_rules($sco, $userid);
        }
        else{

            $rolluprules = $DB->get_record('scorm_seq_rolluprule', array('scoid'=>$sco->id, 'userid'=>$userid));
            foreach ($rolluprules as $rolluprule) {
                $rollupruleconds = $DB->get_records('scorm_seq_rolluprulecond', array('rollupruleid'=>$rolluprule->id));
                foreach ($rollupruleconds as $rolluprulecond) {

                    switch ($rolluprulecond->cond!='satisfied'
                            && $rolluprulecond->cond!='completed' && $rolluprulecond->cond!='attempted') {

                           scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, false);

                        break;
                    }
                }

        }
    }
    */
}

function scorm_seq_objective_rollup_measure($sco, $userid, $attempt = 0) {
    global $DB;

    $targetobjective = null;

    $objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $sco->id));
    foreach ($objectives as $objective) {
        if ($objective->primaryobj == true) {
            $targetobjective = $objective;
            break;
        }
    }
    if ($targetobjective != null) {
        if ($targetobjective->satisfiedbymeasure) {
            if (!scorm_seq_is('objectiveprogressstatus', $sco->id, $userid, $attempt)) {
                scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt, false);
            } else {
                if (scorm_seq_is('active', $sco->id, $userid, $attempt)) {
                    $isactive = true;
                } else {
                    $isactive = false;
                }

                $normalizedmeasure = $DB->get_record('scorm_scoes_track',
                    array('scoid' => $sco->id, 'userid' => $userid, 'element' => 'objectivenormalizedmeasure'));

                $sco = scorm_get_sco ($sco->id);

                if (!$isactive || ($isactive &&
                    (!isset($sco->measuresatisfactionifactive) || $sco->measuresatisfactionifactive == true))) {
                    if (isset($normalizedmeasure->value) && ($normalizedmeasure->value >= $targetobjective->minnormalizedmeasure)) {
                        scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt);
                        scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, $attempt);
                    } else {
                        // TODO: handle the case where cmi.success_status is passed and objectivenormalizedmeasure undefined.
                        scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt);
                    }
                } else {
                    scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt, false);
                }
            }
        }
    }
}

function scorm_seq_objective_rollup_default($sco, $userid, $attempt = 0) {
    global $DB;

    if (!(scorm_seq_rollup_rule_check($sco, $userid, 'incomplete')) && !(scorm_seq_rollup_rule_check($sco, $userid, 'completed'))) {
        if ($rolluprules = $DB->get_record('scorm_seq_rolluprule', array('scoid' => $sco->id))) {
            foreach ($rolluprules as $rolluprule) {
                $rollupruleconds = $DB->get_records('scorm_seq_rolluprulecond', array('rollupruleid' => $rolluprule->id));
                foreach ($rollupruleconds as $rolluprulecond) {
                    if ($rolluprulecond->cond != 'satisfied' && $rolluprulecond->cond != 'completed' &&
                            $rolluprulecond->cond != 'attempted') {
                        scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, $attempt, false);
                        break;
                    }
                }
            }
        }
    }
}

function scorm_seq_objective_rollup_rules($sco, $userid, $attempt = 0) {
    global $DB;

    $targetobjective = null;

    $objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $sco->id));
    foreach ($objectives as $objective) {
        if ($objective->primaryobj == true) {// Objective contributes to rollup I'm using primaryobj field, but not.
            $targetobjective = $objective;
            break;
        }
    }
    if ($targetobjective != null) {

        if (scorm_seq_rollup_rule_check($sco, $userid, 'notsatisfied')) {// With not satisfied rollup for the activity.
            scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt);
            scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, $attempt, false);
        }
        if (scorm_seq_rollup_rule_check($sco, $userid, 'satisfied')) {// With satisfied rollup for the activity.
            scorm_seq_set('objectiveprogressstatus', $sco->id, $userid, $attempt);
            scorm_seq_set('objectivesatisfiedstatus', $sco->id, $userid, $attempt);
        }

    }

}

function scorm_seq_activity_progress_rollup ($sco, $userid, $seq) {

    if (scorm_seq_rollup_rule_check($sco, $userid, 'incomplete')) {
        // Incomplete rollup action.
        scorm_seq_set('attemptcompletionstatus', $sco->id, $userid, $seq->attempt, false);
        scorm_seq_set('attemptprogressstatus', $sco->id, $userid, $seq->attempt, true);

    }
    if (scorm_seq_rollup_rule_check($sco, $userid, 'completed')) {
        // Incomplete rollup action.
        scorm_seq_set('attemptcompletionstatus', $sco->id, $userid, $seq->attempt, true);
        scorm_seq_set('attemptprogressstatus', $sco->id, $userid, $seq->attempt, true);
    }

}

function scorm_seq_rollup_rule_check ($sco, $userid, $action) {
    global $DB;

    if ($rolluprules = $DB->get_record('scorm_seq_rolluprule', array('scoid' => $sco->id, 'action' => $action))) {
        $childrenbag = Array ();
        $children = scorm_get_children ($sco);

        foreach ($rolluprules as $rolluprule) {
            foreach ($children as $child) {

                /*$tracked = $DB->get_records('scorm_scoes_track', array('scoid'=>$child->id, 'userid'=>$userid));
                if ($tracked && $tracked->attemp != 0) {*/
                $child = scorm_get_sco ($child);
                if (!isset($child->tracked) || ($child->tracked == 1)) {
                    if (scorm_seq_check_child ($child, $action, $userid)) {
                        $rollupruleconds = $DB->get_records('scorm_seq_rolluprulecond', array('rollupruleid' => $rolluprule->id));
                        $evaluate = scorm_seq_evaluate_rollupcond($child, $rolluprule->conditioncombination,
                                                                  $rollupruleconds, $userid);
                        if ($evaluate == 'unknown') {
                            array_push($childrenbag, 'unknown');
                        } else {
                            if ($evaluate == true) {
                                array_push($childrenbag, true);
                            } else {
                                array_push($childrenbag, false);
                            }
                        }
                    }
                }

            }
            $change = false;

            switch ($rolluprule->childactivityset) {

                case 'all':
                    // I think I can use this condition instead equivalent to OR.
                    if ((array_search(false, $childrenbag) === false) && (array_search('unknown', $childrenbag) === false)) {
                        $change = true;
                    }
                break;

                case 'any':
                    // I think I can use this condition instead equivalent to OR.
                    if (array_search(true, $childrenbag) !== false) {
                        $change = true;
                    }
                break;

                case 'none':
                    // I think I can use this condition instead equivalent to OR.
                    if ((array_search(true, $childrenbag) === false) && (array_search('unknown', $childrenbag) === false)) {
                        $change = true;
                    }
                break;

                case 'atleastcount':
                    // I think I can use this condition instead equivalent to OR.
                    foreach ($childrenbag as $itm) {
                        $cont = 0;
                        if ($itm === true) {
                            $cont++;
                        }
                        if ($cont >= $rolluprule->minimumcount) {
                            $change = true;
                        }
                    }
                break;

                case 'atleastcount':
                    foreach ($childrenbag as $itm) {// I think I can use this condition instead equivalent to OR.
                        $cont = 0;
                        if ($itm === true) {
                            $cont++;
                        }
                        if ($cont >= $rolluprule->minimumcount) {
                            $change = true;
                        }
                    }
                break;

                case 'atleastpercent':
                    foreach ($childrenbag as $itm) {// I think I can use this condition instead equivalent to OR.
                        $cont = 0;
                        if ($itm === true) {
                            $cont++;
                        }
                        if (($cont / count($childrenbag)) >= $rolluprule->minimumcount) {
                            $change = true;
                        }
                    }
                break;
            }
            if ($change == true) {
                return true;
            }
        }
    }
    return false;
}

function scorm_seq_flow_tree_traversal($activity, $direction, $childrenflag, $prevdirection, $seq, $userid, $skip = false) {
    $revdirection = false;
    $parent = scorm_get_parent($activity);
    if (!empty($parent)) {
        $children = scorm_get_available_children($parent);
    } else {
        $children = array();
    }
    $childrensize = count($children);

    if (($prevdirection != null && $prevdirection == 'backward') && ($children[$childrensize - 1]->id == $activity->id)) {
        $direction = 'backward';
        $activity = $children[0];
        $revdirection = true;
    }

    if ($direction == 'forward') {
        $ancestors = scorm_get_ancestors($activity);
        $ancestorsroot = array_reverse($ancestors);
        $preorder = array();
        $preorder = scorm_get_preorder($preorder, $ancestorsroot[0]);
        $preordersize = count($preorder);
        if (($activity->id == $preorder[$preordersize - 1]->id) || (($activity->parent == '/') && !($childrenflag))) {
            $seq->endsession = true;
            $seq->nextactivity = null;
            return $seq;
        }
        if (scorm_is_leaf ($activity) || !$childrenflag) {
            if ($children[$childrensize - 1]->id == $activity->id) {
                $seq = scorm_seq_flow_tree_traversal ($parent, $direction, false, null, $seq, $userid);
                if ($seq->nextactivity->launch == null) {
                    $seq = scorm_seq_flow_tree_traversal ($seq->nextactivity, $direction, true, null, $seq, $userid);
                }
                return $seq;
            } else {
                $position = 0;
                foreach ($children as $sco) {
                    if ($sco->id == $activity->id) {
                        break;
                    }
                    $position++;
                }
                if ($position != ($childrensize - 1)) {
                    $seq->nextactivity = $children[$position + 1];
                    $seq->traversaldir = $direction;
                    return $seq;
                } else {
                    $siblings = scorm_get_siblings($activity);
                    $children = scorm_get_children($siblings[0]);
                    $seq->nextactivity = $children[0];
                    return $seq;
                }
            }
        } else {
            $children = scorm_get_available_children($activity);
            if (!empty($children)) {
                $seq->traversaldir = $direction;
                $seq->nextactivity = $children[0];
                return $seq;
            } else {
                $seq->traversaldir = null;
                $seq->nextactivity = null;
                $seq->exception = 'SB.2.1-2';
                return $seq;
            }
        }
    } else if ($direction == 'backward') {
        if ($activity->parent == '/') {
            $seq->traversaldir = null;
            $seq->nextactivity = null;
            $seq->exception = 'SB.2.1-3';
            return $seq;
        }
        if (scorm_is_leaf ($activity) || !$childrenflag) {
            if (!$revdirection) {
                if (isset($parent->forwardonly) && ($parent->forwardonly == true && !$skip)) {
                    $seq->traversaldir = null;
                    $seq->nextactivity = null;
                    $seq->exception = 'SB.2.1-4';
                    return $seq;
                }
            }
            if ($children[0]->id == $activity->id) {
                $seq = scorm_seq_flow_tree_traversal($parent, 'backward', false, null, $seq, $userid);
                return $seq;
            } else {
                $ancestors = scorm_get_ancestors($activity);
                $ancestorsroot = array_reverse($ancestors);
                $preorder = array();
                $preorder = scorm_get_preorder($preorder, $ancestorsroot[0]);
                $position = 0;
                foreach ($preorder as $sco) {
                    if ($sco->id == $activity->id) {
                        break;
                    }
                    $position++;
                }
                if (isset($preorder[$position])) {
                    $seq->nextactivity = $preorder[$position - 1];
                    $seq->traversaldir = $direction;
                }
                return $seq;
            }
        } else {
            $children = scorm_get_available_children($activity);
            if (!empty($children)) {
                if (isset($parent->flow) && ($parent->flow == true)) {
                    $seq->traversaldir = 'forward';
                    $seq->nextactivity = $children[0];
                    return $seq;
                } else {
                    $seq->traversaldir = 'backward';
                    $seq->nextactivity = $children[count($children) - 1];
                    return $seq;
                }
            } else {
                $seq->traversaldir = null;
                $seq->nextactivity = null;
                $seq->exception = 'SB.2.1-2';
                return $seq;
            }
        }
    }
}

// Returns the next activity on the tree, traversal direction, control returned to the LTS, (may) exception.
function scorm_seq_flow_activity_traversal ($activity, $userid, $direction, $childrenflag, $prevdirection, $seq) {
    $parent = scorm_get_parent ($activity);
    if (!isset($parent->flow) || ($parent->flow == false)) {
        $seq->deliverable = false;
        $seq->exception = 'SB.2.2-1';
        $seq->nextactivity = $activity;
        return $seq;
    }

    $rulecheck = scorm_seq_rules_check($activity, 'skip');
    if ($rulecheck != null) {
        $skip = scorm_evaluate_condition ($rulecheck, $activity, $userid);
        if ($skip) {
            $seq = scorm_seq_flow_tree_traversal($activity, $direction, false, $prevdirection, $seq, $userid, $skip);
            $seq = scorm_seq_flow_activity_traversal($seq->nextactivity, $userid, $direction,
                                                     $childrenflag, $prevdirection, $seq);
        } else if (!empty($seq->identifiedactivity)) {
            $seq->nextactivity = $activity;
        }
        return $seq;
    }

    $ch = scorm_check_activity ($activity, $userid);
    if ($ch) {
        $seq->deliverable = false;
        $seq->exception = 'SB.2.2-2';
        $seq->nextactivity = $activity;
        return $seq;
    }

    if (!scorm_is_leaf($activity)) {
        $seq = scorm_seq_flow_tree_traversal ($activity, $direction, true, null, $seq, $userid);
        if ($seq->identifiedactivity == null) {
            $seq->deliverable = false;
            $seq->nextactivity = $activity;
            return $seq;
        } else {
            if ($direction == 'backward' && $seq->traversaldir == 'forward') {
                $seq = scorm_seq_flow_activity_traversal($seq->identifiedactivity, $userid,
                                                         'forward', $childrenflag, 'backward', $seq);
            } else {
                $seq = scorm_seq_flow_activity_traversal($seq->identifiedactivity, $userid,
                                                         $direction, $childrenflag, null, $seq);
            }
            return $seq;
        }

    }

    $seq->deliverable = true;
    $seq->nextactivity = $activity;
    $seq->exception = null;
    return $seq;

}

function scorm_seq_flow ($activity, $direction, $seq, $childrenflag, $userid) {
    // TODO: $PREVDIRECTION NOT DEFINED YET.
    $prevdirection = null;
    $seq = scorm_seq_flow_tree_traversal ($activity, $direction, $childrenflag, $prevdirection, $seq, $userid);
    if ($seq->nextactivity == null) {
        $seq->nextactivity = $activity;
        $seq->deliverable = false;
        return $seq;
    } else {
        $activity = $seq->nextactivity;
        $seq = scorm_seq_flow_activity_traversal($activity, $userid, $direction, $childrenflag, null, $seq);
        return $seq;
    }
}

/**
 * Sets up $userdata array and default values for SCORM 1.3 .
 *
 * @param stdClass $userdata an empty stdClass variable that should be set up with user values
 * @param object $scorm package record
 * @param string $scoid SCO Id
 * @param string $attempt attempt number for the user
 * @param string $mode scorm display mode type
 * @return array The default values that should be used for SCORM 1.3 package
 */
function get_scorm_default (&$userdata, $scorm, $scoid, $attempt, $mode) {
    global $DB, $USER;

    $userdata->student_id = $USER->username;
    $userdata->student_name = $USER->lastname .', '. $USER->firstname;

    if ($usertrack = scorm_get_tracks($scoid, $USER->id, $attempt)) {
        // According to SCORM 2004(RTE V1, 4.2.8), only cmi.exit==suspend should allow previous datamodel elements on re-launch.
        if (isset($usertrack->{'cmi.exit'}) && ($usertrack->{'cmi.exit'} == 'suspend')) {
            foreach ($usertrack as $key => $value) {
                $userdata->$key = $value;
            }
        } else {
            $userdata->status = '';
            $userdata->score_raw = '';
        }
    } else {
        $userdata->status = '';
        $userdata->score_raw = '';
    }

    if ($scodatas = scorm_get_sco($scoid, SCO_DATA)) {
        foreach ($scodatas as $key => $value) {
            $userdata->$key = $value;
        }
    } else {
        print_error('cannotfindsco', 'scorm');
    }
    if (!$sco = scorm_get_sco($scoid)) {
        print_error('cannotfindsco', 'scorm');
    }

    if (isset($userdata->status)) {
        if (!isset($userdata->{'cmi.exit'}) || $userdata->{'cmi.exit'} == 'time-out' || $userdata->{'cmi.exit'} == 'normal') {
                $userdata->entry = 'ab-initio';
        } else {
            if (isset($userdata->{'cmi.exit'}) && ($userdata->{'cmi.exit'} == 'suspend' || $userdata->{'cmi.exit'} == 'logout')) {
                $userdata->entry = 'resume';
            } else {
                $userdata->entry = '';
            }
        }
    }

    $userdata->mode = 'normal';
    if (!empty($mode)) {
        $userdata->mode = $mode;
    }
    if ($userdata->mode == 'normal') {
        $userdata->credit = 'credit';
    } else {
        $userdata->credit = 'no-credit';
    }

    $objectives = $DB->get_records('scorm_seq_objective', array('scoid' => $scoid));
    $index = 0;
    foreach ($objectives as $objective) {
        if (!empty($objective->minnormalizedmeasure)) {
            $userdata->{'cmi.scaled_passing_score'} = $objective->minnormalizedmeasure;
        }
        if (!empty($objective->objectiveid)) {
            $userdata->{'cmi.objectives.N'.$index.'.id'} = $objective->objectiveid;
            $index++;
        }
    }

    $def = array();
    $def['cmi.learner_id'] = $userdata->student_id;
    $def['cmi.learner_name'] = $userdata->student_name;
    $def['cmi.mode'] = $userdata->mode;
    $def['cmi.entry'] = $userdata->entry;
    $def['cmi.exit'] = scorm_isset($userdata, 'cmi.exit');
    $def['cmi.credit'] = scorm_isset($userdata, 'credit');
    $def['cmi.completion_status'] = scorm_isset($userdata, 'cmi.completion_status', 'unknown');
    $def['cmi.completion_threshold'] = scorm_isset($userdata, 'threshold');
    $def['cmi.learner_preference.audio_level'] = scorm_isset($userdata, 'cmi.learner_preference.audio_level', 1);
    $def['cmi.learner_preference.language'] = scorm_isset($userdata, 'cmi.learner_preference.language');
    $def['cmi.learner_preference.delivery_speed'] = scorm_isset($userdata, 'cmi.learner_preference.delivery_speed');
    $def['cmi.learner_preference.audio_captioning'] = scorm_isset($userdata, 'cmi.learner_preference.audio_captioning', 0);
    $def['cmi.location'] = scorm_isset($userdata, 'cmi.location');
    $def['cmi.max_time_allowed'] = scorm_isset($userdata, 'attemptAbsoluteDurationLimit');
    $def['cmi.progress_measure'] = scorm_isset($userdata, 'cmi.progress_measure');
    $def['cmi.scaled_passing_score'] = scorm_isset($userdata, 'cmi.scaled_passing_score');
    $def['cmi.score.scaled'] = scorm_isset($userdata, 'cmi.score.scaled');
    $def['cmi.score.raw'] = scorm_isset($userdata, 'cmi.score.raw');
    $def['cmi.score.min'] = scorm_isset($userdata, 'cmi.score.min');
    $def['cmi.score.max'] = scorm_isset($userdata, 'cmi.score.max');
    $def['cmi.success_status'] = scorm_isset($userdata, 'cmi.success_status', 'unknown');
    $def['cmi.suspend_data'] = scorm_isset($userdata, 'cmi.suspend_data');
    $def['cmi.time_limit_action'] = scorm_isset($userdata, 'timelimitaction');
    $def['cmi.total_time'] = scorm_isset($userdata, 'cmi.total_time', 'PT0H0M0S');

    return $def;
}


text:
This plugin is intended to provide a simple, drop in solution for helping users meet burdensome password requirements.

## Usage

1. Include [jQuery](http://jquery.com/) and [Underscore.js](http://underscorejs.org/):

	```html
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
	```

2. Include plugin's code:

	```html
	<script src="path/to/jquery-password-validator.min.js"></script>
	<link rel="stylesheet" href="path/to/jquery-password-validator.css"></link>
	```

3. Call the plugin:

	```html
	<input type="password" id="password_input">

	<script>
		$(function () {
			$("#password_input").passwordValidator({
				// list of qualities to require
				require: ['length', 'lower', 'upper', 'digit'],
				// minimum length requirement
				length: 12
			});
		});
	</script>
	```

### Options

#### require
An array of validation requirements. Valid options are:

* length - validate minimum password length
* lower - validate password includes at least one lower case character
* upper - validate password includes at least one upper case character
* digit - validate password includes at least one digit

For example `require: ['lower', 'digit']` would result in validation which requires at least one lower case alpha character, and a numeric character, but use no explicit length validation (although in this example a password would need to be at least two characters to satisfy the other requirements), nor the inclusion of an upper case character.

Default is to require all 4 available options.

#### length
The minimum length to require, if `"length"` is included in the `require` option.

Default value is 12.

## Contributing
Check [CONTRIBUTING.md](https://github.com/IoraHealth/jquery-password-validator/blob/master/CONTRIBUTING.md) for more information.

## License

[MIT License](https://github.com/IoraHealth/jquery-password-validator/blob/mc-inital_implementation/LICENSE.md) © Iora Health


text:
class Visitor;
//Contract
class Contract
{
public:
	virtual void accept(Visitor & visitor) = 0;
};
typedef std::shared_ptr<Contract> ContractPtr;
class Zero : public Contract
{
public:
	void accept(Visitor & visitor);
};
class One : public Contract
{
public:
	One(Currency currency) : currency_(currency){}
	Currency getCurrency(){ return currency_; }
	void accept(Visitor & visitor);
private:
	Currency currency_;
};
class Scale : public Contract
{
public:
	Scale(Obs<double> & obs, ContractPtr contract) : obs_(obs), contract_(contract){}
	ContractPtr get_contract(){ return contract_; }
	Obs<double> & get_obs(){ return obs_; }
	void accept(Visitor & visitor);
private:
	Obs<double> obs_;
	ContractPtr contract_;
};
class When : public Contract
{
public:
	When(Obs<bool> & obs, ContractPtr contract) : obs_(obs), contract_(contract){}
	ContractPtr get_contract(){ return contract_; }
	Obs<bool> & get_obs(){ return obs_; }
	void accept(Visitor & visitor);
private:
	Obs<bool> obs_;
	ContractPtr contract_;
};
class Give : public Contract
{
public:
	Give(ContractPtr contract) : contract_(contract){}
	ContractPtr get_contract(){ return contract_; }
	void accept(Visitor & visitor);
private:
	ContractPtr contract_;
};
class Or : public Contract
{
public:
	Or(ContractPtr c1, ContractPtr c2) : contract1_(c1), contract2_(c2){}
	ContractPtr get_contract1(){ return contract1_; }
	ContractPtr get_contract2(){ return contract2_; }
	void accept(Visitor & visitor);
private:
	ContractPtr contract1_;
	ContractPtr contract2_;
};
class And : public Contract
{
public:
	And(ContractPtr c1, ContractPtr c2) : contract1_(c1), contract2_(c2){}
	ContractPtr get_contract1(){ return contract1_; }
	ContractPtr get_contract2(){ return contract2_; }
	void accept(Visitor & visitor);
private:
	ContractPtr contract1_;
	ContractPtr contract2_;
};
//Unsed...
template<class A_, class B_>
Obs<B_> lift(std::function<B_(A_)> f, Obs<A_> o)
{
	return Obs<B_>([=](Date t){
		PR<A_> & prs = o(t);
		std::vector<RV<B_>> new_unPr;
		for (auto rv : prs.unPr)
		{
			std::vector<B_> new_values(rv.values.size());
			std::transform(rv.values.begin(), rv.values.end(), new_values.begin(), f);
			new_unPr.push_back(RV<B_>(new_values));
		}
		return new_unPr;
	});
}
template<class A_, class B_, class C_>
Obs<C_> lift2(std::function<C_(A_, B_)> f, Obs<A_> & o1, Obs<B_> & o2)
{
	return Obs<C_>([=](Date t){
		PR<A_> & prs1 = o1(t);
		PR<B_> & prs2 = o2(t);
		const std::size_t size_unPr = prs1.unPr.size();
		const std::size_t size_values = prs1.unPr[0].size();
		PR<C_> pr;
		for (std::size_t i = 0; i < size_unPr; ++i)
		{
			std::vector<C_> new_values(prs1.unPr[i].size());
			for (std::size_t j = 0; j < size_values; ++j)
			{
				new_values[j] = f(prs1.unPr[i][j], prs2.unPr[i][j]);
			}
			pr.unPr.push_back(RV<C_>(new_values));
		}
		return pr;
	});
}
//Unsed...
template<class T_>
Obs<bool> operator==(Obs<T_> & o1, Obs<T_> & o2){
	std::function<bool(T_, T_)> f = ([](T_ a, T_ b){return a == b; });
	return lift2(f, o1, o2);
}
template<class T_> inline PR<T_> bigK(T_ x){ return PR<T_>(x); };
template<class T_> inline Obs<T_> konst(T_ val){ return Obs<T_>([=](Date t){return bigK(val); }); }
//Differ from the original implementation(http://contracts.scheming.org/) because I'm not sure how to write lazy/sequential process in C++ easily
static Obs<Date> date = Obs<Date>([](double t){return PR<Date>(mkDate(0));});
//inline Obs<bool> at(Date t){ return (konst<Date>(t) == date); }
inline Obs<bool> at(Date t){
	return Obs<bool>([=](Date dummy){
		PR<bool> pr;
		for (Date lt = 0; lt < t; ++lt)
		{
			pr.unPr.push_back(RV<bool>(1, false));
		}
		pr.unPr.push_back(RV<bool>(1, true));
		return pr;
	});
}
inline Obs<Date> mkObsDate(Date t){ return Obs<Date>([=](Date dummy){return PR<Date>(mkDate(t)); }); }
static ContractPtr zero = std::make_shared<Zero>();
inline ContractPtr one(Currency currency){ return std::make_shared<One>(currency); }
inline ContractPtr when(Obs<bool> & o, ContractPtr c){ return std::make_shared<When>(o, c); }
inline ContractPtr or(ContractPtr c1, ContractPtr c2){ return std::make_shared<Or>(c1, c2); }
inline ContractPtr and(ContractPtr c1, ContractPtr c2){ return std::make_shared<And>(c1, c2); }
inline ContractPtr scale(Obs<double> & o, ContractPtr contract){ return std::make_shared<Scale>(o, contract); }
//Compositional valuation semantics for contracts
inline ContractPtr european(Date t, ContractPtr c){return when(at(t), or(c, zero));}
inline ContractPtr zcb(Date t, double x, Currency k){ return when(at(t), scale(konst(x), one(k))); }


text:
package server.query;

import java.io.Serializable;

public class Query implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 2396198797934569671L;

	private String clientId;

	private QueryType type;

	public Query(String clientId, QueryType type) {
		super();
		this.clientId = clientId;
		this.type = type;
	}

	public String getClientId() {
		return clientId;
	}

	public void setClientId(String clientId) {
		this.clientId = clientId;
	}

	public QueryType getType() {
		return type;
	}

	public void setType(QueryType type) {
		this.type = type;
	}

}


text:
\hypertarget{unionun__mk1}{\section{un\-\_\-mk1 Union Reference}
\label{unionun__mk1}\index{un\-\_\-mk1@{un\-\_\-mk1}}
}
\subsection*{Data Fields}
\begin{DoxyCompactItemize}
\item
\hypertarget{unionun__mk1_ac88524fd8a511cf8a69603e25dfe3066}{unsigned short {\bfseries mk1}}\label{unionun__mk1_ac88524fd8a511cf8a69603e25dfe3066}

\item
\hypertarget{unionun__mk1_a0cf26ed6b612a34ae122f6101c95ce0f}{\hyperlink{struct_____b_i_t_s16}{\-\_\-\-\_\-\-B\-I\-T\-S16} {\bfseries B\-I\-T}}\label{unionun__mk1_a0cf26ed6b612a34ae122f6101c95ce0f}

\end{DoxyCompactItemize}

\subsection{Detailed Description}

Definition at line 342 of file iodefine.\-h.

The documentation for this union was generated from the following file\-:\begin{DoxyCompactItemize}
\item
C\-:/\-Users/\-Omega\-Dog/\-Dropbox/\-Kiln/\-Open\-R\-F/\-Protocol\-\_\-\-Platform/\-Source\-Code/\-Application/\-S\-X1231 Simple Test Application/iodefine.\-h\end{DoxyCompactItemize}


text:
require 'rspec'
require 'this_context_protocol'

RSpec.configure do |config|
  config.color_enabled = true
  config.formatter     = 'documentation'
end


text:
using System;

namespace TrainingsCalendar.Domain.Model
{
    public class StartEndModel
    {
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public int Month { get; set; }
        public int DaysInMonth { get; set; }
    }
}


text:
package irk.config

import java.io.{File, PrintWriter}

import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers}
import scala.concurrent.duration._

class IrkConfigSpec extends FunSpec with Matchers with BeforeAndAfterAll {

    val ft = IrkConfig(sequential = true, 2, 5, 60.seconds,Some("irk.conf"))

    val configFileName = "irk.conf"

    def createFile(data: String) = {
        val f = new File(configFileName)
        val pw = new PrintWriter(f)
        pw.write(data)
        pw.close()
    }

    def releaseFile = {
        val f = new File(configFileName)
        if (f.exists())
            f.delete()
    }

    override def beforeAll(): Unit = {
        releaseFile
    }

    describe(s"testing irk.config file") {
        it("file doesn't exists") {
            IrkConfig.loadFromFile(configFileName) shouldBe None
        }

        it("file has corrupted data") {
            createFile("{}")
            IrkConfig.loadFromFile(configFileName) shouldBe None
            releaseFile
        }

        it("file has valid data") {
            createFile(IrkConfig.fmtJson.writes(ft).toString())
            IrkConfig.loadFromFile(configFileName) shouldBe Some(ft)
            releaseFile
        }

    }

    override def afterAll(): Unit = releaseFile

}


text:
var CATEGORIA_CONJURADOR = new Categoria(CAT_CONJURADOR);

CATEGORIA_CONJURADOR.descripcion = "";
CATEGORIA_CONJURADOR.arquetipo = ARQ_MISTICO;
CATEGORIA_CONJURADOR.multiploDeVida = 20;
CATEGORIA_CONJURADOR.pvPorNivel = 5;
CATEGORIA_CONJURADOR.turnoPorNivel = 5;
CATEGORIA_CONJURADOR.CMPorNivel = 10;
CATEGORIA_CONJURADOR.nivelesParaCV = 3;

//HABILIDADES PRIMARIAS
CATEGORIA_CONJURADOR.limiteCombate = 0.5;
CATEGORIA_CONJURADOR.habAtaque = 3;
CATEGORIA_CONJURADOR.habParada = 3;
CATEGORIA_CONJURADOR.habEsquiva = 2;
CATEGORIA_CONJURADOR.habArmadura = 3;
CATEGORIA_CONJURADOR.ki = 3;
CATEGORIA_CONJURADOR.acumulacionKi = 30;
CATEGORIA_CONJURADOR.limiteSobrenatural = 0.6;
CATEGORIA_CONJURADOR.zeon = 1;
CATEGORIA_CONJURADOR.costeACT = 60;
CATEGORIA_CONJURADOR.proyeccionMagica = 3;
CATEGORIA_CONJURADOR.convocar = 1;
CATEGORIA_CONJURADOR.dominar = 1;
CATEGORIA_CONJURADOR.atar = 1;
CATEGORIA_CONJURADOR.desconvocar = 1;
CATEGORIA_CONJURADOR.limitePsiquica = 0.5;
CATEGORIA_CONJURADOR.costeCV = 20;
CATEGORIA_CONJURADOR.proyeccionPsiquica = 3;

//HABILIDADES SECUNDARIAS
CATEGORIA_CONJURADOR.atleticas = 2;
CATEGORIA_CONJURADOR.sociales = 2;
CATEGORIA_CONJURADOR.perceptivas = 2;
CATEGORIA_CONJURADOR.intelectuales = 2;
CATEGORIA_CONJURADOR.vigor = 3;
CATEGORIA_CONJURADOR.subterfugio = 2;
CATEGORIA_CONJURADOR.creativas = 2;

//Costes reducidos
CATEGORIA_CONJURADOR.costesReducidos = [
    new Coste(HB_OCULTISMO, 1, true, UDS_PD)
];

//BONIFICADORES INNATOS
CATEGORIA_CONJURADOR.bonosInnatos = [
    new Bono(BONO_HABILIDAD,HB_ZEON,50,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_CONVOCAR,10,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_DOMINAR,10,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_ATAR,10,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_DESCONVOCAR,10,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_VALORACION_MAGICA,5,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR}),
    new Bono(BONO_HABILIDAD,HB_OCULTISMO,10,"",true,BONO_INNATO,ORIGEN_CATEGORIA,{categoriaPersonaje:CAT_CONJURADOR})
];
categorias_set.push(CATEGORIA_CONJURADOR);


text:
package io.github.leovr.rtipmidi.messages;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class AppleMidiInvitationAcceptedTest {

    private final byte[] expectedMessage =
            {(byte) 0xff, (byte) 0xff, (byte) 0x4f, (byte) 0x4b, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
                    (byte) 0x00, (byte) 0x16, (byte) 0x3d, (byte) 0x91, (byte) 0x27, (byte) 0x8e, (byte) 0x7d,
                    (byte) 0x1c, (byte) 0x74, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00};

    @Test
    public void testInvitationAccepted() throws Exception {
        final AppleMidiInvitationAccepted accepted = new AppleMidiInvitationAccepted(2, 1457553, 663649564, "test");

        assertThat(accepted.toByteArray()).inHexadecimal().containsExactly(expectedMessage);
    }

}


text:
module.exports = Lead = require('typedef')

// THIS CODE WAS GENERATED BY AN AUTOMATED TOOL. Editing it is not recommended.
// For more information, see http://github.com/bvalosek/grunt-infusionsoft
// Generated on Wed Jan 08 2014 12:43:55 GMT-0600 (CST)

// This table holds opportunity record data.
.class('Lead') .define({

    __static__field__primary__number__read__Id:
        'Id',

    __static__field__string__edit__delete__add__read__OpportunityTitle:
        'OpportunityTitle',

    __static__field__number__edit__delete__add__read__ContactID:
        'ContactID',

    __static__field__number__edit__delete__add__read__AffiliateId:
        'AffiliateId',

    __static__field__number__edit__delete__add__read__UserID:
        'UserID',

    __static__field__number__edit__delete__add__read__StageID:
        'StageID',

    __static__field__number__edit__delete__add__read__StatusID:
        'StatusID',

    __static__field__string__add__read__Leadsource:
        'Leadsource',

    __static__field__string__edit__delete__add__read__Objection:
        'Objection',

    __static__field__number__edit__delete__add__read__ProjectedRevenueLow:
        'ProjectedRevenueLow',

    __static__field__number__edit__delete__add__read__ProjectedRevenueHigh:
        'ProjectedRevenueHigh',

    __static__field__string__edit__delete__add__read__OpportunityNotes:
        'OpportunityNotes',

    __static__field__datetime__edit__delete__read__DateCreated:
        'DateCreated',

    __static__field__datetime__edit__delete__read__LastUpdated:
        'LastUpdated',

    __static__field__number__edit__delete__add__read__LastUpdatedBy:
        'LastUpdatedBy',

    __static__field__number__edit__delete__add__read__CreatedBy:
        'CreatedBy',

    __static__field__datetime__edit__delete__add__read__EstimatedCloseDate:
        'EstimatedCloseDate',

    __static__field__datetime__edit__delete__add__read__NextActionDate:
        'NextActionDate',

    __static__field__string__edit__delete__add__read__NextActionNotes:
        'NextActionNotes'

});


text:
/* This file maybe included more than once */

/*-------------------------------------------------------------------------------------------------*\
 |    C O N S T A N T S   &   M A C R O S
\*-------------------------------------------------------------------------------------------------*/
/**
** ASF_TASK_STATIC ( ThreadId, EntryFunction, Priority, StackSize, QueueSize )
**      This macro declares a static thread that will be created (along with an
**      associated queue) automatically by the ASF startup initialization and
**      will persist throughout the lifetime of the application.
**
** Parameters:
**      ThreadId - User defined C-Style identifier for the thread.
**                 E.g. MY_THREAD_ID. This identifier will be used in the
**                 application to access the thread properties and its
**                 associated queue.
**      EntryFunction - Thread entry function name.
**      Priority - Thread priority in the range of 51 through 254. Higher value
**                 implies higher priority. Values 0 through 50 are reserved and
**                 should not be used.
**      StackSize - Thread stack size in bytes.
**      QueueSize - This denotes the maximum number of messages that are allowed
**                 to be queued for the thread. An optimum value should be
**                 chosen for this parameter to minimize memory wastage.
**
**      Example:   ASF_TASK_STATIC ( COMM_THREAD, CommThreadEntry, 55, 1024, 10 )
**
** Entry Function must be declared in the following manner:
**      ASF_TASK MyThreadEntry ( ASF_TASK_ARG )
**      {
**          ...
**      }
**
*/
/* Declare all ASF tasks here */
/* This task creates other tasks and OS resources and must always be present */
ASF_TASK_STATIC ( INSTR_MANAGER_TASK_ID,  InstrManagerTask,   50,  0x400,    4 )

/* Handles command input from UART */
ASF_TASK_STATIC ( CMD_HNDLR_TASK_ID,      CmdHandlerTask,     92,  0x400,    4 )

/* Additional tasks specific to application is defined in App_Tasks.h */
#include "app_tasks.h"

/*-------------------------------------------------------------------------------------------------*\
 |    E N D   O F   F I L E
\*-------------------------------------------------------------------------------------------------*/


text:
=head1 LICENSE

Copyright [1999-2016] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::FormatTranscriber::Callback::fasta_header

=head1 SYNOPSIS

  use Bio::FormatTranscriber::Callback::fasta_header

  $callback_obj = Bio::FormatTranscriber::Callback::fasta_header->new({header_pattern => "regex_of_fasta_header",
                                                                       parameter_1 => { hash of substitutions },
                                                                       parameter_2 => { hash of substitutions },
                                                                      );

  $updated_record = $callback_obj->run({record => $record});

=head1 DESCRIPTION

Callback to match a given FASTA header using regular expressions, and do
hash based substitutions on capture groups ($1, $2, $3).

For example a standard Ensembl FASTA header like:
>1 dna:chromosome chromosome:GRCh38:1:1:248956422:1 REF

would be matched by a regex such as:
"\\w+ [\\w:]+ \\w+:(\\w+):(\\w+):\\w+:\\w+:\\w+ \\w+"

where in this regex the assembly and slice (chromosome name) are captured
in to $1 and $2. In the callback initialization there should be
corresponding parameter_1 and parameter_2 options giving the
hash lookup tables to try and substitute the capture group from.

Mapping entry could look like:

    "fasta_header" : {
      "_callback" : "run",
      "_module" : "Bio::FormatTranscriber::Callback::fasta_header",
      "_init" : { "header_pattern" : "(\\w+) [\\w:]+ \\w+:(\\w+):\\w+:\\w+:\\w+:\\w+ \\w+",
                  "parameter_1" : "[[chromosome|homo_sapiens_ensembl_to_ucsc]]",
                  "parameter_2" : "[[assembly]]" },
      "_parameters" : { "record" : "{{record}}" }
    },
    "assembly" : { "GRCh38" : "New_Chromosome_Name" }

and be called during the _pre or _post field step of a filter, ie.

  "input_filter": { "_pre" : "fasta_header"
		  },

=cut

package Bio::FormatTranscriber::Callback::fasta_header;

use strict;
use warnings;
use Carp;
use Data::Dumper;

use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw);

use base qw/Bio::FormatTranscriber::Callback/;

sub new {
    my $class = shift;
    my $params = shift;
    my $self;

    unless($params->{header_pattern}) {
	throw("No regex given for the fasta header format");
    }
    $self->{pattern} = $params->{header_pattern};

    # Try to find substitution parameters which should match
    # the capture groups () in the regex
    $self->{parameters} = ();
    for(my $i=1; $i <= 9; $i++) {
	my $param_str = "parameter_$i";
	if($params->{$param_str}) {
	    $self->{parameters}->[$i] = $params->{$param_str};
	}
    }

    return bless $self, $class;
}

# Run routine for module, for each header of a fasta record,
# compare it against the regex string we received during
# initialization.

sub run {
    my $self = shift;
    my $params = shift;

    # Die if we weren't configured to receive a record
    unless((ref $params eq 'HASH') &&
	   $params->{record}) {
	throw "No record found for sequence";
    }

    # Extract the fasta header
    my $header = $params->{record}->header;

    # Try to compare the fasta header against the regex and if
    # it matches send it off to the switcher helper to make the changes
    if($header =~ s/$self->{pattern}/switcher($self->{parameters})/e) {
	$params->{record}->header($header);
    }

}

# Helper routine to do the actual substitution in the matching string,
# it takes the list of capture groups and their coordinates and tries
# to substitute in the replacement strings if they match in the
# corresponding lookup tables.

sub switcher {
    my $params = shift;

    # $& is the original matching string
    my $header = $&;
    # Capture all the capture groups in to an array we
    # can point at by index, rather than individual variables
    my @P = (undef,$1,$2,$3,$4,$5,$6,$7,$8,$9);

    # Working backwards since we're slicing an array and indexes will change,
    # go through all the parameters we've been given which should match
    # the capture groups, and see if we can substitute a new string
    # from the hash based lookup.
    for(my $i = $#{$params}; $i > 0; $i--) {
	# $params is a reference to an array of the lookup tables for the
	# substitutions, the index of the lookup table in $params should
	# correspond to the capture group () in the regex. ie. the 3rd
	# element in $params->[] should match the third () in the regex
	if($params->[$i]->{$P[$i]}) {
	    # Once we've found a match, use substr to replace the existing
	    # string at the point of the capture group () using the new
	    # one from the lookup table. @- is an array of the starting indexes
	    # of the matches and @+ is an array of the ending indexes of the
	    # matches in the original string.
	    substr $header, $-[$i], $+[$i] - $-[$i], $params->[$i]->{$P[$i]};
	}
    }

    return $header;
}

1;


text:
from __future__ import annotations

import asyncio
import logging
from datetime import datetime
from typing import Iterator, Literal, NamedTuple, Optional

import discord
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.data_manager import cog_data_path
from redbot.core.utils import menus

from .apsw_wrapper import Connection
from .converters import MemberOrID

log = logging.getLogger("red.sinbadcogs.modnotes")

class Note(NamedTuple):
    uid: int
    author_id: int
    subject_id: int
    guild_id: int
    note: str
    created_at: int

    def embed(self, ctx, color) -> discord.Embed:
        e = discord.Embed(
            description=self.note,
            timestamp=datetime.fromtimestamp(self.created_at),
            color=color,
        )
        author = ctx.guild.get_member(self.author_id)
        subject = ctx.guild.get_member(self.subject_id)
        a_str = (
            f"{author} ({self.author_id})"
            if author
            else f"Unknown Author ({self.author_id})"
        )
        s_str = (
            f"{subject} ({self.subject_id})"
            if subject
            else f"Unknown Subject ({self.subject_id})"
        )
        e.add_field(name="Note Author", value=a_str)
        e.add_field(name="Note Subject", value=s_str)
        return e

class ModNotes(commands.Cog):
    """
    Store moderation notes
    """

    __version__ = "2021.03"

    async def red_delete_data_for_user(
        self,
        *,
        requester: Literal["discord_deleted_user", "owner", "user", "user_strict"],
        user_id: int,
    ):
        if requester != "discord_deleted_user":
            return
        await self.bot.send_to_owners(
            f"Data deletion request for `ModNotes` by {requester} for user id {user_id}."
        )

    def format_help_for_context(self, ctx):
        pre_processed = super().format_help_for_context(ctx)
        return f"{pre_processed}\nCog Version: {self.__version__}"

    def __init__(self, bot: Red):
        self.bot: Red = bot
        fp = str(cog_data_path(self) / "notes.db")
        self._connection = Connection(fp)
        self._ready_event = asyncio.Event()
        self._init_task: Optional[asyncio.Task] = None

    def init(self):
        self._init_task = asyncio.create_task(self.initialize())

        def done_callback(fut: asyncio.Future):

            try:
                fut.exception()
            except asyncio.CancelledError:
                log.info("Modnotes didn't set up and was cancelled")
            except asyncio.InvalidStateError as exc:
                log.exception(
                    "We somehow have a done callback when not done?", exc_info=exc
                )
            except Exception as exc:
                log.exception("Unexpected exception in modnotes: ", exc_info=exc)

        self._init_task.add_done_callback(done_callback)

    async def initialize(self):
        await self.bot.wait_until_ready()
        with self._connection.with_cursor() as cursor:
            cursor.execute("""PRAGMA journal_mode=wal""")

            # rename if exists NOTES -> member_notes
            cursor.execute("""PRAGMA table_info("NOTES")""")
            if cursor.fetchone():
                cursor.execute("""ALTER TABLE NOTES RENAME TO member_notes""")

            cursor.execute(
                """
                CREATE TABLE IF NOT EXISTS member_notes (
                    uid INTEGER PRIMARY KEY AUTOINCREMENT,
                    author_id INTEGER NOT NULL,
                    subject_id INTEGER NOT NULL,
                    guild_id INTEGER NOT NULL,
                    note TEXT,
                    created INTEGER NOT NULL
                )
                """
            )
            # If lookups feel slow,
            # Consider an index later on member_notes(subject_id, guild_id)
        self._ready_event.set()

    async def cog_before_invoke(self, ctx):
        await self._ready_event.wait()

    def cog_unload(self):
        if self._init_task:
            self._init_task.cancel()

    def insert(self, *, author_id: int, subject_id: int, guild_id: int, note: str):
        with self._connection.with_cursor() as cursor:
            now = int(datetime.utcnow().timestamp())
            cursor.execute(
                """
                INSERT INTO member_notes(author_id, subject_id, guild_id, note, created)
                VALUES(?,?,?,?,?)
                """,
                (author_id, subject_id, guild_id, note, now),
            )

    def find_by_author(self, author_id: int) -> Iterator[Note]:
        with self._connection.with_cursor() as cursor:
            for items in cursor.execute(
                """
                SELECT uid, author_id, subject_id, guild_id, note, created
                FROM member_notes
                WHERE author_id=?
                ORDER BY created
                """,
                (author_id,),
            ):
                yield Note(*items)

    def find_by_author_in_guild(
        self, *, author_id: int, guild_id: int
    ) -> Iterator[Note]:
        with self._connection.with_cursor() as cursor:
            for items in cursor.execute(
                """
                SELECT uid, author_id, subject_id, guild_id, note, created
                FROM member_notes
                WHERE author_id=? AND guild_id=?
                ORDER BY created
                """,
                (author_id, guild_id),
            ):
                yield Note(*items)

    def find_by_member(self, *, member_id: int, guild_id: int) -> Iterator[Note]:
        with self._connection.with_cursor() as cursor:
            for items in cursor.execute(
                """
                SELECT uid, author_id, subject_id, guild_id, note, created
                FROM member_notes
                WHERE subject_id=? AND guild_id=?
                ORDER BY created
                """,
                (member_id, guild_id),
            ):
                yield Note(*items)

    def find_by_guild(self, guild_id: int) -> Iterator[Note]:
        with self._connection.with_cursor() as cursor:
            for items in cursor.execute(
                """
                SELECT uid, author_id, subject_id, guild_id, note, created
                FROM member_notes
                WHERE guild_id=?
                ORDER BY created
                """,
                (guild_id,),
            ):
                yield Note(*items)

    def delete_by_uid(self, uid: int):
        with self._connection.with_cursor() as cursor:
            cursor.execute("DELETE FROM NOTES WHERE uid=?", (uid,))

    @checks.mod()
    @commands.guild_only()
    @commands.command()
    async def makemodnote(self, ctx, user: MemberOrID, *, note: str):
        """ Make a note about a user """

        self.insert(
            author_id=ctx.author.id,
            subject_id=user.id,
            note=note,
            guild_id=ctx.guild.id,
        )
        await ctx.tick()

    @checks.mod()
    @commands.guild_only()
    @commands.group()
    async def getmodnotes(self, ctx):
        """ Get notes """
        pass

    @getmodnotes.command()
    async def about(self, ctx, user: MemberOrID):
        """ Get notes about a user """
        color = await ctx.embed_color()
        notes = [
            n.embed(ctx, color)
            for n in self.find_by_member(member_id=user.id, guild_id=ctx.guild.id)
        ]
        if not notes:
            return await ctx.send("No mod notes about this user")
        mx = len(notes)
        for i, n in enumerate(notes, 1):
            n.title = f"Showing #{i} of {mx} found notes"

        await menus.menu(ctx, notes, menus.DEFAULT_CONTROLS)


text:
import {Component, Input, OnInit} from '@angular/core';
import {SecUtil} from '../../classes/sec-util';
import {ErrorHandlerService} from '../../services/error-handler.service';
import {CommentDTO, CommentsRestControllerService} from '../../ws/soccer';

@Component({
    selector: 'app-comment',
    template: `

          {{comment?.content}} - {{'text.by' | translate}} {{comment?.postedBy?.name}} {{'text.on' | translate}} {{comment?.postDate}}

                  <button type="button" class="btn btn-warning" aria-label="Delete comment" (click)="deleteComment(comment)" title="{{'tooltip.comments.delete' | translate}}">

                  </button>
                  <button type="button" class="btn" aria-label="Edit comment" (click)="showEditComment = !showEditComment" title="{{'tooltip.comments.edit' | translate}}">

                  </button>

            <app-comment-form (onSubmit)="updateComment($event)" [comment]="comment"></app-comment-form>

  `,
    styles: []
})
export class CommentComponent implements OnInit {
    @Input() comment: CommentDTO;
    @Input() messageId: string;

    private showEditComment: boolean;
    private showBtns: boolean;

    constructor(private _errorHandler: ErrorHandlerService, private _api: CommentsRestControllerService) {
    }

    ngOnInit() {
    }

    isLoggedIn() {
        return SecUtil.isLoggedIn();
    }

    isAdmin() {
        return SecUtil.isAdmin();
    }

    getUser() {
        return SecUtil.getUser();
    }

    updateComment(comment: CommentDTO) {

        this.showEditComment = false;
        this._api.editComment(comment, this.messageId)
            .subscribe(r => {
                console.log("success");
                this.comment.content = comment.content;
                },
                e => {
                    this._errorHandler.handle(e);
            })
    }

    deleteComment(comment: CommentDTO) {

        this.showEditComment = false;
        this._api.deleteComment(this.messageId, comment.id)
            .subscribe(
                r => {
                console.log("success");
                this.comment = null;
                },
                e => {
                    this._errorHandler.handle(e);
                }
            )
    }

}


text:
Koffie ☕ [![License](https://img.shields.io/npm/l/koffie.svg)](#)
===============================================================

[![npm version](https://img.shields.io/npm/v/koffie.svg?maxAge=2592000)](https://www.npmjs.com/package/koffie)
[![Bower version](https://img.shields.io/bower/v/koffie.svg?maxAge=2592000)](#)
[![Build Status](https://img.shields.io/travis/ghaschel/koffie.svg?maxAge=2592000)](https://travis-ci.org/ghaschel/koffie)
[![devDependency Status](https://david-dm.org/ghaschel/koffie/dev-status.svg)](https://david-dm.org/ghaschel/koffie#info=devDependencies)

*A pack of useful mixins, functions, classes and placeholders for a faster development. Available in Stylus, LESS, and SCSS.*

## Installation

You can get the latest version of Koffie in a few different ways:

- Get the [Latest Release](https://github.com/ghaschel/koffie/archive/v1.1.4.zip)
- Clone the repo: `git clone https://github.com/ghaschel/koffie.git`
- Install with [Bower](https://bower.io/): `bower install koffie`
- Install with [npm](https://www.npmjs.com/): `npm install koffie`

## Documentation

Take a look at the [docs](https://rawgit.com/ghaschel/koffie/master/docs/index.html) and see how a cup of Koffie can help you code faster.


text:
@interface DAAutorizeVKViewController : UIViewController

@end