text:
AliAnalysisTask *AddTask_ffionda_BJPsi(Bool_t isMC=kFALSE){
  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_ffionda_BJPsi", "No analysis manager found.");
    return 0;
  }

  //Do we have an MC handler?
  Bool_t hasMC=isMC;
    //(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
  //Do we have an AOD handler?
  Bool_t isAOD=(mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class() ? kTRUE : kFALSE);

  //set config file name
  TString configFile("$TRAIN_ROOT/jbook_jpsi/ConfigJpsi_jb_PbPb.C");
  TString trainRoot=gSystem->Getenv("TRAIN_ROOT");
  if (trainRoot.IsNull()) configFile="$ALICE_PHYSICS/PWGDQ/dielectron/macrosJPSI/ConfigBJpsi_ff_PbPb.C";

  //create task and add it to the manager
  AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDieData");
  task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
  if (!hasMC) task->UsePhysicsSelection();
  mgr->AddTask(task);

  //load dielectron configuration file
  TString checkconfig="ConfigJpsi_ff_PbPb";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<2; ++i){ //nDie defined in config file
    AliDielectron *jpsi=ConfigBJpsi_ff_PbPb(i,hasMC);
    if (jpsi ) task->AddDielectron(jpsi);
    if (jpsi ) printf("add: %s\n",jpsi->GetName());
  }

  //Add event filter
  AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
  if(!hasMC) eventCuts->SetRequireVertex();
  if (isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
  eventCuts->SetMinVtxContributors(1);
  eventCuts->SetVertexZ(-10.,10.);
  eventCuts->SetCentralityRange(0.0,80.0);
  task->SetEventFilter(eventCuts);

  //create output container
  TString containerName = "JPSI.root";
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("ffionda_tree",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
			 containerName.Data());

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("ffionda_QA",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
			 containerName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("ffionda_CF",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
			 containerName.Data());

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("ffionda_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
			 containerName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);
  return task;
}


text:
import os

MAX_SIZE = 2048
WORK_PATH = os.path.dirname(os.path.realpath(__file__))
CLASSIFIER_PATH = os.path.join(WORK_PATH, 'ocr', 'classifier', 'clf_svm_def.pkl')

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
| -------------------------------------
| @file  : Registrar.php
| @date  : 3/24/2015
| @author:
| -------------------------------------
*/

class Registrar extends CI_Controller
{
    // @deprecated move this function to Search class
    // retain only for backward compatibility
    function search_by_id($id)
    {
        $this->load->model('registrar/party');

        // clean the url since the request is a get method
        $id         = urldecode($id);
        $data       = array();
        $results_id = $this->party->searchId($id);
        $stat       = $this->session->userdata('status');

        foreach ($results_id as $r) {
            $data[] = array('value' => $r['legacyid'], 'name' => $r['firstname'] . ' ' . $r['lastname']);
        }

        echo json_encode($data);
    }

    // @deprecated move this function to Search class
    // retain only for backward compatibility
    function search_forpayment($id)
    {
        $this->load->model('registrar/party');
        $id         = urldecode($id);
        $data       = array();
        $results_id = $this->party->search_pay($id);

        foreach ($results_id as $r) {
            $data[] = array('value' => $r['legacyid'], 'name' => $r['firstname'] . ' ' . $r['lastname']);
        }

        echo json_encode($data);
    }

    // @deprecated move this function to Search class
    // retain only for backward compatibility
    function search_sub($txt)
    {
        $txt    = urldecode($txt);
        $data   = array();
        $r      = $this->db->query("SELECT name, descriptivetitle FROM tbl_subject
                    WHERE code LIKE '%$txt%'
                    OR descriptivetitle LIKE '%$txt%'
                    ORDER BY code LIMIT 10 ")->result_array();

        foreach ($r as $rr) {
            $data[] = array('value' =>  $rr['code'], 'name' => $rr['descriptivetitle']);
        }

        echo json_encode($data);
    }

    function edit_grades($code, $subject, $grade)
    {
        $data['code'] = $code;
        $data['subject'] = $subject;
        $data['grade'] = $grade;
        $this->head();
        $this->load->view('registrar/edit_gades', $data);
        $this->load->view('templates/footer');
    }

    function buildup($id)
    {
        $this->load->model(array(
            'registrar/course', 'home/useroption',
            'registrar/grade', 'registrar/common',
            'registrar/subject', 'registrar/party',
            'registrar/academicterm', 'registrar/log_student',
            'registrar/enrollment','registrar/studentgrade',
            'registrar/registration','registrar/curriculum',
            'registrar/curriculumdetail'
        ));

        $this->api->userMenu();

        $data['id'] = $id;
        $this->load->view('registrar/buildstudRecord', $data);
        $this->load->view('templates/footer');
    }

    public function insert_subject()
    {
        $data['code']               = strtoupper($this->input->post('code'));
        $data['descriptivetitle']   = strtoupper($this->input->post('descriptivetitle'));
        $data['units']              = $this->input->post('units');
        $data['own']                = $this->input->post('school_id');

        $where = "(code = {$data['code']} OR descriptivetitle = {$data['descriptivetitle']}) AND own = {$data['own']}";

        $this->db->where($where);
        $count = $this->db->count_all_results('tbl_subject');

        if ($count > 0) {
            $this->api->set_session_message('danger', 'Duplicate Subject Code Or Descriptivetitle', 'message1');
        } else {
            $this->db->insert('tbl_subject', $data);
            $this->api->set_session_message('success', 'Successfully Inserted', 'message1');
        }

        redirect('/rgstr_build/'.$this->input->post('legacyid').'#academic_wrapper');
    }

    function permanentRecord($id)
    {

        $this->load->model(array(
            'registrar/tor'
        ));

        $this->api->userMenu();

        $data['id'] = $id;
        $this->load->view('registrar/view_permanent_record', $data);
        $this->load->view('templates/footer');
    }

    function search()
    {
        $this->load->model('registrar/party');
        $id     = $this->input->post('search');
        $id1    = $this->party->existsID($id);

        if ($id1 > 0) {
            redirect('/rgstr_build/' . $id);
        } else {
            $this->session->set_flashdata('message', '
Unable to find student id
');
            redirect($this->input->post('cur_url'));
        }
    }

    function save_grade()
    {
        $enrolmentid    = $this->input->post('enrolmentid');
        $subjid         = $this->input->post('add_subj');
        $grade          = $this->input->post('sub_grade');
        $academicid     = $this->input->post('academictermid');
        $schoolid       = $this->input->post('schoolid');

        $this->load->model(array(
            'registrar/classallocation',
            'registrar/studentgrade',
            'registrar/subject',
            'registrar/grade',
            'registrar/log_student',
            'registrar/enrollment'
        ));

        $data['subject']        = $subjid;
        $data['academicterm']   = $academicid;
        //$count = $this->classallocation->whereCount($data);

        // we can prevent user from entering duplicate subj within a academicterm but
        // the studentgrade table will be a mess
        // cause we will not create a new record in tbl_classallocation
        // just fetch the first record that is found
        $this->db->where('enrolment', $enrolmentid);
        $this->db->where('subject', $subjid);
        $q = $this->db->count_all_results('views_studentgrade');

        if ($q < 1) {
            $id = $this->classallocation->insert_ca_returnId($subjid, $academicid);

            if (is_numeric($id)) {
                $data['subj']           = $subjid;
                $data['grade_user']     = $grade;
                $data['enrolmentid']    = $enrolmentid;
                $data['academicterm']   = $academicid;
                $data['schoolid']       = $schoolid;
                $p                      = $this->enrollment->getID($enrolmentid);
                $this->log_student->insert_not_exists($p['student'],'E');
                $data['sid']            = $this->studentgrade->save_grade_returnId($id, $grade, $enrolmentid);
                $this->load->view('registrar/ajax/add_subject', $data);
            } else
                echo 'error';
        } else
            echo 'Subject Already exists';
    }

    function insert_flag()
    {
        $this->load->model(array(
            'registrar/common',
            'registrar/log_student'
        ));
        $partyid        = $this->input->post('partyid');
        $url            = $this->input->post('url');
        $flag_status    = $this->input->post('flag_status');

        $curtm = $this->log_student->getLatestTm($partyid);

        if ($flag_status == 'C') {
            $tm = $this->input->post('tm');

            if ($tm == $curtm) {
                $this->add_flag($partyid, $flag_status);
                $data['user']       = $this->session->userdata('uid');
                $data['dte']        = date('Y-m-d');
                $data['student']    = $partyid;
                $data['status']     = $flag_status;
                $data['tm']         = time();
                $this->db->insert('log_student');
            } else {
                $this->session->set_flashdata('message', '

A update has been occurred before you submit.
                    Please review again and then submit

');
                redirect($url);
            }
        } else {
            $this->log_student->ins_stat($partyid, $flag_status);
            $this->add_flag($partyid, $flag_status);
        }
    }

    private function add_flag($partyid, $status)
    {
        $this->load->model('registrar/common');
        $data2 = array('status' => $status);
        $this->db->where('id', $partyid);
        $this->db->update('tbl_party', $data2);
        redirect('/');
    }

    function save_edit_grade()
    {
        $this->load->model(array(
            'registrar/studentgrade',
            'registrar/log_student',
            'registrar/enrollment'
        ));
        $val    = $this->input->post('val');
        $cat    = explode('_', $val);
        $i      = 0;

        foreach ($cat as $c) {
            $v = explode('-', $c);
            if ($i == 0)
                $studgrade = $v[1];
            elseif ($i == 1)
                $grade_id = $v[1];
            else
                $enroll = $v[1];
            $i++;
        }

        $q      = $this->enrollment->getID($enroll);
        $pid    = $q['student'];
        $stat   = $this->log_student->chkStatus($pid);

        if ($stat['status'] != 'S') {
            $this->log_student->insert_not_exists($q['student'], 'E');
            $this->studentgrade->update_grade($studgrade, $grade_id);
        } else
            echo 'This record is already submitted';
    }

    function delete_record()
    {
        $this->load->model(array(
            'registrar/studentgrade',
            'registrar/enrollment'
        ));

        $val        = $this->input->post('value');
        $cat        = explode('-', $val);
        $enrolid    = $cat[0];
        $studgrade  = $cat[1];
        $this->studentgrade->delete_grade($studgrade);
        $this->enrollment->update_record($enrolid);
    }

    function add_acam()
    {
        $partyid    = $this->input->post('partyid');
        $sch_id     = $this->input->post('school_id');
        $cid        = $this->input->post('course_id');
        $syid       = $this->input->post('sy_id');

        $this->load->model(array(
            'registrar/enrollment', 'registrar/party',
            'registrar/course', 'registrar/academicterm',
            'registrar/subject', 'registrar/grade',
            'registrar/log_student','registrar/registration',
            'registrar/curriculum','registrar/curriculumdetail'
        ));

        $data['student']            = $partyid;
        $data['coursemajor']        = $cid;
        $data['academicterm']       = $syid;
        $data['school']             = $sch_id;
        $data['numberofsubject']    = 1;

        $db['academicterm'] = $syid;
        $db['student']      = $partyid;

        $stat = $this->log_student->chkStatus($partyid);
        if ($stat['status'] != 'S') {
            $count = $this->enrollment->whereCount($db);

            if ($count < 1) {
                $d['student']       = $partyid;
                $d['coursemajor']   = $cid;
                $d['academicterm']  = $syid;
                $this->registration->ins_not_exist($d);
                $this->log_student->insert_not_exists($partyid, 'E');
                $id = $this->enrollment->insert_return_id($data);
                $data['id'] = $id;
                $this->load->view('registrar/ajax/add_academicterm', $data);
            } else {
                echo 'Academic Term Already Exists';
            }
        } else {
            echo 'This record is already submitted';
        }

    }

    function add_session()
    {
        $value = $this->input->post('value');
        $this->session->set_userdata('status', $value);
        $data['param'] = $this->input->post('param');
        $this->load->model(array(
            'registrar/enrollment',
            'registrar/party',
            'registrar/course'
        ));
        $this->load->view('registrar/ajax/tbl_studlist', $data);
    }
    function delete_acam()
    {
        $enrolmentid = $this->input->post('eid');
        $this->load->model(array(
            'registrar/enrollment',
            'registrar/studentgrade',
            'registrar/classallocation',
            'registrar/log_student'
        ));

        $p      = $this->enrollment->getID($enrolmentid);
        $pid    = $p['student'];
        $stat   = $this->log_student->chkStatus($pid);

        if ($stat['status'] != 'S') {
            $this->log_student->insert_not_exists($p['student'], 'E');
            $this->enrollment->delete_enroll($enrolmentid);

            // after the classallocation has been deleted
            // its time to deleted the subjects grade
            $this->studentgrade->delete($enrolmentid);
        } else {
            echo 'This record is already submitted';
        }
    }
    function add_re_exam()
    {
        $this->load->model(array(
            'registrar/studentgrade',
            'registrar/log_student',
            'registrar/enrollment'
        ));

        $val    = $this->input->post('val');
        $cat    = explode('_', $val);
        $i      = 0;

        foreach ($cat as $c)
        {
            $v = explode('-', $c);
            if ($i == 0)
                $studgrade = $v[1];
            elseif ($i == 1)
                $grade_id = $v[1];
            else
                $enroll = $v[1];
            $i++;
        }

        $q      = $this->enrollment->getID($enroll);
        $pid    = $q['student'];
        $stat   = $this->log_student->chkStatus($pid);

        if ($stat['status'] != 'S') {
            $this->log_student->insert_not_exists($q['student'], 'E');
            $this->studentgrade->update_reexam_grade($studgrade, $grade_id);
        }
        else
            echo 'This record is already submitted';
    }

    function re_exam()
    {
        $this->load->model(array(
            'registrar/log_student',
            'registrar/enrollment',
            'registrar/grade',
            'registrar/studentgrade'
        ));

        $enrol_id   = $this->input->post('enrol');
        $q          = $this->enrollment->getID($enrol_id);
        $pid        = $q['student'];
        $stat       = $this->log_student->chkStatus($pid);

        if ($stat['status'] != 'S') {
            $grade_id               = $this->input->post('grad');
            $data['enrolmentid']    = $enrol_id;
            $data['sid']            = $this->input->post('stugrade');

            $this->studentgrade->update_grade($data['sid'],$grade_id);
            $this->log_student->insert_not_exists($pid, 'E');
            $this->load->view('registrar/ajax/re_exam',$data);
        } else {
            echo 'This record is already submitted';
        }
    }

    function update_studinfo()
    {
        //update in tbl_party
        $partyid    = $this->input->post('partyid');
        $firstname  = $this->input->post('firstname');
        $middlename = $this->input->post('middlename');
        $lastname   = $this->input->post('lastname');
        $dob        = $this->input->post('dob');
        $pob        = $this->input->post('pob');
        $address1   = $this->input->post('address1');
        $address2   = $this->input->post('address2');

       //update in tbl_student
        $primary        = $this->input->post('primary');
        $elementary     = $this->input->post('elementary');
        $highschool     = $this->input->post('highschool');
        $primaryyear    = $this->input->post('primaryyear');
        $elementaryyear = $this->input->post('elementaryyear');
        $highschoolyear = $this->input->post('highschoolyear');

        //latest registration to be updated
        $url            = $this->input->post('url');
        $course         = $this->input->post('course');
        $dateregistered = $this->input->post('dateregistered');
        $dor            = $this->input->post('dor');
        $dat = date('Y');

        $start  = new DateTime($dob);
        $end    = new DateTime(date('Y-m-d'));
        $dDiff  = $start->diff($end);
        $dif    = $dDiff->format('%Y');
        $alerts = '
<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="color:red">×</button>';
        $suc    = '<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="color:red">×</button>';

        if ($dif < 10) {
            $this->session->set_flashdata('message', $alerts . 'Invalid Date of Birth.
');
        } elseif ($pob == '') {
            $this->session->set_flashdata('message',  $alerts . 'Please Fill-up Place of Birth
');
        } elseif ($address1 == '') {
            $this->session->set_flashdata('message',  $alerts . 'Please Fill-up Address
');
        } elseif ($elementary == '' OR $elementary == 'Select') {
            $this->session->set_flashdata('message',  $alerts . 'Please Select First Elementary School
');
        } elseif ($primary == '' OR $primary == 'Select') {
            $this->session->set_flashdata('message',  $alerts . 'Please Select First Primary School
');
        } elseif ($highschool == '' OR $highschool == 'Select') {
            $this->session->set_flashdata('message', $alerts . 'Please Select First High School
');
        } elseif ($primaryyear == '' OR $primaryyear > $dat) {
            $this->session->set_flashdata('message',  $alerts . 'Please Select First Year of Completion in Primary School
');
        } elseif ($elementaryyear == '' OR $elementaryyear > $dat) {
            $this->session->set_flashdata('message', $alerts . 'Please Select First Year of Completion in Elementary School
');
        } elseif ($highschoolyear == '' OR $highschoolyear > $dat) {
            $this->session->set_flashdata('message', $alerts . 'Please Select First Year of Completion in High School
');
        } else {

            $this->session->set_flashdata('message', '
'. $suc . 'Information Successfuly Saved.
');
            $data = array(
                'firstname'     => $firstname,
                'middlename'    => $middlename,
                'lastname'      => $lastname,
                'dateofbirth'   => $dob,
                'placeofbirth'  => $pob,
                'address1'      => $address1,
                'address2'      => $address2,
            );
            $this->db->where('id', $partyid);
            $this->db->update('tbl_party', $data);

            $data2 = array(
                'primary'               => $primary,
                'elementary'            => $elementary,
                'secondary'             => $highschool,
                'completionprimary'     => $primaryyear,
                'completionelementary'  => $elementaryyear,
                'completionsecondary'   => $highschoolyear
                );
            $this->db->where('id', $partyid);
            $this->db->update('tbl_student', $data2);
            $coursmaj = $this->db->query("SELECT course, id FROM tbl_coursemajor WHERE course = '$course'");
            $x = $coursmaj->row_array();
            $x['id'];
            $data3 = array('coursemajor' => $course,
                            'date' => $dor
                            );
            $this->db->where('student', $partyid);
            $this->db->where('date',$dateregistered);
            $this->db->update('tbl_registration', $data3);

        }
        $x = array(
            'firstname'             => $firstname,
            'middlename'            => $middlename,
            'lastname'              => $lastname,
            'dob'                   => $dob,
            'pob'                   => $pob,
            'address1'              => $address1,
            'address2'              => $address2,
            'primary'               => $primary,
            'elementaryss'          => $elementary,
            'secondary'             => $highschool,
            'completionprimary'     => $primaryyear,
            'completionelementary'  => $elementaryyear,
            'completionsecondary'   => $highschoolyear
        );
        $_SESSION['infos'] = $x;
        // print_r($_SESSION['infos']);
        redirect('/rgstr_build/' . $url);
    }

    function add_school()
    {
        if ($this->input->post('ajax')) {
            $msg = 'message1';
        }
        else{
            $msg = 'message';
        }
        $sch    = strtoupper($this->input->post('school'));
        $add    = strtoupper($this->input->post('address'));
        $short  = strtoupper($this->input->post('short'));
        $name   = strtoupper($this->input->post('name'));
        $lvl1   = strtoupper($this->input->post('lvl1'));
        $lvl2   = strtoupper($this->input->post('lvl2'));
        $lvl3   = strtoupper($this->input->post('lvl3'));
        $lvl4   = strtoupper($this->input->post('lvl4'));

        $data = array(
            'sch'   => $sch,
            'add'   =>$add,
            'short' =>$short,
            'name'  =>$name,
            'lvl1'  =>$lvl1,
            'lvl2'  =>$lvl2,
            'lvl3'  =>$lvl3,
            'lvl4'  =>$lvl4
        );

        if($this->input->post('action') == 'add'){
            $query = $this->db->query("SELECT COUNT(*) as ctr FROM tbl_party, tbl_school
                              WHERE firstname = '$sch' AND tbl_party.id = tbl_school.id");
            $query = $query->row_array();
            $query = $query['ctr'];
        }
        else{
            $sname   = strtoupper($this->input->post('sname'));
            if ($sname == $sch) {
                $query = 0;
            }
            else{
                $query = $this->db->query("SELECT COUNT(*) as ctr FROM tbl_party, tbl_school
                                 WHERE firstname = '$sch' AND firstname = '$sch' AND tbl_party.id = tbl_school.id");
                $query = $query->row_array();
                $query = $query['ctr'];
            }
        }

        if ($query == 0) {

            $data1 = array(
                'firstname' => $sch,
                'address1'  => $add,
                'shortname' => $short
            );

            if ($this->input->post('action') == 'add') {
                $this->db->insert('tbl_party', $data1);
                $id = $this->db->insert_id();
            } else {
                $this->db->where('id', $this->input->post('id'));
                $this->db->update('tbl_party', $data1);
            }

            $data2 = array(
                'id'            => $id,
                'registrarname' => $name,
                'primary'       => $lvl1,
                'elementary'    => $lvl2,
                'secondary'     => $lvl3,
                'tertiary'      => $lvl4
            );

            if($this->input->post('action') == 'add'){

                $this->db->insert('tbl_school', $data2);

                $this->session->set_flashdata($msg, '

                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                      Success!  School successfully added!.

                ');

                if ($this->input->post('ajax')) {
                    redirect('/rgstr_build/'.$this->input->post('student').'#academic_wrapper');
                }
                else{
                    redirect('/menu/registrar-sys_param/');
                }
            }
            else{

                $data3 = array(
                    'registrarname' => $name,
                    'primary'       => $lvl1,
                    'elementary'    => $lvl2,
                    'secondary'     => $lvl3,
                    'tertiary'      => $lvl4
                );
                $this->db->where('id', $this->input->post('id'));
                $this->db->update('tbl_school', $data3);

                $this->session->set_flashdata($msg, '

                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                      Success!  School successfully updated!.

                ');

                redirect('/menu/registrar-sys_param/');
            }

        }
        else{
            $this->session->set_flashdata($msg, '

                  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                  Stop!  School name already exist.

            ');
            $_SESSION['data'] = $data;
            if ($this->input->post('action') == 'add') {
                if ($this->input->post('ajax')) {
                    redirect('/rgstr_build/'.$this->input->post('student').'#academic_wrapper');
                }
                else{
                    redirect('/menu/registrar-sys_param/');
                }
            }
            else{
                redirect('/menu/registrar-sys_param/'.$this->input->post('id'));
            }
        }

    }

    function delete_school($id)
    {
        $this->load->model('registrar/common');
        $query = $this->common->check_school($id);

        if($query == 0){
                $this->common->delete_school($id);

                $this->session->set_flashdata('message', '

                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                      Success!  School successfully deleted!.

                ');
        }
        else{
                $this->session->set_flashdata('message', '

                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                      Unable to delete school still in use !.

                ');
        }
        redirect('/menu/registrar-sys_param/');
    }

    function search_student_det($sid)
    {
        $sid = urldecode($sid);
        $this->load->model(array(
            'registrar/tor'
        ));
        $s          = $this->tor->getStudent($sid);
        $data       = array();

        foreach ($s as $r)
        {
            $data[] = array('value' => $r['legacyid'], 'name' => $r['lastname'].' '.$r['firstname']);
        }
        echo json_encode($data);
    }

    function tor($sid = '')
    {
        $sid = array('sid' => $sid);
        $this->load->model('registrar/tor');
        $this->load->view('registrar/tor_preview', $sid);
    }

    function tor_preview()
    {
        redirect('/registrar_tor/'.$this->input->post('search'));
    }

    // this function will be for the new student registration
    function registration()
    {
        $this->load->library('form_validation');
        $this->load->helper('form');

        $field = array(
                    'lastname'      => 'Lastname',
                    'firstname'     => 'Firstname',
                    'middlename'    => 'Middlename',
                    'course'        =>'Course',
                    'gender'        =>'Gender',
                    'religion'      =>'Religion',
                    'dob'           =>'Date of Birth',
                    'mailadd'       =>'Mailing Address',
                    'username'      => 'Username',
                    'password'      =>'Password',
                    'rpass'         =>'Repeat Password',
                    'emailadd'      =>'Email Address'
                );

        foreach ($field as $key => $value) {
            $this->form_validation->set_rules($key, $value, 'required');
        }
        // nationality not found in tbl_party
        //$this->form_validation->set_rules('nationality', 'Nationality','required');
        $d['error'] = '';

        if ($this->form_validation->run() === FALSE) {
            $this->api->userMenu();
            $d['fname']     = set_value('firstname');
            $d['lname']     = set_value('lastname');
            $d['mname']     = set_value('middlename');
            $d['legacyid']  = ($this->input->post('sid')    ? $this->input->post('sid') : 0);
            $d['course']    = ($this->input->post('course') ? $this->input->post('course') : 0);
            $this->load->view('registrar/newstudent_registration', $d);
            $this->load->view('templates/footer2');
        } else {
            $email = $this->input->post('emailadd');
            //check if the email add is valid
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $password = $this->input->post('password');

                // check if the password and repeat password is equal
                if ($password == $this->input->post('rpass')) {
                    $this->db->trans_begin();
                    $systemVal              = $this->api->systemValue();
                    $data['firstname']      = ucwords($this->input->post('firstname'));
                    $data['lastname']       = ucwords($this->input->post('lastname'));
                    $data['middlename']     = ucwords($this->input->post('middlename'));
                    $data['sex']            = $this->input->post('gender');
                    $data['religion']       = $this->input->post('religion');
                    $data['dateofbirth']    = $this->input->post('dob');
                    $data['placeofbirth']   = ucwords($this->input->post('pob'));
                    $data['emailaddress']   = $email;
                    //check if the legacyid exists
                    $stud_id                = $this->student_id($systemVal['laststudentid']);
                    $data['legacyid']       = $stud_id;

                    $this->db->insert('tbl_party', $data);
                    $id = $this->db->insert_id();

                    // update the laststudent id in systemvalues
                    $lid = explode('-', $stud_id);
                    $inc = $lid[1] + 1;
                    $sys['laststudentid'] = $lid[0].'-'.$inc;
                    $this->db->update('tbl_systemvalues', $sys);

                    // get the coursemajor
                    $course_m = $this->input->post('course');

                    // get the latest curriculum for that student
                    $reg['coursemajor']     = $course_m;
                    $reg['academicterm']    = $systemVal['currentacademicterm'];
                    $reg['datecreated']     = date('Y-m-d');
                    $reg['date']            = date('Y-m-d');
                    $reg['student']         = $id;
                    $reg['curriculum']      = $this->get_current_curriculum($course_m, $systemVal['currentacademicterm']);
                    $reg['status']          = 'E';
                    $this->db->insert('tbl_registration', $reg);

                    $acc['partyid']  = $id;
                    $acc['username'] = $this->input->post('username');
                    $acc['password'] = password_hash($password, PASSWORD_BCRYPT);
                    $this->db->insert('tbl_useraccess', $acc);

                    // insert into tbl_student
                    $stud['id']                 = $id;
                    $stud['fathername']         = $this->input->post('father');
                    $stud['fatherproffesion']   = $this->input->post('occupation');
                    $stud['mothername']         = $this->input->post('mother');
                    $stud['motherproffesion']   = $this->input->post('moccupation');
                    $this->db->insert('tbl_student', $stud);

                    // insert tbl_account, useroption
                    $name = $data['firstname'].' '.$data['lastname'];
                    $this->insert_account($id, $name);

                    $menu = array(
                        'optionid'  => STUD_MENU_GRADES,
                        'optionid'  => STUD_MENU_BILL,
                        'userid'    => $id,
                        'userid'    => $id
                    );

                    $this->db->insert('tbl_useroption', $menu);

                    if ($this->db->trans_status() === FALSE) {
                        $this->db->trans_rollback();
                    } else {
                        $this->db->trans_commit();
                    }

                    redirect(base_url('take_photo/'.$id));
                } else {
                    $error = '

                                    Password and Re-peat password did not match

';
                    $this->error_reg($error);
                }
            } else {
                // send a invalid email error
                $error = '

                                Invalid email address

';
                $this->error_reg($error);
            }
        }
    }

    function get_current_curriculum($coursemajor, $systart)
    {
        $cur1       = 0;
        $acamd      = $this->db->query("SELECT * FROM `tbl_academicterm` WHERE systart <= $systart ORDER BY systart DESC,term")->result_array();

        foreach ($acamd as $acams) {
            $c = $this->db->query("SELECT id FROM tbl_curriculum WHERE coursemajor = $coursemajor AND academicterm = {$acams['id']}");

            if ($c->num_rows() > 0) {
                $cur    = $c->row_array();
                $cur1   = $cur['id'];
                break;
            }
        }

        if ($cur1 == 0) {
            $cur    = $this->db->query("SELECT * FROM tbl_curriculum a,tbl_academicterm b WHERE coursemajor = $coursemajor and b.id = a.academicterm ORDER BY b.systart DESC LIMIT 1 ")->row_array();
            $cur1   = $cur['id'];
        }

        return $cur1;
    }

    function student_id($id)
    {
        $value  = $id;
        $this->db->where('legacyid', $value);
        $c      = $this->db->count_all_results('tbl_party');

        while ($c > 0) {
            $value += 1;
            $this->db->where('legacyid', $value);
            $c = $this->db->count_all_results('tbl_party');
        }

        return $value;
    }

    function error_reg($error)
    {
        $d['error']     = $error;
        $d['id']        = 0;
        $d['fname']     = set_value('firstname');
        $d['lname']     = set_value('lastname');
        $d['mname']     = set_value('middlename');
                            // inline if statement
        $d['legacyid']  = ($this->input->post('sid')    ? $this->input->post('sid') : 0);
        $d['course']    = ($this->input->post('course') ? $this->input->post('course') : 0);
        $this->api->userMenu();
        $this->load->view('registrar/newstudent_registration', $d);
        $this->load->view('templates/footer2');
    }

    function take_photo($id = '')
    {
        if ( ! empty($id) ) {
            $this->api->userMenu();
            $data['id'] = $id;
            $this->db->where('id', $id);
            $this->db->select('legacyid');
            $r = $this->db->get('tbl_party')->row_array();
            $data['student_id'] = $r['legacyid'];
            $this->load->view('registrar/take_photo', $data);
            $this->load->view('templates/footer2');
        } else
            show_error('Did you type the url by yourself ?');
    }

    function save_photo()
    {
        $id     = $this->input->post('id');
        $image  = $this->input->post('image');
        $bin    = base64_decode($image);
        $result = file_put_contents('./assets/images/profile/'.$id.'.jpg', $bin);

        if (!$result) {
            die('Could not save image! Check file permissions.');
        } else {
            $d['pic'] = $id.'.jpg';
            $this->db->where('id', $id);
            $this->db->update('tbl_party', $d);
            redirect(base_url('registration'));
        }
    }

    function find_stu()
    {
        $this->db->where('legacyid', $this->input->post('student_search'));
        $this->db->select('id');
        $r = $this->db->get('tbl_party')->row_array();
        redirect('/update_registration/'.$r['id']);
    }

    function update_reg($id)
    {
        $this->load->model('registrar/registration');
        $this->load->helper('form');
        $this->db->where('student', $id);
        $this->db->where('status', 'E');
        $tt = $this->db->count_all_results('tbl_registration');

        if ($tt < 1) {
            $data['id'] = $id;
            $this->db->where('id', $id);
            $this->db->select('firstname,lastname,middlename,placeofbirth,dateofbirth,emailaddress,legacyid,sex');
            $p = $this->db->get('tbl_party')->row_array();
            $data['fname']      = $p['firstname'];
            $data['lname']      = $p['lastname'];
            $data['mname']      = $p['middlename'];
            $data['pob']        = $p['placeofbirth'];
            $data['dob']        = $p['dateofbirth'];
            $data['emailadd']   = $p['emailaddress'];
            $data['error']      = '';
            $data['legacyid']   = $p['legacyid'];
            $data['gender']     = $p['sex'];

            $t              = $this->registration->getLatestCM($id);
            $tt             = $this->db->get_where('tbl_coursemajor', array('id' => $t['coursemajor']))->row_array();
            $data['course'] = $tt['course'];
            $data['major']  = $tt['major'];

            $this->api->userMenu();
            $this->load->view('registrar/update_registration', $data);
        }
        else
            $this->set_error('Cannot open status is pending', 'menu/registrar-update_student');
    }

    function form_update_reg()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('lastname', 'Lastname', 'required');
        $this->form_validation->set_rules('firstname', 'Firstname', 'required');
        $this->form_validation->set_rules('middlename', 'Middlename', 'required');
        $this->form_validation->set_rules('pob', 'Place of Birth', 'required');
        $this->form_validation->set_rules('mailadd', 'Mailing Address', 'required');

        if ($this->form_validation->run() === FALSE) {
            $data['id']         = set_value('id');
            $data['fname']      = set_value('fname');
            $data['lname']      = set_value('lname');
            $data['mname']      = set_value('mname');
            $data['pob']        = set_value('pob');
            $data['dob']        = set_value('dob');
            $data['emailadd']   = set_value('emailadd');
            $data['error']      = '';
            $data['legacyid']   = set_value('legacyid');
            $data['gender']     = set_value('gender');
            $data['course']     = set_value('course');
            $data['major']      = set_value('major');
            $this->api->userMenu();
            $this->load->view('registrar/update_registration', $data);
        } else {
            $this->load->model('registrar/registration');
            $t['firstname']     = ucwords($this->input->post('firstname'));
            $t['lastname']      = ucwords($this->input->post('lastname'));
            $t['middlename']    = ucwords($this->input->post('middlename'));
            $t['placeofbirth']  = ucwords($this->input->post('pob'));
            $t['dateofbirth']   = $this->input->post('dob');
            $t['sex']           = $this->input->post('gender');
            $t['emailaddress']  = $this->input->post('emailadd');
            $id                 = $this->input->post('id');
            $this->db->where('id', $id);
            $this->db->update('tbl_party', $t);
            $p = $this->registration->getLatestCM($id);

            // update the tbl_registration status
            $this->ch_stat_reg($p['id']);
            $this->api->set_session_message('success', 'Successfully Updated');
            redirect('/menu/registrar-update_student');
        }
    }

    function ch_stat_reg($reg_id, $stat = 'E')
    {
        $this->db->where('id', $reg_id);
        $i['status'] = $stat;
        $this->db->update('tbl_registration', $i);
    }

    function find_shift()
    {
        $this->db->where('legacyid', $this->input->post('student_search'));
        $this->db->select('id');
        $r = $this->db->get('tbl_party')->row_array();
        redirect('/shiftee/'.$r['id']);
    }

    function shiftee_form()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('firstname', 'Firstname', 'required');
        $this->form_validation->set_rules('lastname', 'Lastname', 'required');
        $this->form_validation->set_rules('middlename', 'Middlename', 'required');

        if ($this->form_validation->run() == FALSE) {
            $d['course']    = $this->input->post('course');
            $this->load->view('registrar/shiftee', $d);
        } else {

            $t                  = $this->db->get('tbl_coursemajor')->row_array();
            $r['student']       = $this->input->post('id');
            $r['coursemajor']   = $this->input->post('course');
            $systemVal          = $this->api->systemValue();
            $r['academicterm']  = $systemVal['currentacademicterm'];
            $r['curriculum']    = $this->get_current_curriculum($this->input->post('course'), $systemVal['currentacademicterm']);
            $r['createdby']     = $this->session->userdata('uid');
            $r['datecreated']   = date('Y-m-d');
            $this->db->insert('tbl_registration', $r);
            $this->ch_stat_reg($this->db->insert_id());
            redirect('/menu/registrar-shift_student');
        }
    }

    function shiftee($id = '')
    {
        if (!empty($id)) {
            $systemVal = $this->api->systemValue();

            if ($systemVal['phase'] == ENR) {
                $this->load->helper('form');
                $this->db->where('status', 'E');
                $this->db->where('student', $id);
                $rr = $this->db->count_all_results('tbl_registration');

                if ($rr < 1) {
                    $this->load->model('registrar/registration');
                    $this->db->where('id', $id);
                    $this->db->select('firstname,middlename,lastname,legacyid');
                    $p                  = $this->db->get('tbl_party')->row_array();
                    $data['firstname']  = $p['firstname'];
                    $data['lastname']   = $p['lastname'];
                    $data['middlename'] = $p['middlename'];
                    $data['legacyid']   = $p['legacyid'];

                    $r = $this->registration->getLatestCM($id);

                    $this->db->where('id', $r['coursemajor']);
                    $this->db->select('course');
                    $c = $this->db->get('tbl_coursemajor')->row_array();

                    $data['id']     = $id;
                    $data['course'] = $c['course'];
                    $this->api->userMenu();
                    $this->load->view('registrar/shiftee', $data);
                    $this->load->view('templates/footer');
                } else {
                    $this->set_error('Cannot open status is pending','menu/registrar-shift_student');
                }
            } else {
                show_error('Phase term is not enrollment');
            }
        } else {
            show_error('Did you type the url by yourself ?');
        }
    }

    function pending_reg($id)
    {
        $this->load->model(array(
            'registrar/registration',
            'registrar/course')
        );
        $data['id'] = $id;
        $p = $this->registration->getLatestCM($id);
        $this->db->where('id', $p['student']);
        $pp                 = $this->db->get('tbl_party')->row_array();
        $data['fname']      = $pp['firstname'];
        $data['lname']      = $pp['lastname'];
        $data['mname']      = $pp['middlename'];
        $data['gender']     = $pp['sex'];
        $data['legacyid']   = $pp['legacyid'];
        $data['pob']        = $pp['placeofbirth'];
        $data['cid']        = $p['coursemajor'];
        $data['reg']        = $p['id'];
        $this->api->userMenu();
        $this->load->view('registrar/pending_reg', $data);
        $this->load->view('templates/footer');
        // load the students info
    }

    function approve()
    {
        $t['status']        = 'A';
        $t['dateverified']  = date('Y-m-d');
        $this->db->where('id', $this->input->post('reg_id'));
        $this->db->update('tbl_registration', $t);
        $this->api->set_session_message('success', 'Successfully updated');
        redirect('/menu/registrar-pending_registration');
    }

    function disapprove($id)
    {
        $t['status'] = 'D';
        $this->db->where('id', $id);
        $this->db->update('tbl_registration', $t);
        redirect('/menu/registrar-pending_registration');
    }

    function set_error($message, $back)
    {
        $data['back']       = $back;
        $data['message']    = $message;
        $this->api->userMenu();
        $this->load->view('registrar/error_message', $data);
    }

    function print_fields($sid)
    {
        $arr = array('sid' => $sid );
        $this->load->model('registrar/tor');
        $this->load->view('templates/header');
        $this->load->view('templates/header_title1');
        $this->load->view('registrar/print_fields',$arr);
        $this->load->view('templates/footer');
    }

    function set_print_for($sid, $for)
    {
        $this->session->set_userdata('for', $for);
        redirect(base_url('registrar_tor/'.$sid));
    }

    function updateFields()
    {
        $this->load->model('registrar/tor');

        $f11 = $this->input->post('f-1-1');
        $f12 = $this->input->post('f-1-2');
        $this->tor->updateFields($f11, $f12, 1);
        $f21 = $this->input->post('f-2-1');
        $f22 = $this->input->post('f-2-2');
        $this->tor->updateFields($f21, $f22, 2);
        $f31 = $this->input->post('f-3-1');
        $f32 = $this->input->post('f-3-2');
        $this->tor->updateFields($f31, $f32, 3);
        $f41 = $this->input->post('f-4-1');
        $f42 = $this->input->post('f-4-2');
        $this->tor->updateFields($f41, $f42, 4);

        $order_title   = $this->input->post('order_title');
        $order         = $this->input->post('order');
        $series        = $this->input->post('series');
        $remarks       = $this->input->post('remarks');

        $fields = array(
            'order_title' => $order_title,
            'order_no'    => $order,
            'series'      => $series,
            'remarks'     => $remarks
        );

        $this->session->set_userdata('fields', $fields);

        $sid = $this->input->post('sid');

        redirect('/registrar_tor/'.$sid);
    }

    function legacy_matching()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('tbl_subject', 'Subject', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('legacy_matching');
        } else {
            $legacy = $this->input->post('legacy');

            foreach ($legacy as $c) {
                $data['subject_id'] = $this->input->post('tbl_subject');
                $this->db->where('grouping', $c);
                $this->db->update('tbl_enrolment_legacy', $data);
            }

            $this->load->view('legacy_matching');
        }

    }

    function insert_account($partyid, $name)
    {
        $data = array('party' => $partyid, 'accounttype' => 4, 'seq' => 0, 'ccy' => 1, 'description' => $name);
        $this->db->insert('tbl_account', $data);
    }

    function register()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('firstname', 'Firstname', 'required');
        $this->form_validation->set_rules('student_id', 'Student ID', 'required');
        $this->form_validation->set_rules('lastname', 'Lastname', 'required');
        $this->form_validation->set_rules('course', 'Course', 'required');
        $this->form_validation->set_rules('academicterm', 'Academicterm', 'required');

        $courseMajor = $this->db->get('tbl_coursemajor')->result();

        if ($this->form_validation->run() === false) {
            $this->api->userMenu();
            $data['error']          = '';
            $data['coursemajors']   = $courseMajor;
            $this->load->view('registrar/register', $data);
            $this->load->view('templates/footer');
        } else {
            $this->db->where('legacyid', $this->input->post('student_id'));
            $c = $this->db->count_all_results('tbl_party');

            if ($c > 0) {
                $this->api->userMenu();
                $data['error']          = '
Student ID Already Exists
';
                $data['coursemajors']   = $courseMajor;
                $this->load->view('registrar/register', $data);
                $this->load->view('templates/footer');
            } else {
                $this->db->trans_begin();

                $course_m = $this->input->post('course');

                $d['firstname']     = strtoupper($this->input->post('firstname'));
                $d['lastname']      = strtoupper($this->input->post('lastname'));
                $d['middlename']    = strtoupper($this->input->post('middlename'));
                $d['legacyid']      = $this->input->post('student_id');
                $d['partytype']     = 3;
                $this->db->insert('tbl_party', $d);
                $id = $this->db->insert_id();

                $student['id'] = $id;
                $this->db->insert('tbl_student', $student);

                $data['student']        = $id;
                $data['coursemajor']    = $course_m;
                $data['academicterm']   = $this->input->post('academicterm');
                $data['date']           = date('Y-m-d');

                $this->db->where('id', $this->input->post('academicterm'));
                $acam_id = $this->db->get('tbl_academicterm')->row();

                $data['curriculum']     = $this->get_current_curriculum($course_m, $acam_id->systart);
                $data['status']         = 'A';
                $this->db->insert('tbl_registration', $data);

                $menu = array(
                    'optionid'  => STUD_MENU_GRADES,
                    'optionid'  => STUD_MENU_BILL,
                    'userid'    => $id,
                    'userid'    => $id
                );

                $this->db->insert('tbl_useroption', $menu);

                if ($this->db->trans_status() === FALSE) {
                     $this->db->trans_rollback();
                     $this->session->set_flashdata('message', '
Something Went Wrong
');
                } else {
                    $this->db->trans_commit();
                    $this->insert_account($id, $d['firstname'].' '.$d['lastname']);
                    $this->session->set_flashdata('message', '
Successfully Registered
');
                }

                redirect('/register');
            }
        }
    }
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2005, 2006, 2007 Eric Ehlers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file
    \brief Conversion function matrixToOper - Convert matrix to Excel OPER
*/

#ifndef rpxl_conversions_matrixtooper_hpp
#define rpxl_conversions_matrixtooper_hpp

#include <rpxl/conversions/scalartooper.hpp>
#include <vector>

namespace reposit {

    //! Convert type std::vector<std::vector<T> > to an Excel OPER.
    template <class T>
    void matrixToOper(const std::vector<std::vector<T> > &vv, OPER &xMatrix) {

        if (vv.empty() || vv[0].empty()) {
            xMatrix.xltype = xltypeErr;
            xMatrix.val.err = xlerrNA;
            return;
        }

        xMatrix.val.array.rows = vv.size();
        xMatrix.val.array.columns = vv[0].size();
        xMatrix.val.array.lparray = new OPER[xMatrix.val.array.rows * xMatrix.val.array.columns];
        xMatrix.xltype = xltypeMulti | xlbitDLLFree;

        for (unsigned int i=0; i<vv.size(); ++i) {
            std::vector<T> v = vv[i];
            for (unsigned int j=0; j<v.size(); ++j) {
                // FIXME - is the workaround below still required,
                // now that we are no longer using boost::any ?

                // For some instantiations of this template, VC8 refuses to compile the line below:
                //scalarToOper(v[j], xMatrix.val.array.lparray[i * v.size() + j]);
                // A static_cast is necessary to disambiguate native C++ datatypes from boost::any.
                scalarToOper(static_cast<T>(v[j]), xMatrix.val.array.lparray[i * v.size() + j], false);
            }
        }

    }

}

#endif


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

include RR

describe Initializer do
  it "should have an empty configuration" do
    Initializer::configuration.should be_an_instance_of(Configuration)
  end
end

describe Initializer do
  before(:each) do
    Initializer::reset
  end

  it "run should yield the configuration object" do
    Initializer::run do |config|
      config.should be_an_instance_of(Configuration)
    end
  end

  def make_dummy_configuration_change
    Initializer::run do |config|
      config.left = :dummy
    end
  end

  it "configuration should return the current configuration" do
    make_dummy_configuration_change
    Initializer::configuration.should be_an_instance_of(Configuration)
    Initializer::configuration.left.should == :dummy
  end

  it "configuration= should set a new configuration" do
    make_dummy_configuration_change
    Initializer::configuration = :dummy_config
    Initializer::configuration.should == :dummy_config
  end

  it "reset should clear the configuration" do
    make_dummy_configuration_change
    Initializer::reset
    Initializer::configuration.left.should {}
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- OAuth/Spring Security Beans -->
    <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="oauthRequestValidator" class="org.mitre.oauth2.token.ScopeServiceAwareOAuth2RequestValidator" />

    <bean id="clientCredentialsEndpointFilter"
          class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"
            p:authenticationManager-ref="clientAuthenticationManager"
            p:requiresAuthenticationRequestMatcher-ref="clientAuthMatcher" />

    <bean id="clientAssertionEndpointFilter"
          class="org.mitre.openid.connect.assertion.JWTBearerClientAssertionTokenEndpointFilter"
          c:additionalMatcher-ref="clientAuthMatcher"
          p:authenticationManager-ref="clientAssertionAuthenticationManager"  />

    <bean id="clientAssertionAuthenticationProvider"
          class="org.mitre.openid.connect.assertion.JWTBearerAuthenticationProvider" />

    <bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"
          p:realmName="%{oidc.oauth.authn.entrypoint.realm:OIDC}" />

    <bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />

    <bean id="oauth2ExceptionTranslator"
          class="org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator" />

    <!-- Spring Security -->
    <security:authentication-manager id="clientAuthenticationManager">
        <security:authentication-provider user-service-ref="clientUserDetailsService" />
        <security:authentication-provider user-service-ref="uriEncodedClientUserDetailsService" />
    </security:authentication-manager>

    <security:authentication-manager id="clientAssertionAuthenticationManager">
        <security:authentication-provider ref="clientAssertionAuthenticationProvider" />
    </security:authentication-manager>

    <security:global-method-security pre-post-annotations="enabled" proxy-target-class="true"
                                     authentication-manager-ref="authenticationManager">
        <security:expression-handler ref="oauthExpressionHandler" />
    </security:global-method-security>

</beans>


text:
package org.sil.bloom.reader;

import androidx.annotation.Nullable;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;

// This class improves security. Our WebView is, at the level of its basic settings, allowed
// extensive file system access. However, all the requests for anything come through this
// class's shouldInterceptRequest method. We forbid any access to any url that isn't part
// of the folder where we decompressed this book. (Files that are in the app's assets folder,
// like our question sounds, are exempt from this check.)
public class ReaderWebViewClient extends WebViewClient {

    String mAllowedPathPrefix;
    BloomFileReader mFileReader;
    int mLengthOfCanonicalPrefix;
    public ReaderWebViewClient(String bookFolderPath, BloomFileReader fileReader) {
        // Our basic strategy is to extract files to a directory and give bloom-player
        // a file:// url to the root html directory in that folder. So any valid urls
        // will start with file:// plus the path to the folder.
        mAllowedPathPrefix = "file://" + bookFolderPath;
        mFileReader = fileReader;
        // To get a key for fileReader.tryGetFile, we need to take the canonical path
        // of the file requested and strip off the bit indicated by allowedPathPrefix.
        // (plus one more slash).
        mLengthOfCanonicalPrefix = bookFolderPath.length() + 1;
    }

    @Nullable
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();

        WebResourceResponse fontResponse = getHostedFontResponseIfApplicable(url);
        if (fontResponse != null)
            return fontResponse;

        if (urlIsAllowed(url))
            return super.shouldInterceptRequest(view, request);

        return new WebResourceResponse("text", "utf-8", 403,
                "request for file not part of book",
                new HashMap<String, String>(), new ByteArrayInputStream("".getBytes()));
    }

    // Starting in bloom-player 2.1, we have font-face rules which tell the host to serve up
    // the appropriate Andika or Andika New Basic font file. An example is:
    //             @font-face {
    //                font-family: "Andika New Basic";
    //                font-weight: bold;
    //                font-style: normal;
    //                src:
    //                    local("Andika New Basic Bold"),
    //                    local("Andika Bold"),
    //    ===>            url("./host/fonts/Andika New Basic Bold"),
    //                    url("https://bloomlibrary.org/fonts/Andika%20New%20Basic/AndikaNewBasic-B.woff")
    //                ;
    //            }
    // So if we have a request for /host/fonts/, here is where we intercept and handle it.
    private WebResourceResponse getHostedFontResponseIfApplicable(String url) {
        try {
            if (!url.contains("/host/fonts/"))
                return null;

            String fontNameRequested = IOUtilities.getFilename(url);
            fontNameRequested = URLDecoder.decode(fontNameRequested, "UTF-8");
            String fontFileName = null;
            switch (fontNameRequested) {
                case "Andika New Basic":
                case "Andika":
                    fontFileName = "Andika-Regular.ttf";
                    break;
                case "Andika New Basic Bold":
                case "Andika Bold":
                    fontFileName = "Andika-Bold.ttf";
                    break;
                case "Andika New Basic Italic":
                case "Andika Italic":
                    fontFileName = "Andika-Italic.ttf";
                    break;
                case "Andika New Basic Bold Italic":
                case "Andika Bold Italic":
                    fontFileName = "Andika-BoldItalic.ttf";
                    break;
            }

            if (fontFileName != null) {
                return new WebResourceResponse("font/ttf", "utf-8", 200,
                        "OK", new HashMap<>(),
                        BloomReaderApplication.getBloomApplicationContext().getAssets().open("fonts/Andika/" + fontFileName));
            }
        } catch (Exception e) {
            // Just silently fail on any exception; definitely not a good reason to crash
            return null;
        }
        return null;
    }

    // We use the canonical path of the file to prevent hacks involving a valid directory
    // prefix followed by multiple "../" to get back to one that is not permitted.
    private boolean urlIsAllowed(String url) {
        if (!url.startsWith("file://"))
            return false;
        String path = null;
        try {
            path = URLDecoder.decode(url.substring("file://".length()), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); // absolutely stupid compiler requirement, of course UTF-8 is supported!
        }
        try {
            String canonicalPath = new File(path).getCanonicalPath();
            String canonicalUrl = "file://" + canonicalPath;
            if (canonicalUrl.startsWith(mAllowedPathPrefix)) {
                // Make sure the file we want has been unzipped.
                String keyInZip = canonicalPath.substring(mLengthOfCanonicalPrefix);
                int index = keyInZip.indexOf("?");
                if (index >= 0) {
                    keyInZip = keyInZip.substring(0,index);
                }
                mFileReader.tryGetFile(keyInZip);
                return true;
            }
            // I think this only happens before Android 21 (Lollipop); in later androids,
            // the app's own assets are automatically OK.
            return canonicalUrl.startsWith("file:///android_asset/bloom-player/");
        } catch (IOException e) {
            return false;
        }
    }
}


text:
class Email < ActiveRecord::Base
  acts_as_cute_admin :display_name => :email, :index_columns => [
    :email,
    :employee,
    {:employee => :company}
  ]
  belongs_to :employee
end


text:
angular.module("umbraco").controller("FormEditor.Editor.FieldController", ["$scope", "$filter", "formEditorPropertyEditorFieldValidator", "formEditorPropertyEditorResource", "dialogService", "contentResource",
  function ($scope, $filter, formEditorPropertyEditorFieldValidator, formEditorPropertyEditorResource, dialogService, contentResource) {
    $scope.originalFieldName = $scope.dialogData.field.name;
    $scope.addFieldValue = function () {
      $scope.dialogData.field.fieldValues.push({});
    };
    $scope.removeFieldValue = function (index) {
      $scope.dialogData.field.fieldValues.splice(index, 1);
    };
    $scope.setSelectedFieldValue = function (index) {
      if (!$scope.dialogData.field.multiSelect) {
        _.each($scope.dialogData.field.fieldValues, function (fieldValue) {
          if ($scope.dialogData.field.fieldValues.indexOf(fieldValue) != index) {
            fieldValue.selected = false;
          }
        });
      }
    };
    $scope.validateFieldName = function ($event) {
      return formEditorPropertyEditorFieldValidator.validateFieldName($scope.dialogData.field);
    };
    $scope.pickImage = function () {
      dialogService.mediaPicker({
        multiPicker: false,
        callback: function (data) {
          $scope.dialogData.field.mediaId = data.id;
          $scope.loadMediaUrl();
        }
      });
    }
    $scope.pickPage = function () {
      dialogService.contentPicker({
        multiPicker: false,
        callback: function (data) {
          $scope.dialogData.field.pageId = data.id;
          $scope.dialogData.page = {
            name: data.name,
            id: data.id,
            cssClass: "icon " + data.icon
          };
        }
      });
    }
    $scope.removePage = function () {
      $scope.dialogData.field.pageId = 0;
      $scope.dialogData.page = null;
    }
    $scope.loadMediaUrl = function () {
      formEditorPropertyEditorResource.getMediaUrl($scope.dialogData.field.mediaId).then(function (data) {
        //console.log("Got media URL", $scope.dialogData.field.mediaId, data);
        $scope.dialogData.field.mediaUrl = data.url;
      });
    }
    $scope.loadPage = function() {
      contentResource.getById($scope.dialogData.field.pageId).then(
        // success
        function (data) {
          $scope.dialogData.page = {
            name: data.name,
            id: data.id,
            cssClass: "icon " + data.icon
          };
        },
        // error
        function (data) {
          // ignore for now
        }
      );
    }
    $scope.fieldNameChanged = function() {
      if ($scope.dialogData.warnWhenRenaming) {
        $scope.showRenameWarning = $scope.dialogData.field.name != $scope.originalFieldName;
      }
    }
    $scope.allValueFields = function () {
      return $filter("filter")(formEditorPropertyEditorFieldValidator.fields, { isValueField: true });
    }
    if ($scope.dialogData.field.mediaId) {
      $scope.loadMediaUrl();
    }
    if ($scope.dialogData.field.pageId) {
      $scope.loadPage();
    }
    $scope.sortableOptionsFieldValues = {
      axis: "y",
      cursor: "move",
      update: function (ev, ui) {
      },
      stop: function (ev, ui) {
      }
    };
  }
]);


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.application;

import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Tags;
import com.yahoo.text.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

import javax.xml.transform.TransformerException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * Handles overrides in a XML document according to the rules defined for multi-environment application packages.
 *
 * Rules:
 *
 * 1. A directive specifying both environment and region will override a more generic directive specifying only one of them
 * 2. Directives are inherited in child elements
 * 3. When multiple XML elements with the same name is specified (i.e. when specifying search or docproc chains),
 *    the id attribute of the element is used together with the element name when applying directives
 *
 * @author Ulf Lilleengen
 */
class OverrideProcessor implements PreProcessor {

    private static final Logger log = Logger.getLogger(OverrideProcessor.class.getName());

    private final InstanceName instance;
    private final Environment environment;
    private final RegionName region;
    private final Tags tags;

    private static final String ID_ATTRIBUTE = "id";
    private static final String INSTANCE_ATTRIBUTE = "instance";
    private static final String ENVIRONMENT_ATTRIBUTE = "environment";
    private static final String REGION_ATTRIBUTE = "region";
    private static final String TAGS_ATTRIBUTE = "tags";

    public OverrideProcessor(InstanceName instance, Environment environment, RegionName region, Tags tags) {
        this.instance = instance;
        this.environment = environment;
        this.region = region;
        this.tags = tags;
    }

    public Document process(Document input) throws TransformerException {
        log.log(Level.FINE, () -> "Preprocessing overrides with " + environment + "." + region);
        Document ret = Xml.copyDocument(input);
        Element root = ret.getDocumentElement();
        applyOverrides(root, Context.empty());
        return ret;
    }

    private void applyOverrides(Element parent, Context context) {
        context = getParentContext(parent, context);

        Map<String, List<Element>> elementsByTagName = elementsByTagNameAndId(XML.getChildren(parent));

        retainOverriddenElements(elementsByTagName);

        // For each tag name, prune overrides
        for (Map.Entry<String, List<Element>> entry : elementsByTagName.entrySet()) {
            pruneOverrides(parent, entry.getValue(), context);
        }

        // Repeat for remaining children;
        for (Element child : XML.getChildren(parent)) {
            applyOverrides(child, context);
            // Remove attributes
            child.removeAttributeNS(XmlPreProcessor.deployNamespaceUri, INSTANCE_ATTRIBUTE);
            child.removeAttributeNS(XmlPreProcessor.deployNamespaceUri, ENVIRONMENT_ATTRIBUTE);
            child.removeAttributeNS(XmlPreProcessor.deployNamespaceUri, REGION_ATTRIBUTE);
            child.removeAttributeNS(XmlPreProcessor.deployNamespaceUri, TAGS_ATTRIBUTE);
        }
    }

    private Context getParentContext(Element parent, Context context) {
        Set<InstanceName> instances = context.instances;
        Set<Environment> environments = context.environments;
        Set<RegionName> regions = context.regions;
        Tags tags = context.tags;
        if (instances.isEmpty())
            instances = getInstances(parent);
        if (environments.isEmpty())
            environments = getEnvironments(parent);
        if (regions.isEmpty())
            regions = getRegions(parent);
        if (tags.isEmpty())
            tags = getTags(parent);
        return Context.create(instances, environments, regions, tags);
    }

    /**
     * Prune overrides from parent according to deploy override rules.
     *
     * @param parent parent {@link Element} above children.
     * @param children children where one {@link Element} will remain as the overriding element
     * @param context current context with instance, environment and region.
     */
    private void pruneOverrides(Element parent, List<Element> children, Context context) {
        checkConsistentInheritance(children, context);
        pruneNonMatching(parent, children);
        retainMostSpecific(parent, children, context);
    }

    private void checkConsistentInheritance(List<Element> children, Context context) {
        for (Element child : children) {
            Set<InstanceName> instances = getInstances(child);
            if ( ! instances.isEmpty() &&  ! context.instances.isEmpty() && ! context.instances.containsAll(instances)) {
                throw new IllegalArgumentException("Instances in child (" + instances +
                                                   ") are not a subset of those of the parent (" + context.instances + ") at " + child);
            }

            Set<Environment> environments = getEnvironments(child);
            if ( ! environments.isEmpty() &&  ! context.environments.isEmpty() && ! context.environments.containsAll(environments)) {
                throw new IllegalArgumentException("Environments in child (" + environments +
                                                   ") are not a subset of those of the parent (" + context.environments + ") at " + child);
            }

            Set<RegionName> regions = getRegions(child);
            if ( ! regions.isEmpty() && ! context.regions.isEmpty() && ! context.regions.containsAll(regions)) {
                throw new IllegalArgumentException("Regions in child (" + regions +
                                                   ") are not a subset of those of the parent (" + context.regions + ") at " + child);
            }

            Tags tags = getTags(child);
            if ( ! tags.isEmpty() &&  ! context.tags.isEmpty() && ! context.tags.containsAll(tags)) {
                throw new IllegalArgumentException("Tags in child (" + environments +
                                                   ") are not a subset of those of the parent (" + context.tags + ") at " + child);
            }
        }
    }

    /** Prune elements that are not matching our environment and region. */
    private void pruneNonMatching(Element parent, List<Element> children) {
        Iterator<Element> elemIt = children.iterator();
        while (elemIt.hasNext()) {
            Element child = elemIt.next();
            if ( ! matches(getInstances(child), getEnvironments(child), getRegions(child), getTags(child))) {
                parent.removeChild(child);
                elemIt.remove();
            }
        }
    }

    private boolean matches(Set<InstanceName> elementInstances,
                            Set<Environment> elementEnvironments,
                            Set<RegionName> elementRegions,
                            Tags elementTags) {
        if ( ! elementInstances.isEmpty()) { // match instance
            if ( ! elementInstances.contains(instance)) return false;
        }

        if ( ! elementEnvironments.isEmpty()) { // match environment
            if ( ! elementEnvironments.contains(environment)) return false;
        }

        if ( ! elementRegions.isEmpty()) { // match region
            // match region in multi-region environments only
            if ( environment.isMultiRegion()  && ! elementRegions.contains(region)) return false;

            // explicit region implies multi-region environment
            if ( ! environment.isMultiRegion() && elementEnvironments.isEmpty() ) return false;
        }

        if ( ! elementTags.isEmpty()) { // match tags
            if ( ! elementTags.intersects(tags)) return false;
        }

        return true;
    }

    /** Find the most specific element and remove all others. */
    private void retainMostSpecific(Element parent, List<Element> children, Context context) {
        // Keep track of elements with highest number of matches (might be more than one element with same tag, need a list)
        List<Element> bestMatches = new ArrayList<>();
        int bestMatch = 0;
        for (Element child : children) {
            bestMatch = updateBestMatches(bestMatches, child, bestMatch, context);
        }
        if (bestMatch > 0) { // there was a region/environment specific override
            doElementSpecificProcessingOnOverride(bestMatches);
            for (Element child : children) {
                if ( ! bestMatches.contains(child)) {
                    parent.removeChild(child);
                }
            }
        }
    }

    private int updateBestMatches(List<Element> bestMatches, Element child, int bestMatch, Context context) {
        int overrideCount = getNumberOfOverrides(child, context);
        if (overrideCount >= bestMatch) {
            if (overrideCount > bestMatch)
                bestMatches.clear();

            bestMatches.add(child);
            return overrideCount;
        } else {
            return bestMatch;
        }
    }

    private int getNumberOfOverrides(Element child, Context context) {
        int currentMatch = 0;
        Set<InstanceName> elementInstances = hasInstance(child) ? getInstances(child) : context.instances;
        Set<Environment> elementEnvironments = hasEnvironment(child) ? getEnvironments(child) : context.environments;
        Set<RegionName> elementRegions = hasRegion(child) ? getRegions(child) : context.regions;
        Tags elementTags = hasTag(child) ? getTags(child) : context.tags;
        if ( ! elementInstances.isEmpty() && elementInstances.contains(instance))
            currentMatch++;
        if ( ! elementEnvironments.isEmpty() && elementEnvironments.contains(environment))
            currentMatch++;
        if ( ! elementRegions.isEmpty() && elementRegions.contains(region))
            currentMatch++;
        if ( elementTags.intersects(tags))
            currentMatch++;
        return currentMatch;
    }

    /** Called on each element which is selected by matching some override condition */
    private void doElementSpecificProcessingOnOverride(List<Element> elements) {
        // if node capacity is specified explicitly for some combination we should require that capacity
        elements.forEach(element -> {
            if (element.getTagName().equals("nodes"))
                if (!hasChildWithTagName(element, "node")) // specifies capacity, not a list of nodes
                    element.setAttribute("required", "true");
        });
    }

    private static boolean hasChildWithTagName(Element element, String childName) {
        for (var child : XML.getChildren(element)) {
            if (child.getTagName().equals(childName))
                return true;
        }

        return false;
    }

    /** Retains all elements where at least one element is overridden. Removes non-overridden elements from map. */
    private void retainOverriddenElements(Map<String, List<Element>> elementsByTagName) {
        Iterator<Map.Entry<String, List<Element>>> it = elementsByTagName.entrySet().iterator();
        while (it.hasNext()) {
            List<Element> elements = it.next().getValue();
            boolean hasOverrides = false;
            for (Element element : elements) {
                if (hasInstance(element) || hasEnvironment(element) || hasRegion(element) || hasTag(element)) {
                    hasOverrides = true;
                }
            }
            if (!hasOverrides) {
                it.remove();
            }
        }
    }

    private boolean hasInstance(Element element) {
        return element.hasAttributeNS(XmlPreProcessor.deployNamespaceUri, INSTANCE_ATTRIBUTE);
    }

    private boolean hasRegion(Element element) {
        return element.hasAttributeNS(XmlPreProcessor.deployNamespaceUri, REGION_ATTRIBUTE);
    }

    private boolean hasEnvironment(Element element) {
        return element.hasAttributeNS(XmlPreProcessor.deployNamespaceUri, ENVIRONMENT_ATTRIBUTE);
    }

    private boolean hasTag(Element element) {
        return element.hasAttributeNS(XmlPreProcessor.deployNamespaceUri, TAGS_ATTRIBUTE);
    }

    private Set<InstanceName> getInstances(Element element) {
        String instance = element.getAttributeNS(XmlPreProcessor.deployNamespaceUri, INSTANCE_ATTRIBUTE);
        if (instance == null || instance.isEmpty()) return  Set.of();
        return Arrays.stream(instance.split(" ")).map(InstanceName::from).collect(Collectors.toSet());
    }

    private Set<Environment> getEnvironments(Element element) {
        String env = element.getAttributeNS(XmlPreProcessor.deployNamespaceUri, ENVIRONMENT_ATTRIBUTE);
        if (env == null || env.isEmpty()) return Set.of();
        return Arrays.stream(env.split(" ")).map(Environment::from).collect(Collectors.toSet());
    }

    private Set<RegionName> getRegions(Element element) {
        String reg = element.getAttributeNS(XmlPreProcessor.deployNamespaceUri, REGION_ATTRIBUTE);
        if (reg == null || reg.isEmpty()) return Set.of();
        return Arrays.stream(reg.split(" ")).map(RegionName::from).collect(Collectors.toSet());
    }

    private Tags getTags(Element element) {
        String env = element.getAttributeNS(XmlPreProcessor.deployNamespaceUri, TAGS_ATTRIBUTE);
        if (env == null || env.isEmpty()) return Tags.empty();
        return Tags.fromString(env);
    }

    private Map<String, List<Element>> elementsByTagNameAndId(List<Element> children) {
        Map<String, List<Element>> elementsByTagName = new LinkedHashMap<>();
        // Index by tag name
        for (Element child : children) {
            String key = child.getTagName();
            if (child.hasAttribute(ID_ATTRIBUTE)) {
                key += child.getAttribute(ID_ATTRIBUTE);
            }
            if ( ! elementsByTagName.containsKey(key)) {
                elementsByTagName.put(key, new ArrayList<>());
            }
            elementsByTagName.get(key).add(child);
        }
        return elementsByTagName;
    }

    // For debugging
    private static String getPrintableElement(Element element) {
        StringBuilder sb = new StringBuilder(element.getTagName());
        final NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            sb.append(" ").append(attributes.item(i).getNodeName());
        }
        return sb.toString();
    }

    // For debugging
    private static String getPrintableElementRecursive(Element element) {
        StringBuilder sb = new StringBuilder();
        sb.append(element.getTagName());
        final NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            sb.append(" ")
              .append(attributes.item(i).getNodeName())
              .append("=")
              .append(attributes.item(i).getNodeValue());
        }
        final List<Element> children = XML.getChildren(element);
        if (children.size() > 0) {
            sb.append("\n");
            for (Element e : children)
                sb.append("\t").append(getPrintableElementRecursive(e));
        }
        return sb.toString();
    }

    /**
     * Represents environment and region in a given context.
     */
    private static final class Context {

        final Set<InstanceName> instances;
        final Set<Environment> environments;
        final Set<RegionName> regions;
        final Tags tags;

        private Context(Set<InstanceName> instances,
                        Set<Environment> environments,
                        Set<RegionName> regions,
                        Tags tags) {
            this.instances = Set.copyOf(instances);
            this.environments = Set.copyOf(environments);
            this.regions = Set.copyOf(regions);
            this.tags = tags;
        }

        static Context empty() {
            return new Context(Set.of(), Set.of(), Set.of(), Tags.empty());
        }

        public static Context create(Set<InstanceName> instances,
                                     Set<Environment> environments,
                                     Set<RegionName> regions,
                                     Tags tags) {
            return new Context(instances, environments, regions, tags);
        }

    }

}