text:
import { Attribute } from '../attributes/attribute';
import Modifier from '../modifiers/modifier';
import IHasAttributes from '../attributes/has-attributes.i';
import AttributeCollection from '../attributes/attribute-collection';
import IHasModifiers from '../modifiers/has-modifiers.i';
import ModifierCollection from '../modifiers/modifier-collection';
import XethyaObject from '../../base/object';
import assert from '../../utils/assert/assert';
import SkillThrow from '../../dice/throws/skill-throw';
import { SkillThrowResult } from '../../dice/throws/skill-throw-result';
import { DiceThrowTypes } from '../../dice/throws/dice-throw';
import { ChanceThrow } from '../../dice/throws/chance-throw';

export type SkillSettings = {
  id: string;
  owner?: XethyaObject;
  attributes?: Attribute[],
  modifiers?: Modifier[],
  primaryAttribute?: string | Attribute,
}

export class Skill extends XethyaObject implements IHasAttributes, IHasModifiers {
  attributes: AttributeCollection;
  modifiers: ModifierCollection;

  protected _id: string;
  protected _primaryAttribute?: Attribute;

  constructor({
    id,
    owner = undefined,
    attributes = [],
    modifiers = [],
    primaryAttribute = ''
  }: SkillSettings) {
    super();

    this._id = id;
    this.attributes = AttributeCollection.fromArray(attributes);
    this.modifiers = ModifierCollection.fromArray(modifiers);

    if (this.attributes.count > 0) {
      this._setPrimaryAttribute(primaryAttribute);
    }
  }

  private _setPrimaryAttribute(primaryAttribute: string | Attribute) {
    const isAttributeID = typeof primaryAttribute === 'string';
    const attributeID: string = isAttributeID ? primaryAttribute as string : (primaryAttribute as Attribute).id;

    assert(this.attributes.contains(attributeID),
      'Skill#constructor: primaryAttribute must be defined in attributes array');

    this._primaryAttribute = this.attributes.get(attributeID) as Attribute;
  }

  get primaryAttribute(): Attribute | undefined {
    return this._primaryAttribute;
  }

  set primaryAttribute(newPrimaryAttribute: Attribute | undefined) {
    this._primaryAttribute = newPrimaryAttribute;
  }

  get id() {
    return this._id;
  }

  get value() {
    return (this._primaryAttribute as Attribute).value;
  }

  use(): SkillThrowResult {
    this.emit('before:use', this);

    const skillThrow = new SkillThrow(this);
    const result = skillThrow.roll();

    if (result.throwType === DiceThrowTypes.FAILURE) {
      result.failureRoll = new ChanceThrow().roll();
    }

    this.emit('use', this);

    return result;
  }
}


text:
module FarmEvents
  class Create < Mutations::Command
    include FarmEvents::ExecutableHelpers
    executable_fields :optional
    BACKWARDS_END_TIME = "This event starts before it ends. Did you flip the "\
                         "start and end times?"

    BAD_START_TIME     = "FarmEvent start time needs to be in the future, not" +
                         " the past."
    required do
      model   :device, class: Device
      integer :repeat, min: 1
      string  :time_unit, in: FarmEvent::UNITS_OF_TIME
    end

    optional do
      time :start_time, default: Time.current
      time :end_time
    end

    def validate
      validate_start_time
      validate_end_time
      validate_executable
    end

    def execute
      p = inputs.merge(executable: executable)
      # Needs to be set this way for cleanup operations:
      p[:end_time] = (p[:start_time] + 1.minute) if is_one_time_event
      FarmEvent.create!(p)
    end

    def validate_start_time
      add_error :start_time, :expired, BAD_START_TIME if (start_time < Time.now)
    end

    def validate_end_time
      no_go = end_time && (start_time > end_time) && !is_one_time_event
      add_error :end_time, :backwards, BACKWARDS_END_TIME if no_go
    end

    def is_one_time_event
      time_unit == FarmEvent::NEVER
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
date_default_timezone_set('Asia/Taipei');
session_start(); //we need to call PHP's session object to access it through CI

class Admin extends CI_Controller {

  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   *     http://example.com/index.php/welcome
   *  - or -
   *     http://example.com/index.php/welcome/index
   *  - or -
   * Since this controller is set as the default controller in
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore will
   * map to /index.php/welcome/<method_name>
   * @see http://codeigniter.com/user_guide/general/urls.html
   */

/*
  public function index()
  {
    $this->template->set_layout('dashboard');
    $this->template->build('admin/dashboard');
  }
*/

  public function index()
  {
    $this->load->helper(array('form'));
    $this->template->set_layout('admin');
    $this->template->build('admin/index');
  }

  public function dashboard()
  {
    if($this->session->userdata('logged_in'))
    {
      $this->template->set_layout('dashboard');
      $this->template->build('admin/dashboard');
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function post_add()
  {
    if($this->session->userdata('logged_in'))
    {
      $this->template->set_layout('dashboard');
      $this->template->build('admin/post_add');
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function post_add_db()
  {
    if($this->session->userdata('logged_in'))
    {
      $data = $this->input->post();
      $data['post_coverphoto_url'] = $data['post_coverphoto_url'][0];
      $data['post_created_time'] = date('Y-m-d H:i:s');
      $this->load->model('st_posts_model');
      $status = $this->st_posts_model->insert($data);

      if($status){
        $path = base_url() ."admin/post_manage";
        //header('Refresh: 1; URL='.$path);
        echo "\n<script type=\"text/javascript\">alert('文章送出成功!');</script>\n";
        echo "\n<script type=\"text/javascript\">window.location.replace('$path');</script>\n";
      } else {
        echo "something error please contact poku1010@gmail.com";
      }
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }

  }

  public function post_edit($post_id)
  {
    if($this->session->userdata('logged_in'))
    {
      $this->load->model('st_posts_model');
      $data['post'] = $this->st_posts_model->as_array()->get($post_id);
      $this->template->set_layout('dashboard');
      $this->template->build('admin/post_edit', $data);
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function post_edit_db()
  {
    if($this->session->userdata('logged_in'))
    {
      $data = $this->input->post();
      if($data['post_coverphoto_url'][0]!='n'){
        $data['post_coverphoto_url'] = $data['post_coverphoto_url'][0];
      }
      else {
        unset($data['post_coverphoto_url']);
      }
      $this->load->model('st_posts_model');
      $status = $this->st_posts_model->update($data['post_id'], $data);

      if($status){
        //echo "文章修改成功! 1秒後跳至文章管理頁";
        $path = base_url() ."admin/post_manage";
        //header('Refresh: 1; URL='.$path);
        echo "\n<script type=\"text/javascript\">alert('文章修改成功!');</script>\n";
        echo "\n<script type=\"text/javascript\">window.location.replace('$path');</script>\n";
      } else {
        echo "something error please contact poku1010@gmail.com";
      }
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function post_manage()
  {
    if($this->session->userdata('logged_in'))
    {
      $this->load->model('st_posts_model');
      $data['posts'] = $this->st_posts_model->as_array()->get_all();
      $this->template->set_layout('dashboard');
      $this->template->build('admin/post_manage', $data);
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function post_delete($delete_id)
  {
    if($this->session->userdata('logged_in'))
    {
      $this->load->model('st_posts_model');
      try{
          $this->st_posts_model->remove($delete_id);
      }catch (Exception $e){
          echo 'Something went wrong...';
      }
      redirect( base_url().'admin/post_manage');
    }
    else
    {
      //If no session, redirect to login page
      redirect('admin', 'refresh');
    }
  }

  public function example()
  {
      $this->template->set_layout('admin');
      $this->template->build('admin/example');
  }

  function logout()
  {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('admin', 'refresh');
  }

}

/* End of file admin.php */
/* Location: ./application/controllers/admin.php */


text:
namespace Pythia8 {

//==========================================================================

// Info class.
// This class contains a mixed bag of information on the event generation
// activity, especially on the current subprocess properties.

//--------------------------------------------------------------------------

// Constants: could be changed here if desired, but normally should not.
// These are of technical nature, as described for each.

// Number of times the same error message will be repeated at most.
const int Info::TIMESTOPRINT = 1;

// LHA convention with cross section in pb may require conversion from mb.
const double Info::CONVERTMB2PB = 1e9;

//--------------------------------------------------------------------------

// List (almost) all information currently set.

void Info::list() const {

  // Header and beam info.
  cout << "\n --------  PYTHIA Info Listing  ------------------------"
       << "---------------- \n \n"
       << scientific << setprecision(3)
       << " Beam A: id = " << setw(6) << idASave << ", pz = " << setw(10)
       << pzASave << ", e = " << setw(10) << eASave << ", m = " << setw(10)
       << mASave << ".\n"
       << " Beam B: id = " << setw(6) << idBSave << ", pz = " << setw(10)
       << pzBSave << ", e = " << setw(10) << eBSave << ", m = " << setw(10)
       << mBSave << ".\n\n";

  // Done if no subprocess has been defined.
  if (codeSave == 0 && nFinalSave == 0) {
    cout << " No process has been set; something must have gone wrong! \n"
         << "\n --------  End PYTHIA Info Listing  --------------------"
         << "----------------" << endl;
    return;
  }

  // Colliding parton info.
  if (isRes) {
    cout << " In 1: id = " << setw(4) << id1pdfSave[0] << ", x = "
         << setw(10) << x1pdfSave[0] << ", pdf = " << setw(10) << pdf1Save[0]
         << " at Q2 = " << setw(10) << Q2FacSave[0] << ".\n"
         << " In 2: id = " << setw(4) << id2pdfSave[0] << ", x = "
         << setw(10) << x2pdfSave[0] << ", pdf = " << setw(10) << pdf2Save[0]
         << " at same Q2.\n";
    bool matchIdX = true;
    if (id1pdfSave[0] != id1Save[0] || id2pdfSave[0] != id2Save[0])
      matchIdX = false;
    if (abs(x1pdfSave[0] - x1Save[0]) > 1e-4 * x1Save[0]) matchIdX = false;
    if (abs(x2pdfSave[0] - x2Save[0]) > 1e-4 * x2Save[0]) matchIdX = false;
    if (!matchIdX) cout << " Warning: above flavour/x info does not match"
         << " incoming partons in event!\n";
    cout << "\n";
  }

  // Process name and code.
  cout << ((isRes && !hasSubSave[0]) ? " Subprocess " : " Process ")
       << nameSave << " with code " << codeSave << " is 2 -> "
       << nFinalSave << ".\n";

  // Subprocess name and code for nondiffractive processes.
  if (hasSubSave[0])
    cout << " Subprocess " << nameSubSave[0] << " with code " << codeSubSave[0]
         << " is 2 -> " << nFinalSubSave[0] << ".\n";

  // Process-type-specific kinematics information.
  if ( isRes && nFinalSave == 1)
    cout << " It has sHat = " << setw(10) << sH[0] << ".\n";
  else if ( isRes && nFinalSave == 2)
    cout << " It has sHat = " << setw(10) << sH[0] << ",    tHat = "
         << setw(10) << tH[0] << ",    uHat = " << setw(10) << uH[0] << ",\n"
         << "       pTHat = " << setw(10) << pTH[0] << ",   m3Hat = "
         << setw(10) << m3H[0] << ",   m4Hat = " << setw(10) << m4H[0] << ",\n"
         << "    thetaHat = " << setw(10) << thetaH[0] << ",  phiHat = "
         << setw(10) << phiH[0] << ".\n";
    else if ( nFinalSave == 2)
    cout << " It has s = " << setw(10) << sH[0] << ",    t = " << setw(10)
         << tH[0] << ",    u = " << setw(10) << uH[0] << ",\n"
         << "       pT = " << setw(10) << pTH[0] << ",   m3 = " << setw(10)
         << m3H[0] << ",   m4 = " << setw(10) << m4H[0] << ",\n"
         << "    theta = " << setw(10) << thetaH[0] << ",  phi = " << setw(10)
         << phiH[0] << ".\n";
  else if ( isRes && nFinalSave == 3)
    cout << " It has sHat = " << setw(10) << sH[0] << ", <pTHat> = "
         << setw(10) << pTH[0] << ".\n";
  else if ( nFinalSave == 3)
    cout << " It has s = " << setw(10) << sH[0] << ",  t_A = " << setw(10)
         << tH[0] << ",  t_B = " << setw(10) << uH[0] << ",\n"
         << "     <pT> = " << setw(10) << pTH[0] << ".\n";

  // Couplings.
  if (isRes) cout << "     alphaEM = " << setw(10) << alphaEMSave[0]
    << ",  alphaS = " << setw(10) << alphaSSave[0] << "    at Q2 = "
    << setw(10) << Q2RenSave[0] << ".\n";

  // Diffractive subsystems.
  for (int iDS = 1; iDS < 4; ++iDS) if (id1Save[iDS] != 0) {
    if (iDS == 1) cout << "\n Diffractive system on side A: \n";
    if (iDS == 2) cout << "\n Diffractive system on side B: \n";
    if (iDS == 3) cout << "\n Central diffractive system: \n";
    cout << " In 1: id = " << setw(4) << id1pdfSave[iDS] << ", x = "
         << setw(10) << x1pdfSave[iDS] << ", pdf = " << setw(10)
         << pdf1Save[iDS] << " at Q2 = " << setw(10) << Q2FacSave[iDS]
         << ".\n" << " In 2: id = " << setw(4) << id2pdfSave[iDS]
         << ", x = " << setw(10) << x2pdfSave[iDS] << ", pdf = "
         << setw(10) << pdf2Save[iDS] << " at same Q2.\n";
    cout << " Subprocess " << nameSubSave[iDS] << " with code "
         << codeSubSave[iDS] << " is 2 -> " << nFinalSubSave[iDS] << ".\n";
    if (nFinalSubSave[iDS] == 1) {
      cout << " It has sHat = " << setw(10) << sH[iDS] << ".\n";
    } else if (nFinalSubSave[iDS] == 2) {
      cout << " It has sHat = " << setw(10) << sH[iDS] << ",    tHat = "
           << setw(10) << tH[iDS] << ",    uHat = " << setw(10) << uH[iDS]
           << ",\n" << "       pTHat = " << setw(10) << pTH[iDS]
           << ",   m3Hat = " << setw(10) << m3H[iDS] << ",   m4Hat = "
           << setw(10) << m4H[iDS] << ",\n" << "    thetaHat = " << setw(10)
           << thetaH[iDS] << ",  phiHat = "  << setw(10) << phiH[iDS] << ".\n";
    }
    cout << "     alphaEM = " << setw(10) << alphaEMSave[iDS]
         << ",  alphaS = " << setw(10) << alphaSSave[iDS] << "    at Q2 = "
         << setw(10) << Q2RenSave[iDS] << ".\n";
  }

  // Impact parameter.
  if (bIsSet) cout << "\n Impact parameter b = " << setw(10) << bMPISave
    << " gives enhancement factor = " << setw(10) << enhanceMPISave
    << ".\n";

  // Multiparton interactions and shower evolution.
  if (evolIsSet) cout << " Max pT scale for MPI = " << setw(10) << pTmaxMPISave
    << ", ISR = " << setw(10) << pTmaxISRSave << ", FSR = " << setw(10)
    << pTmaxISRSave << ".\n Number of MPI = " << setw(5) << nMPISave
    << ", ISR = " << setw(5) << nISRSave << ", FSRproc = " << setw(5)
    << nFSRinProcSave << ", FSRreson = " << setw(5) << nFSRinResSave
    << ".\n";

  // Listing finished.
  cout << "\n --------  End PYTHIA Info Listing  --------------------"
       << "----------------" << endl;

}

//--------------------------------------------------------------------------

// Event weights and accumulated weight.

double Info::weight(int iWeight) const {
  double wt = (iWeight <= 0 || iWeight >= int(weightSave.size()))
    ? weightSave[0] : weightSave[iWeight];
  return (abs(lhaStrategySave) == 4) ? CONVERTMB2PB * wt : wt;
}

double Info::weightSum() const {
  return (abs(lhaStrategySave) == 4) ? CONVERTMB2PB * wtAccSum : wtAccSum;
}
//--------------------------------------------------------------------------

// Uncertainty variations initialization

void Info::initUncertainties(vector<string>* variationListIn, bool isISR) {
  size_t vNames = weightLabelSave.size();
  externalVariations.clear();
  externalVarNames.clear();
  externalGroupNames.clear();
  externalMap.clear();
  initialNameSave.clear();
  externalVariations.push_back("Baseline");
  initialNameSave.push_back("Baseline");
  for(vector<string>::const_iterator v=variationListIn->begin();
      v != variationListIn->end(); ++v) {
    string line = *v;
    // Remove initial blank spaces
    while (line.find(" ") == 0) line.erase( 0, 1);
    size_t pos=0;
    // Search for pdf:family keyword for SpaceShower
    if( isISR && ((pos = line.find("isr:pdf:family")) != string::npos) ) {
      size_t posEnd = line.find(" ",pos);
      if( posEnd == string::npos ) posEnd = line.size();
      for(size_t i=0; i < vNames; ++i) {
        string local = weightLabelSave[i];
        if( local.find("isr:pdf:member") != string::npos ) {
          size_t iEqual = local.find("=")+1;
          string nMember = local.substr(iEqual,local.size());
          nMember.append(" ");
          string tmpLine = line;
          tmpLine.replace(pos,posEnd-pos,local);
          size_t iBlank = line.find_first_of(" ");
          tmpLine.replace(iBlank,1,nMember);
          externalVariations.push_back(tmpLine);
          initialNameSave.push_back(line.substr(0,line.find_first_of(" ")));
        }
      }
    } else {
      externalVariations.push_back(line);
      initialNameSave.push_back(line.substr(0,line.find_first_of(" ")));
    }
  }
  externalVariationsSize = externalVariations.size();
  size_t nNames = externalVariationsSize;
  externalVarNames.resize(nNames);
  externalVarNames[0].push_back("Baseline");
  externalGroupNames.resize(nNames);
  externalGroupNames[0]="Baseline";
  for(size_t iWeight = 0; iWeight < nNames; ++iWeight) {
    string uVarString = toLower(externalVariations[iWeight]);
    size_t firstBlank  = uVarString.find_first_of(" ");
    size_t endLine = uVarString.size();
    if( firstBlank > endLine) continue;
    externalGroupNames[iWeight] = uVarString.substr(0,firstBlank);
    uVarString  = uVarString.substr(firstBlank+1,endLine);
    size_t pos = 0;
    while ((pos = uVarString.find(" ")) != string::npos) {
      string token = uVarString.substr(0, pos);
      externalVarNames[iWeight].push_back(token);
      uVarString.erase(0, pos + 1);
    }
    if (uVarString == "" || uVarString == " ") continue;
    externalVarNames[iWeight].push_back(uVarString);
  }
  externalMap.resize(nNames);
  for(size_t iWeight = 0; iWeight < vNames; ++iWeight) {
    for(size_t iV = 0; iV < nNames; ++iV) {
      for(size_t iW = 0; iW < externalVarNames[iV].size(); ++iW) {
        if( externalVarNames[iV][iW] == weightLabelSave[iWeight] ) {
          externalMap[iV].push_back(iWeight);
        } else if ( isISR && externalVarNames[iV][iW].find("isr:pdf:family")
        != string::npos && weightLabelSave[iWeight].find("isr:pdf:member")
        != string::npos ) {
          externalMap[iV].push_back(iWeight);
        }
      }
    }
  }
}

//--------------------------------------------------------------------------

// List of all hard processes switched on.

vector<int> Info::codesHard() {
  vector<int> codesNow;
  for (map<int, long>::iterator nTryEntry = nTryM.begin();
    nTryEntry != nTryM.end(); ++nTryEntry)
      codesNow.push_back( nTryEntry->first );
  return codesNow;
}

//--------------------------------------------------------------------------

// Print a message the first few times. Insert in database.

  void Info::errorMsg(string messageIn, string extraIn, bool showAlways) {

  // Recover number of times message occured. Also inserts new string.
  int times = messages[messageIn];
  ++messages[messageIn];

  // Print message the first few times.
  if (times < TIMESTOPRINT || showAlways) cout << " PYTHIA "
    << messageIn << " " << extraIn << endl;

}

//--------------------------------------------------------------------------

// Provide total number of errors/aborts/warnings experienced to date.

int Info::errorTotalNumber() {

  int nTot = 0;
  for ( map<string, int>::iterator messageEntry = messages.begin();
    messageEntry != messages.end(); ++messageEntry)
    nTot += messageEntry->second;
  return nTot;

}

//--------------------------------------------------------------------------

// Print statistics on errors/aborts/warnings.

void Info::errorStatistics() {

  // Header.
  cout << "\n *-------  PYTHIA Error and Warning Messages Statistics  "
       << "----------------------------------------------------------* \n"
       << " |                                                       "
       << "                                                          | \n"
       << " |  times   message                                      "
       << "                                                          | \n"
       << " |                                                       "
       << "                                                          | \n";

  // Loop over all messages
  map<string, int>::iterator messageEntry = messages.begin();
  if (messageEntry == messages.end())
    cout << " |      0   no errors or warnings to report              "
         << "                                                          | \n";
  while (messageEntry != messages.end()) {
    // Message printout.
    string temp = messageEntry->first;
    int len = temp.length();
    temp.insert( len, max(0, 102 - len), ' ');
    cout << " | " << setw(6) << messageEntry->second << "   "
         << temp << " | \n";
    ++messageEntry;
  }

  // Done.
  cout << " |                                                       "
       << "                                                          | \n"
       << " *-------  End PYTHIA Error and Warning Messages Statistics"
       << "  ------------------------------------------------------* "
       << endl;

}

//--------------------------------------------------------------------------

// Return a list of all header key names

vector < string > Info::headerKeys() {
  vector < string > keys;
  for (map < string, string >::iterator it = headers.begin();
      it != headers.end(); it++)
    keys.push_back(it->first);
  return keys;
}

//--------------------------------------------------------------------------

// Reset the LHEF3 objects read from the init and header blocks.

void Info::setLHEF3InitInfo() {
  initrwgt     = 0;
  generators   = 0;
  weightgroups = 0;
  init_weights = 0;
  headerBlock  = "";
}

//--------------------------------------------------------------------------

// Set the LHEF3 objects read from the init and header blocks.

void Info::setLHEF3InitInfo( int LHEFversionIn, LHAinitrwgt *initrwgtIn,
  vector<LHAgenerator> *generatorsIn,
  map<string,LHAweightgroup> *weightgroupsIn,
  map<string,LHAweight> *init_weightsIn, string headerBlockIn ) {
  LHEFversionSave = LHEFversionIn;
  initrwgt        = initrwgtIn;
  generators      = generatorsIn;
  weightgroups    = weightgroupsIn;
  init_weights    = init_weightsIn;
  headerBlock     = headerBlockIn;
}

//--------------------------------------------------------------------------

// Reset the LHEF3 objects read from the event block.

void Info::setLHEF3EventInfo() {
  eventAttributes    = 0;
  weights_detailed   = 0;
  weights_compressed = 0;
  scales             = 0;
  weights            = 0;
  rwgt               = 0;
  weights_detailed_vector.resize(0);
  eventComments      = "";
  eventWeightLHEF    = 1.0;
}

//--------------------------------------------------------------------------

// Set the LHEF3 objects read from the event block.

void Info::setLHEF3EventInfo( map<string, string> *eventAttributesIn,
   map<string,double> *weights_detailedIn,
   vector<double> *weights_compressedIn,
   LHAscales *scalesIn, LHAweights *weightsIn,
   LHArwgt *rwgtIn, vector<double> weights_detailed_vecIn,
   string eventCommentsIn, double eventWeightLHEFIn ) {
   eventAttributes    = eventAttributesIn;
   weights_detailed   = weights_detailedIn;
   weights_compressed = weights_compressedIn;
   scales             = scalesIn;
   weights            = weightsIn;
   rwgt               = rwgtIn;
   weights_detailed_vector = weights_detailed_vecIn;
   eventComments      = eventCommentsIn;
   eventWeightLHEF    = eventWeightLHEFIn;
}

//--------------------------------------------------------------------------

// Retrieve events tag information.

string Info::getEventAttribute(string key, bool doRemoveWhitespace) {
  if (!eventAttributes) return "";
  if ( eventAttributes->find(key) != eventAttributes->end() ) {
    string res = (*eventAttributes)[key];
    if (doRemoveWhitespace)
      res.erase (remove (res.begin(), res.end(), ' '), res.end());
    return res;
  }
  return "";
}

//--------------------------------------------------------------------------

// Retrieve LHEF version.

int Info::LHEFversion() { return LHEFversionSave;}

//--------------------------------------------------------------------------

// Retrieve initrwgt tag information.

unsigned int Info::getInitrwgtSize() {
  if (!initrwgt) return 0;
  return initrwgt->weights.size();
}

//--------------------------------------------------------------------------

// Retrieve generator tag information.

unsigned int Info::getGeneratorSize() {
  if (!generators) return 0;
  return generators->size();
}

string Info::getGeneratorValue(unsigned int n) {
  if (!generators || generators->size() < n+1) return "";
  return (*generators)[n].contents;
}

string Info::getGeneratorAttribute( unsigned int n, string key,
  bool doRemoveWhitespace) {
  if (!generators || generators->size() < n+1) return "";
  string res("");
  if ( key == "name") {
    res = (*generators)[n].name;
  } else if ( key == "version") {
    res = (*generators)[n].version;
  } else if ( (*generators)[n].attributes.find(key)
           != (*generators)[n].attributes.end() ) {
    res = (*generators)[n].attributes[key];
  }
  if (doRemoveWhitespace && res != "")
    res.erase (remove (res.begin(), res.end(), ' '), res.end());
  return res;
}

//--------------------------------------------------------------------------

// Retrieve rwgt tag information.

unsigned int Info::getWeightsDetailedSize() {
  if (!weights_detailed) return 0;
  return weights_detailed->size();
}

double Info::getWeightsDetailedValue(string n) {
  if (weights_detailed->empty()
    || weights_detailed->find(n) == weights_detailed->end())
    return std::numeric_limits<double>::quiet_NaN();
  return (*weights_detailed)[n];
}

string Info::getWeightsDetailedAttribute(string n, string key,
  bool doRemoveWhitespace) {
  if (!rwgt || rwgt->wgts.find(n) == rwgt->wgts.end())
    return "";
  string res("");
  if ( key == "id") {
    res = rwgt->wgts[n].id;
  } else if ( rwgt->wgts[n].attributes.find(key)
           != rwgt->wgts[n].attributes.end() ) {
    res = rwgt->wgts[n].attributes[key];
  }
  if (doRemoveWhitespace && res != "")
    res.erase (remove (res.begin(), res.end(), ' '), res.end());
  return res;
}

//--------------------------------------------------------------------------

// Retrieve weights tag information.

unsigned int Info::getWeightsCompressedSize() {
  if (!weights_compressed) return 0;
  return weights_compressed->size();
}

double Info::getWeightsCompressedValue(unsigned int n) {
  if (weights_compressed->empty() || weights_compressed->size() < n+1)
    return std::numeric_limits<double>::quiet_NaN();
  return (*weights_compressed)[n];
}

string Info::getWeightsCompressedAttribute(string key,
  bool doRemoveWhitespace) {
  if (!weights || weights->attributes.find(key) == weights->attributes.end())
    return "";
  string res("");
  if ( weights->attributes.find(key)
           != weights->attributes.end() ) {
    res = weights->attributes[key];
  }
  if (doRemoveWhitespace && res != "")
    res.erase (remove (res.begin(), res.end(), ' '), res.end());
  return res;
}

//--------------------------------------------------------------------------

// Retrieve scales tag information.

string Info::getScalesValue(bool doRemoveWhitespace) {
  if (!scales) return "";
  string res = scales->contents;
  if (doRemoveWhitespace && res != "")
    res.erase (remove (res.begin(), res.end(), ' '), res.end());
  return res;
}

double Info::getScalesAttribute(string key) {
  if (!scales) return std::numeric_limits<double>::quiet_NaN();
  double res = std::numeric_limits<double>::quiet_NaN();
  if ( key == "muf") {
    res = scales->muf;
  } else if ( key == "mur") {
    res = scales->mur;
  } else if ( key == "mups") {
    res = scales->mups;
  } else if ( key == "SCALUP") {
    res = scales->SCALUP;
  } else if ( scales->attributes.find(key)
           != scales->attributes.end() ) {
    res = scales->attributes[key];
  }
  return res;
}

//==========================================================================

} // end namespace Pythia8


text:
package io.infinicast.client.impl.query;

import io.infinicast.*;
import io.infinicast.client.api.IPath;
import io.infinicast.client.api.errors.ICError;
import io.infinicast.client.api.paths.*;
import io.infinicast.client.api.paths.handler.lists.APListAddCallback;
import io.infinicast.client.api.paths.handler.lists.APListQueryResultCallback;
import io.infinicast.client.api.paths.handler.objects.CreateObjectCallback;
import io.infinicast.client.api.paths.options.CompleteCallback;
import io.infinicast.client.impl.IConnector;
import io.infinicast.client.impl.contexts.PathAndEndpointContext;
import io.infinicast.client.impl.messaging.ConnectorMessageManager;
import io.infinicast.client.impl.pathAccess.IPathAndData;
import io.infinicast.client.impl.pathAccess.PathAndData;
import io.infinicast.client.protocol.Connector2EpsMessageType;

import java.util.ArrayList;
import java.util.function.BiConsumer;
public class ChildQueryExecutor extends BaseQueryExecutor  {
    public ChildQueryExecutor(IConnector connector, IPath path, ConnectorMessageManager messageManager) {
        super(connector, path, messageManager);
    }
    public void getAndListenOnChilden(ICDataQuery query, boolean isRemove, final BiConsumer<JObject, IPathAndEndpointContext> onAdd, final BiConsumer<JObject, IPathAndEndpointContext> onChange, final BiConsumer<JObject, IPathAndEndpointContext> onRemove, boolean isOncePerRole, boolean isSticky) {
        this.getAndListenOnChilden(query, isRemove, onAdd, onChange, onRemove, isOncePerRole, isSticky, (CompleteCallback) null);
    }
    public void findChildren(ICDataQuery query, final APListQueryResultCallback callback) {
        JObject data = new JObject();
        data.set("query", query.toJson());
        ConnectorMessageManager messageManager = super._messageManager;
        messageManager.sendMessageWithResponse(Connector2EpsMessageType.JsonQuery, super._path, new JObject(data), (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                callback.accept(error, null, 0);
                ;
            }))) {
                ArrayList<IPathAndData> list = new ArrayList<IPathAndData>();
                int fullCount = json.getInt("fullCount");
                JArray array = json.getJArray("list");
                for (JToken ob : array) {
                    PathAndData pathAndData = new PathAndData();
                    pathAndData.setPath(super._connector.getObjectStateManager().getOrCreateLocalObject(ob.getString("path")));
                    pathAndData.setData(ob.getJObject("data"));
                    list.add(pathAndData);
                }
                callback.accept(null, list, fullCount);
                ;
            }
            ;
        });
    }
    public void addChild(JObject objectData, String requestedIdentifier, final CreateObjectCallback callback) {
        JObject data = new JObject();
        data.set("requestedIdentifier", requestedIdentifier);
        data.set("data", objectData);
        super._messageManager.sendMessageWithResponse(Connector2EpsMessageType.CreateChildRequest, super._path, new JObject(data), (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                callback.accept(error, null, null);
                ;
            }))) {
                callback.accept(null, json.getJObject("data"), super.getPathAndEndpointContext(context));
                ;
            }
            ;
        });
    }
    public void findOneOrAddChild(ICDataQuery query, JObject newObjectValue, final QuadConsumer<ICError, JObject, IAPathContext, Boolean> action) {
        JObject parameters = new JObject();
        parameters.set("data", newObjectValue);
        parameters.set("query", query.toJson());
        super._messageManager.sendMessageWithResponse(Connector2EpsMessageType.GetOrCreate, super._path, parameters, (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                action.accept(error, null, null, false);
                ;
            }))) {
                JObject data = json.getJObject("data");
                action.accept(null, data.getJObject("data"), super.getPathAndEndpointContext(context), json.getBoolean("newlyCreated"));
                ;
            }
            ;
        });
    }
    public void modifyAndGetChildrenData(ICDataQuery query, AtomicChange data, final APListQueryResultCallback callback) {
        JObject parameters = new JObject();
        parameters.set("query", query.toJson());
        parameters.set("changes", data.toJson());
        if (data.hasNamedQueries()) {
            parameters.set("named", data.getNamedQueryJson());
        }
        ConnectorMessageManager messageManager = super._messageManager;
        messageManager.sendMessageWithResponse(Connector2EpsMessageType.ModifyChildData, super._path, parameters, (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                callback.accept(error, null, 0);
                ;
            }))) {
                ArrayList<IPathAndData> list = new ArrayList<IPathAndData>();
                int fullCount = json.getInt("fullCount");
                JArray array = json.getJArray("list");
                for (JToken ob : array) {
                    PathAndData pathAndData = new PathAndData();
                    pathAndData.setPath(super._connector.getObjectStateManager().getOrCreateLocalObject(ob.getString("path")));
                    pathAndData.setData(ob.getJObject("data"));
                    list.add(pathAndData);
                }
                callback.accept(null, list, fullCount);
                ;
            }
            ;
        });
    }
    public void getAndListenOnChilden(ICDataQuery query, boolean isRemove, final BiConsumer<JObject, IPathAndEndpointContext> onAdd, final BiConsumer<JObject, IPathAndEndpointContext> onChange, final BiConsumer<JObject, IPathAndEndpointContext> onRemove, boolean isOncePerRole, boolean isSticky, final CompleteCallback registrationCompleteCallback) {
        JObject parameters = new JObject();
        parameters.set("query", query.toJson());
        if (isRemove) {
            parameters.set("remove", true);
        }
        if (isOncePerRole) {
            parameters.set("once", true);
        }
        if (isSticky) {
            parameters.set("sticky", true);
        }
        super._messageManager.sendMessageWithResponse(Connector2EpsMessageType.GetAndListenOnChildren, super._path, parameters, (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                if (registrationCompleteCallback != null) {
                    registrationCompleteCallback.accept(error);
                    ;
                }
                ;
            }))) {
                JArray array = json.getJArray("list");
                for (JToken ob : array) {
                    PathAndEndpointContext ctx = new PathAndEndpointContext(super._connector.path(ob.getString("path")), context.getEndpoint(), context.getEndpointData());
                    JObject d = ob.getJObject("data");
                    onAdd.accept(d, ctx);
                    ;
                }
                if (registrationCompleteCallback != null) {
                    registrationCompleteCallback.accept(null);
                    ;
                }
            }
            ;
        });
        if (!(isRemove)) {
            super._messageManager.registerHandler(Connector2EpsMessageType.ListAdd, super._path, (json, err, context, id) -> {
                if (onAdd != null) {
                    onAdd.accept(json, context);
                    ;
                }
                ;
            });
            super._messageManager.registerHandler(Connector2EpsMessageType.ListChange, super._path, (json, err, context, id) -> {
                if (onChange != null) {
                    onChange.accept(json, context);
                    ;
                }
                ;
            });
            super._messageManager.registerHandler(Connector2EpsMessageType.ListRemove, super._path, (json, err, context, id) -> {
                if (onRemove != null) {
                    onRemove.accept(json, context);
                    ;
                }
                ;
            });
        }
        else {
            super._messageManager.registerHandler(Connector2EpsMessageType.ListAdd, super._path, null);
            super._messageManager.registerHandler(Connector2EpsMessageType.ListRemove, super._path, null);
            super._messageManager.registerHandler(Connector2EpsMessageType.ListChange, super._path, null);
        }
    }
    public void removeChildren(ICDataQuery query) {
        this.removeChildren(query, (BiConsumer<ICError, Integer>) null);
    }
    public void removeChildren(ICDataQuery query, final BiConsumer<ICError, Integer> completeCallback) {
        JObject parameters = new JObject();
        parameters.set("query", query.toJson());
        ConnectorMessageManager messageManager = super._messageManager;
        messageManager.sendMessageWithResponse(Connector2EpsMessageType.RemoveChildren, super._path, parameters, (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                if (completeCallback != null) {
                    completeCallback.accept(error, 0);
                    ;
                }
                else {
                    super._connector.unhandeledErrorInfo(super._path, error);
                }
                ;
            }))) {
                if (completeCallback != null) {
                    completeCallback.accept(null, json.getInt("count"));
                    ;
                }
            }
            ;
        });
    }
    public void setChildrenData(ICDataQuery query, JObject data) {
        this.setChildrenData(query, data, (BiConsumer<ICError, Integer>) null);
    }
    public void setChildrenData(ICDataQuery query, JObject data, final BiConsumer<ICError, Integer> completeCallback) {
        JObject parameters = new JObject();
        parameters.set("query", query.toJson());
        parameters.set("data", data);
        ConnectorMessageManager messageManager = super._messageManager;
        messageManager.sendMessageWithResponse(Connector2EpsMessageType.SetChildData, super._path, parameters, (json, err, context) -> {
            if (!(super.checkIfHasErrorsAndCallHandlersNew(err, (error) -> {
                if (completeCallback != null) {
                    completeCallback.accept(error, 0);
                    ;
                }
                else {
                    super._connector.unhandeledErrorInfo(super._path, error);
                }
                ;
            }))) {
                if (completeCallback != null) {
                    completeCallback.accept(null, json.getInt("fullCount"));
                    ;
                }
            }
            ;
        });
    }
    void onChildHandler(final APListAddCallback callback, HandlerRegistrationOptions options, CompleteCallback completeCallback, final Connector2EpsMessageType connector2EpsMessageType) {
        super._messageManager.addHandler((callback == null), connector2EpsMessageType, super._path, (json, err, context, id) -> {
            callback.accept(json, context);
        }
        , completeCallback, options);
    }
    public void onChildAdd(APListAddCallback callback, HandlerRegistrationOptions options, CompleteCallback completeCallback) {
        this.onChildHandler(callback, options, completeCallback, Connector2EpsMessageType.ListAdd);
    }
    public void onChildAdd(APListAddCallback callback, HandlerRegistrationOptions options) {
        this.onChildAdd(callback, options, (CompleteCallback) null);
    }
    public void onChildAdd(APListAddCallback callback) {
        this.onChildAdd(callback, (HandlerRegistrationOptions) null, (CompleteCallback) null);
    }
    public void onChildChange(APListAddCallback callback, HandlerRegistrationOptions options, CompleteCallback completeCallback) {
        this.onChildHandler(callback, options, completeCallback, Connector2EpsMessageType.ListChange);
    }
    public void onChildChange(APListAddCallback callback, HandlerRegistrationOptions options) {
        this.onChildChange(callback, options, (CompleteCallback) null);
    }
    public void onChildChange(APListAddCallback callback) {
        this.onChildChange(callback, (HandlerRegistrationOptions) null, (CompleteCallback) null);
    }
    public void onChildDelete(APListAddCallback callback, HandlerRegistrationOptions options, CompleteCallback completeCallback) {
        this.onChildHandler(callback, options, completeCallback, Connector2EpsMessageType.ListRemove);
    }
    public void onChildDelete(APListAddCallback callback, HandlerRegistrationOptions options) {
        this.onChildDelete(callback, options, (CompleteCallback) null);
    }
    public void onChildDelete(APListAddCallback callback) {
        this.onChildDelete(callback, (HandlerRegistrationOptions) null, (CompleteCallback) null);
    }
}


text:
<!DOCTYPE html>
<html lang="en-us">
  <head>
    <title>https://dig-eg-gaz.github.io/tag/mac-text-editor/</title>
    <link rel="canonical" href="https://dig-eg-gaz.github.io/tag/mac-text-editor/">
    <meta name="robots" content="noindex">
    <meta charset="utf-8">
    <meta http-equiv="refresh" content="0; url=https://dig-eg-gaz.github.io/tag/mac-text-editor/">
  </head>
</html>


text:
/*
 * 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.
 */
package io.trino.dispatcher;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import io.trino.Session;
import io.trino.event.QueryMonitor;
import io.trino.execution.ClusterSizeMonitor;
import io.trino.execution.LocationFactory;
import io.trino.execution.QueryExecution;
import io.trino.execution.QueryExecution.QueryExecutionFactory;
import io.trino.execution.QueryManager;
import io.trino.execution.QueryPreparer.PreparedQuery;
import io.trino.execution.QueryStateMachine;
import io.trino.execution.warnings.WarningCollector;
import io.trino.execution.warnings.WarningCollectorFactory;
import io.trino.metadata.Metadata;
import io.trino.security.AccessControl;
import io.trino.server.protocol.Slug;
import io.trino.spi.TrinoException;
import io.trino.spi.resourcegroups.ResourceGroupId;
import io.trino.sql.tree.Statement;
import io.trino.transaction.TransactionManager;
import io.trino.util.StatementUtils;

import javax.inject.Inject;

import java.util.Map;
import java.util.Optional;

import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.util.StatementUtils.isTransactionControlStatement;
import static java.util.Objects.requireNonNull;

public class LocalDispatchQueryFactory
        implements DispatchQueryFactory
{
    private final QueryManager queryManager;
    private final TransactionManager transactionManager;
    private final AccessControl accessControl;
    private final Metadata metadata;
    private final QueryMonitor queryMonitor;
    private final LocationFactory locationFactory;

    private final ClusterSizeMonitor clusterSizeMonitor;

    private final Map<Class<? extends Statement>, QueryExecutionFactory<?>> executionFactories;
    private final WarningCollectorFactory warningCollectorFactory;
    private final ListeningExecutorService executor;

    @Inject
    public LocalDispatchQueryFactory(
            QueryManager queryManager,
            TransactionManager transactionManager,
            AccessControl accessControl,
            Metadata metadata,
            QueryMonitor queryMonitor,
            LocationFactory locationFactory,
            Map<Class<? extends Statement>, QueryExecutionFactory<?>> executionFactories,
            WarningCollectorFactory warningCollectorFactory,
            ClusterSizeMonitor clusterSizeMonitor,
            DispatchExecutor dispatchExecutor)
    {
        this.queryManager = requireNonNull(queryManager, "queryManager is null");
        this.transactionManager = requireNonNull(transactionManager, "transactionManager is null");
        this.accessControl = requireNonNull(accessControl, "accessControl is null");
        this.metadata = requireNonNull(metadata, "metadata is null");
        this.queryMonitor = requireNonNull(queryMonitor, "queryMonitor is null");
        this.locationFactory = requireNonNull(locationFactory, "locationFactory is null");
        this.executionFactories = requireNonNull(executionFactories, "executionFactories is null");
        this.warningCollectorFactory = requireNonNull(warningCollectorFactory, "warningCollectorFactory is null");

        this.clusterSizeMonitor = requireNonNull(clusterSizeMonitor, "clusterSizeMonitor is null");

        this.executor = requireNonNull(dispatchExecutor, "dispatchExecutor is null").getExecutor();
    }

    @Override
    public DispatchQuery createDispatchQuery(
            Session session,
            String query,
            PreparedQuery preparedQuery,
            Slug slug,
            ResourceGroupId resourceGroup)
    {
        WarningCollector warningCollector = warningCollectorFactory.create();
        QueryStateMachine stateMachine = QueryStateMachine.begin(
                query,
                preparedQuery.getPrepareSql(),
                session,
                locationFactory.createQueryLocation(session.getQueryId()),
                resourceGroup,
                isTransactionControlStatement(preparedQuery.getStatement()),
                transactionManager,
                accessControl,
                executor,
                metadata,
                warningCollector,
                StatementUtils.getQueryType(preparedQuery.getStatement().getClass()));

        // It is important that `queryCreatedEvent` is called here. Moving it past the `executor.submit` below
        // can result in delivering query-created event after query analysis has already started.
        // That can result in misbehaviour of plugins called during analysis phase (e.g. access control auditing)
        // which depend on the contract that event was already delivered.
        //
        // Note that for immediate and in-order delivery of query events we depend on synchronous nature of
        // QueryMonitor and EventListenerManager.
        queryMonitor.queryCreatedEvent(stateMachine.getBasicQueryInfo(Optional.empty()));

        ListenableFuture<QueryExecution> queryExecutionFuture = executor.submit(() -> {
            QueryExecutionFactory<?> queryExecutionFactory = executionFactories.get(preparedQuery.getStatement().getClass());
            if (queryExecutionFactory == null) {
                throw new TrinoException(NOT_SUPPORTED, "Unsupported statement type: " + preparedQuery.getStatement().getClass().getSimpleName());
            }

            try {
                return queryExecutionFactory.createQueryExecution(preparedQuery, stateMachine, slug, warningCollector);
            }
            catch (Throwable e) {
                stateMachine.transitionToFailed(e);
                throw e;
            }
        });

        return new LocalDispatchQuery(
                stateMachine,
                queryExecutionFuture,
                queryMonitor,
                clusterSizeMonitor,
                executor,
                queryManager::createQuery);
    }
}


text:
/**
 *
 */
package structures;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import utils.Utils;

/**
 * @author lingong
 * General structure to present a document for DM/ML/IR
 */
public class _Doc extends _DocBase implements Comparable<_Doc> {

	String m_itemID; // ID of the product being commented
	String m_title; //The short title of the document

	int m_sourceType = 1; // source is 1 for Amazon (unlabeled) and 2 for newEgg (labeled)

	// added by Lin
	private _SparseFeature[] m_x_posVct; // sparse vector projected by pos tagging
	private double[] m_x_aspVct; // aspect vector

	double m_stopwordProportion = 0;
	double m_avgIDF = 0;
	double m_sentiScore = 0; //Sentiment score from sentiwordnet

	public void setSourceType(int sourceName) {
		m_sourceType = sourceName;
	}

	public int getSourceType() {
		return m_sourceType;
	}

	public double getAvgIDF() {
		return m_avgIDF;
	}

	public void setAvgIDF(double avgIDF) {
		this.m_avgIDF = avgIDF;
	}

	public double getStopwordProportion() {
		return m_stopwordProportion;
	}

	public void setStopwordProportion(double stopwordProportion) {
		this.m_stopwordProportion = stopwordProportion;
	}

	public void setSentiScore(double s){
		this.m_sentiScore = s;
	}

	public double getSentiScore(){
		return this.m_sentiScore;
	}

	//We only need one representation between dense vector and sparse vector: V-dimensional vector.
	private _SparseFeature[] m_x_projection; // selected features for similarity computation (NOTE: will use different indexing system!!)

	static public final int stn_fv_size = 4; // bias, cosine, length_ratio, position
	static public final int stn_senti_fv_size = 6; // bias, cosine, sentiWordNetScore, prior_positive_negative_count, POS tag divergency

	_Stn[] m_sentences;

	//p(z|d) for topic models in general
	public double[] m_topics;
	//sufficient statistics for estimating p(z|d)
	public double[] m_sstat;//i.e., \gamma in variational inference p(\theta|\gamma)

	// structure only used by Gibbs sampling to speed up the sampling process
	_Word[] m_words;

	_Word[] m_testWords;

	int m_testLength;

	// structure only used by variational inference
	public double[][] m_phi; // p(z|w, \phi)
	Random m_rand;

	//Constructor.
	public _Doc (int ID, String source, int ylabel){
		this.m_ID = ID;
		this.m_source = source;
		this.m_y_label = ylabel;
		this.m_totalLength = 0;
		m_topics = null;
		m_sstat = null;
		m_words = null;
		m_sentences = null;
	}

	public _Doc (int ID, String name, String prodID, String title, String source, int ylabel, long timeStamp){
		this.m_ID = ID;
		this.m_name = name;
		this.m_itemID = prodID;
		this.m_title = title;
		this.m_source = source;
		this.m_y_label = ylabel;
		this.m_totalLength = 0;
		this.m_timeStamp = timeStamp;
		m_topics = null;
		m_sstat = null;
		m_words = null;
		m_sentences = null;
	}

	public void setItemID(String itemID) {
		m_itemID = itemID;
	}

	public String getItemID() {
		return m_itemID;
	}

	public String getTitle(){
		return m_title;
	}

	public void setTitle(String title){
		m_title = title;
	}

	public _SparseFeature[] getProjectedFv() {
		return this.m_x_projection;
	}

	public _Word[] getWords() {
		return m_words;
	}

	public _Word getWordByIndex(int i){return m_words[i];}

	public void setWordByIndex(int i, _Word w){m_words[i]=w;}

	public _Word[] getTestWords(){
		return m_testWords;
	}

	public int getDocTestLength(){
		return m_testLength;
	}

	public int getDocInferLength(){
		return this.m_words.length;
	}

	public _SparseFeature[] m_x_sparse_infer;

	public void createSparseVct4Infer(){
		HashMap<Integer, Double> inferVct = new HashMap<Integer, Double>();

		for(_Word w:m_testWords){
			int wIndex = w.getIndex();
			int featureIndex = Utils.indexOf(m_x_sparse, wIndex);
			double featureVal = m_x_sparse[featureIndex].getValue();
			inferVct.put(wIndex, featureVal--);
		}

		m_x_sparse_infer = Utils.createSpVct(inferVct);
	}

	public _SparseFeature[] getSparseVct4Infer(){
		return m_x_sparse_infer;
	}

	//Create the sparse postagging vector for the document.
	public void createPOSVct(HashMap<Integer, Double> posVct){
		m_x_posVct = Utils.createSpVct(posVct);
	}

	public _SparseFeature[] getPOSVct(){
		return m_x_posVct;
	}

	// added by Md. Mustafizur Rahman for HTMM Topic Modelling
	public void setSentences(ArrayList<_Stn> stnList) {
		m_sentences = stnList.toArray(new _Stn[stnList.size()]);
	}

	// added by Md. Mustafizur Rahman for HTMM Topic Modelling
	public int getSenetenceSize() {
		return this.m_sentences.length;
	}

	public _Stn[] getSentences() {
		return m_sentences;
	}

	// added by Md. Mustafizur Rahman for HTMM Topic Modelling
	public _Stn getSentence(int index) {
		return this.m_sentences[index];
	}

	public boolean hasSegments() {
		return m_x_sparse[0].m_values != null;
	}

	//we will reset the topic vector
	public void setTopics(int k, double alpha) {
		if (m_topics==null || m_topics.length!=k) {
			m_topics = new double[k];
			m_sstat = new double[k];
		}
		Utils.randomize(m_sstat, alpha);
	}

	public double[] getTopics(){
		return m_topics;
	}

	//create necessary structure for variational inference
	public void setTopics4Variational(int k, double alpha) {
		if (m_topics==null || m_topics.length!=k) {
			m_topics = new double[k];
			m_sstat = new double[k];//used as p(z|w,\phi)
			m_phi = new double[m_x_sparse.length][k];
		}

		Arrays.fill(m_sstat, alpha);
		for(int n=0; n<m_x_sparse.length; n++) {
			Utils.randomize(m_phi[n], alpha);
			double v = m_x_sparse[n].getValue();
			for(int i=0; i<k; i++)
				m_sstat[i] += m_phi[n][i] * v;
		}
	}

	void createSpace(int k, double alpha) {
		if (m_topics==null || m_topics.length!=k) {
			m_topics = new double[k];
			m_sstat = new double[k];
		}

		Arrays.fill(m_topics, 0);
		Arrays.fill(m_sstat, alpha);

		//Warning: in topic modeling, we cannot normalize the feature vector and we should only use TF as feature value!
		int docSize = getTotalDocLength();
//		int wordsSize = m_words.length;
		if (m_words==null || m_words.length != docSize) {
			m_words = new _Word[docSize];
		}

		if (m_rand==null)
			m_rand = new Random();
	}

	//create necessary structure to accelerate Gibbs sampling
	public void setTopics4Gibbs(int k, double alpha) {
		createSpace(k, alpha);

		int wIndex = 0, wid, tid;
		for(_SparseFeature fv:m_x_sparse) {
			wid = fv.getIndex();
			for(int j=0; j<fv.getValue(); j++) {
				tid = m_rand.nextInt(k);
				m_words[wIndex] = new _Word(wid, tid);// randomly initializing the topics inside a document
				m_sstat[tid] ++; // collect the topic proportion

				wIndex ++;
			}
		}
	}

	public void createSpace4GibbsTest(int k, double alpha, int trainLength){
		if(m_topics==null||m_topics.length!=k){
			m_topics = new double[k];
			m_sstat = new double[k];
		}

		Arrays.fill(m_topics, 0);
		Arrays.fill(m_sstat, alpha);

		if(m_words==null||m_words.length!=trainLength){
			m_words = new _Word[trainLength];
		}

		if(m_rand==null)
			m_rand = new Random();
	}

	public void setTopics4GibbsTest(int k, double alpha, int testLength){
		int trainLength = m_totalLength-testLength;
		createSpace4GibbsTest(k, alpha, trainLength);
		m_testLength = testLength;
		m_testWords = new _Word[testLength];

		ArrayList<Integer> wordIndexs = new ArrayList<Integer>();
		while(wordIndexs.size()<testLength){
			int testIndex = m_rand.nextInt(m_totalLength);
			if(!wordIndexs.contains(testIndex)){
				wordIndexs.add(testIndex);
			}
		}

		int wIndex = 0, wTrainIndex=0, wTestIndex=0, tid, wid;
		for(_SparseFeature fv:m_x_sparse){
			wid = fv.getIndex();
			for(int j=0; j<fv.getValue(); j++){
				tid = m_rand.nextInt(k);
				if(wordIndexs.contains(wIndex)){
					m_testWords[wTestIndex] = new _Word(wid, tid);
					wTestIndex ++;
				}else{
					m_words[wTrainIndex] = new _Word(wid, tid);
					wTrainIndex ++;
					m_sstat[tid] ++; // collect the topic proportion

				}

				wIndex ++;
			}

		}

	}

	//permutation the order of words for Gibbs sampling
	public void permutation() {
		_Word t;
		int s;
		for(int i=m_words.length-1; i>1; i--) {
			s = m_rand.nextInt(i);

			//swap the word
			t = m_words[s];
			m_words[s] = m_words[i];
			m_words[i] = t;
		}
	}

	@Override
	public int compareTo(_Doc d) {
		int prodCompare = m_itemID.compareTo(d.m_itemID);
		if (prodCompare==0) {
			if(m_timeStamp == d.getTimeStamp())
				return 0;
			return m_timeStamp < d.getTimeStamp() ? -1 : 1;
		} else
			return prodCompare;
	}

	public boolean sameProduct(_Doc d) {
		if (m_itemID == null || d.m_itemID == null)
			return false;
		return m_itemID.equals(d.m_itemID);
	}

	@Override
	public String toString() {
		return String.format("ProdID: %s\tID: %s\t Rating: %d\n%s", m_itemID, m_name, m_y_label, m_source);
	}

	public void setProjectedFv(Map<Integer, Integer> filter) {
		m_x_projection = Utils.projectSpVct(m_x_sparse, filter);
//		if (m_x_projection!=null)
//			Utils.L2Normalization(m_x_projection);
	}

	public void setProjectedFv(double[] denseFv) {
		m_x_projection = Utils.createSpVct(denseFv);
	}

	public void setAspVct(double[] aspVct){
		m_x_aspVct = aspVct;
	}

	public double[] getAspVct(){
		return m_x_aspVct;
	}

	/////////////////////////////////////////////////////////
	//temporal structure for CLogisticRegressionWithDP
	/////////////////////////////////////////////////////////
	public int m_pCount = 0;
	public double m_prob = 0;

	public void setWords(ArrayList<_Word> wordList){
		m_words = new _Word[wordList.size()];
		for(int listIndex=0; listIndex<wordList.size(); listIndex++){
			_Word w = wordList.get(listIndex);
			m_words[listIndex] = new _Word(w.getIndex());
			m_words[listIndex].setRawToken(w.getRawToken());
			m_words[listIndex].setRawIndex(w.getRawIndex());
		}
	}

	public void setTopics4GibbsbyRawTokenLDA(int k, double alpha){
		createSpace(k, alpha);
		int wid, tid;

		for(_Word w:m_words){
			wid = w.getIndex();
			tid = m_rand.nextInt(k);
			w.setTopic(tid);

			m_sstat[tid] ++;

		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeria vagabunda Desm.

### Remarks
null


text:
angular.module('save-my-gas')

.controller('mainController', function(
	$scope,
	authService,
	fileStorageService
) {
	$scope.user = authService.getUser()
	$scope.cordova = !!window.cordova

	fileStorageService.init()
})


text:
package pf

import (
	"fmt"
)

// #include <net/if.h>
// #include <net/pfvar.h>
import "C"

// Action that should be performed by pf
type Action uint8

const (
	// ActionPass Filter rule action to pass the traffic
	ActionPass Action = C.PF_PASS
	// ActionDrop Filter rule action to drop the traffic
	ActionDrop Action = C.PF_DROP

	// ActionScrub Scrub rule action to do scrubbing
	ActionScrub Action = C.PF_SCRUB
	// ActionNoScrub Srub rule action to not do scrubbing
	ActionNoScrub Action = C.PF_NOSCRUB

	// ActionNAT NAT rule action to to NAT
	ActionNAT Action = C.PF_NAT
	// ActionNoNAT NAT rule action to not do NAT
	ActionNoNAT Action = C.PF_NONAT

	// ActionBINAT NAT rule action to to BINAT
	ActionBINAT Action = C.PF_BINAT
	// ActionNoBINAT NAT rule action to not do BINAT
	ActionNoBINAT Action = C.PF_NOBINAT

	// ActionRDR RDR rule action to to RDR
	ActionRDR Action = C.PF_RDR
	// ActionNoRDR RDR rule action to not do RDR
	ActionNoRDR Action = C.PF_NORDR

	// ActionSynProxyDrop TODO
	ActionSynProxyDrop Action = C.PF_SYNPROXY_DROP

	// ActionDefer TODO is this divert?
	// Does not exist on Darwin: // ActionDefer Action = C.PF_DEFER
)

func (a Action) String() string {
	switch a {
	case ActionPass:
		return "pass"
	case ActionDrop:
		return "drop"
	case ActionScrub:
		return "scrub"
	case ActionNoScrub:
		return "no scrub"
	case ActionNAT:
		return "nat"
	case ActionNoNAT:
		return "no nat"
	case ActionBINAT:
		return "binat"
	case ActionNoBINAT:
		return "no binat"
	case ActionRDR:
		return "rdr"
	case ActionNoRDR:
		return "no rdr"
	case ActionSynProxyDrop:
		return "synproxy drop"
// Does not exist on Darwin:
/*	case ActionDefer:
		return "defer"
*/
	default:
		return fmt.Sprintf("Action(%d)", a)
	}
}

func (a Action) AnchorString() string {
	switch a {
	case ActionPass, ActionDrop, ActionScrub, ActionNoScrub:
		return "anchor"
	case ActionNAT, ActionNoNAT:
		return "nat-anchor"
	case ActionBINAT, ActionNoBINAT:
		return "binat-anchor"
	case ActionRDR, ActionNoRDR:
		return "rdr-anchor"
	default:
		return fmt.Sprintf("AnchorString(%d)", a)
	}
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RULE_NAME = void 0;
const utils_1 = require("@typescript-eslint/utils");
const create_testing_library_rule_1 = require("../create-testing-library-rule");
const node_utils_1 = require("../node-utils");
exports.RULE_NAME = 'render-result-naming-convention';
const ALLOWED_VAR_NAMES = ['view', 'utils'];
const ALLOWED_VAR_NAMES_TEXT = ALLOWED_VAR_NAMES.map((name) => `\`${name}\``)
    .join(', ')
    .replace(/, ([^,]*)$/, ', or $1');
exports.default = (0, create_testing_library_rule_1.createTestingLibraryRule)({
    name: exports.RULE_NAME,
    meta: {
        type: 'suggestion',
        docs: {
            description: 'Enforce a valid naming for return value from `render`',
            recommendedConfig: {
                dom: false,
                angular: 'error',
                react: 'error',
                vue: 'error',
            },
        },
        messages: {
            renderResultNamingConvention: `\`{{ renderResultName }}\` is not a recommended name for \`render\` returned value. Instead, you should destructure it, or name it using one of: ${ALLOWED_VAR_NAMES_TEXT}`,
        },
        schema: [],
    },
    defaultOptions: [],
    create(context, _, helpers) {
        const renderWrapperNames = [];
        function detectRenderWrapper(node) {
            const innerFunction = (0, node_utils_1.getInnermostReturningFunction)(context, node);
            if (innerFunction) {
                renderWrapperNames.push((0, node_utils_1.getFunctionName)(innerFunction));
            }
        }
        return {
            CallExpression(node) {
                const callExpressionIdentifier = (0, node_utils_1.getDeepestIdentifierNode)(node);
                if (!callExpressionIdentifier) {
                    return;
                }
                if (helpers.isRenderUtil(callExpressionIdentifier)) {
                    detectRenderWrapper(callExpressionIdentifier);
                }
            },
            VariableDeclarator(node) {
                if (!node.init) {
                    return;
                }
                const initIdentifierNode = (0, node_utils_1.getDeepestIdentifierNode)(node.init);
                if (!initIdentifierNode) {
                    return;
                }
                if (!helpers.isRenderVariableDeclarator(node) &&
                    !renderWrapperNames.includes(initIdentifierNode.name)) {
                    return;
                }
                if ((0, node_utils_1.isObjectPattern)(node.id)) {
                    return;
                }
                const renderResultName = utils_1.ASTUtils.isIdentifier(node.id) && node.id.name;
                if (!renderResultName) {
                    return;
                }
                const isAllowedRenderResultName = ALLOWED_VAR_NAMES.includes(renderResultName);
                if (isAllowedRenderResultName) {
                    return;
                }
                context.report({
                    node,
                    messageId: 'renderResultNamingConvention',
                    data: {
                        renderResultName,
                    },
                });
            },
        };
    },
});


text:
import os, sys
import logging
import argparse
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

reload(sys)
sys.setdefaultencoding('utf-8')

from rocket import Rocket
from belga import app

## Clean .pyc
os.system("find . -type f -iname *.pyc -exec rm  -f {} \;")
os.system("echo 1 > logs/http.log")

def rocket_http(debug=False):
    # Setup logging
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    if debug:
       log.addHandler(logging.StreamHandler(sys.stdout))
    else:
       log.addHandler(logging.FileHandler(__name__ + 'logs/http.log'))

    # Set the configuration of the web server
    server = Rocket(interfaces=('0.0.0.0', 5000, 'ssl/server.key', 'ssl/server.crt'), method='wsgi', app_info={"wsgi_app": app})
    server.start(background=True)

def flask_http(debug=False, ssl=False):
    if (ssl):
        from OpenSSL import SSL
        context = SSL.Context(SSL.SSLv23_METHOD)
        context.use_privatekey_file('ssl/server.key')
        context.use_certificate_file('ssl/server.crt')
        app.run(host='0.0.0.0', port=5000, debug=debug, ssl_context=context)
    else:
        app.run(host='0.0.0.0', port=5000, debug=debug)

def main():
    #----------------------------------------
    # parse arguments
    #----------------------------------------
    parser = argparse.ArgumentParser(description='Start Belga')
    parser.add_argument('--flask',  action='store_true')
    parser.add_argument('--ssl',    action='store_true')
    parser.add_argument('--debug',  action='store_true')
    args = parser.parse_args()

    #----------------------------------------
    # create app files
    #----------------------------------------
    if args.flask:
       flask_http(debug=args.debug, ssl=args.ssl)
       sys.exit(1)

    rocket_http(debug=args.debug)

if __name__ == "__main__":
       main()


text:
"""Django page CMS functionnal tests suite module."""
from pages.models import Page, Content, PageAlias
from pages.tests.testcase import TestCase

import django
from django.conf import settings
from django.template import Template, RequestContext
from django.template import TemplateDoesNotExist

import datetime

class FunctionnalTestCase(TestCase):
    """Django page CMS functionnal tests suite class."""

    def test_add_page(self):
        """Test that the add admin page could be displayed via the
        admin"""
        c = self.get_admin_client()

        response = c.get('/admin/pages/page/add/')
        self.assertEqual(response.status_code, 200)

    def test_create_page(self):
        """Test that a page can be created via the admin."""
        c = self.get_admin_client()

        page_data = self.get_new_page_data()
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        slug_content = Content.objects.get_content_slug_by_slug(
            page_data['slug']
        )
        assert(slug_content is not None)
        page = slug_content.page
        self.assertEqual(page.title(), page_data['title'])
        self.assertEqual(page.slug(), page_data['slug'])
        self.assertNotEqual(page.last_modification_date, None)

    def test_delete_page(self):
        """Create a page, then delete it."""
        c = self.get_admin_client()
        page_data = self.get_new_page_data()
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        slug_content = Content.objects.get_content_slug_by_slug(
            page_data['slug']
        )
        assert(slug_content is not None)
        pageCount = Page.objects.count()
        page = slug_content.page
        page.delete()
        slug_content = Content.objects.get_content_slug_by_slug(
            page_data['slug']
        )
        assert(slug_content is None)
        self.assertEqual(Page.objects.count(), pageCount - 1)

    def test_slug_collision(self):
        """Test a slug collision."""
        self.set_setting("PAGE_UNIQUE_SLUG_REQUIRED", True)

        c = self.get_admin_client()

        page_data = self.get_new_page_data()
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        self.set_setting("PAGE_UNIQUE_SLUG_REQUIRED", False)
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 200)

        page1 = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        page_data['position'] = 'first-child'
        page_data['target'] = page1.id
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        page2 = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertNotEqual(page1.id, page2.id)

    def test_details_view(self):
        """Test the details view basics."""

        c = self.get_admin_client()

        response = c.get(self.get_page_url())
        self.assertEqual(response.status_code, 404)

        page_data = self.get_new_page_data()
        page_data['status'] = Page.DRAFT
        response = c.post('/admin/pages/page/add/', page_data)

        response = c.get(self.get_page_url())
        self.assertEqual(response.status_code, 200)

        page_data = self.get_new_page_data()
        page_data['status'] = Page.PUBLISHED
        page_data['slug'] = 'test-page-2'
        page_data['template'] = 'pages/examples/index.html'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        response = c.get(self.get_page_url('test-page-2'))
        self.assertEqual(response.status_code, 200)

    def test_edit_page(self):
        """Test that a page can edited via the admin."""
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        page = Page.objects.all()[0]
        response = c.get('/admin/pages/page/%d/' % page.id)
        self.assertEqual(response.status_code, 200)
        page_data['title'] = 'changed title'
        page_data['body'] = 'changed body'
        response = c.post('/admin/pages/page/%d/' % page.id, page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        page = Page.objects.get(id=page.id)
        self.assertEqual(page.title(), 'changed title')
        body = Content.objects.get_content(page, 'en-us', 'body')
        self.assertEqual(body, 'changed body')

    def test_site_framework(self):
        """Test the site framework, and test if it's possible to
        disable it."""

        from pages import settings as pages_settings

        # it's not possible to enforce PAGE_USE_SITE_ID in the tests
        if not pages_settings.PAGE_USE_SITE_ID:
            #TODO: use unittest.skip skip when 2.7
            return

        # this is necessary to make the test pass
        setattr(pages_settings, "SITE_ID", 2)

        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data["sites"] = [2]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 2)

        page_data = self.get_new_page_data()
        page_data["sites"] = [3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # we cannot get a slug that doesn't exist
        content = Content.objects.get_content_slug_by_slug("this doesn't exist")
        self.assertEqual(content, None)

        # we cannot get the data posted on another site
        content = Content.objects.get_content_slug_by_slug(page_data['slug'])
        self.assertEqual(content, None)

        setattr(pages_settings, "SITE_ID", 3)
        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 3)

        # with param
        self.assertEqual(Page.objects.on_site(2).count(), 1)
        self.assertEqual(Page.objects.on_site(3).count(), 1)

        # without param
        self.assertEqual(Page.objects.on_site().count(), 1)
        setattr(pages_settings, "SITE_ID", 2)
        self.assertEqual(Page.objects.on_site().count(), 1)

        page_data = self.get_new_page_data()
        page_data["sites"] = [2, 3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        self.assertEqual(Page.objects.on_site(3).count(), 2)
        self.assertEqual(Page.objects.on_site(2).count(), 2)
        self.assertEqual(Page.objects.on_site().count(), 2)

        setattr(pages_settings, "PAGE_USE_SITE_ID", False)

        # we should get everything
        self.assertEqual(Page.objects.on_site().count(), 3)

        setattr(pages_settings, "SITE_ID", 1)

    def test_languages(self):
        """Test post a page with different languages
        and test that the admin views works correctly."""
        c = self.get_admin_client()
        user = c.login(username='batiste', password='b')

        # test that the client language setting is used in add page admin
        c.cookies["django_language"] = 'de'
        response = c.get('/admin/pages/page/add/')

        self.assertContains(response, 'value="de"')
        c.cookies["django_language"] = 'fr-ch'
        response = c.get('/admin/pages/page/add/')
        self.assertContains(response, 'value="fr-ch"')

        page_data = self.get_new_page_data()
        page_data["title"] = 'english title'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Page.objects.all()[0]
        self.assertEqual(page.get_languages(), ['en-us'])

        # test the language cache
        self.assertEqual(page.get_languages(), ['en-us'])

        # this test only works in version superior of 1.0.2
        django_version =  django.get_version().rsplit()[0].split('.')
        if len(django_version) > 2:
            major, middle, minor = [int(v) for v in django_version]
        else:
            major, middle = [int(v) for v in django_version]
        if major >= 1 and middle > 0:
            response = c.get('/admin/pages/page/%d/?language=de' % page.id)
            self.assertContains(response, 'value="de"')

        # add a french version of the same page
        page_data["language"] = 'fr-ch'
        page_data["title"] = 'french title'
        response = c.post('/admin/pages/page/%d/' % page.id, page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # test that the frontend view use the good parameters
        # I cannot find a way of setting the accept-language HTTP
        # header so I used django_language cookie instead
        c = self.get_admin_client()
        c.cookies["django_language"] = 'en-us'
        response = c.get(page.get_url_path())
        self.assertContains(response, 'english title')
        self.assertContains(response, 'lang="en-us"')
        self.assertNotContains(response, 'french title')

        c = self.get_admin_client()
        c.cookies["django_language"] = 'fr-ch'
        response = c.get(page.get_url_path())
        self.assertContains(response, 'french title')
        self.assertContains(response, 'lang="fr-ch"')

        self.assertNotContains(response, 'english title')

        # this should be mapped to the fr-ch content
        c = self.get_admin_client()
        c.cookies["django_language"] = 'fr-fr'
        response = c.get(page.get_url_path())
        self.assertContains(response, 'french title')
        self.assertContains(response, 'lang="fr-ch"')

    def test_revision(self):
        """Test that a page can edited several times."""
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        response = c.post('/admin/pages/page/add/', page_data)
        page = Page.objects.all()[0]

        page_data['body'] = 'changed body'
        response = c.post('/admin/pages/page/%d/' % page.id, page_data)
        self.assertEqual(Content.objects.get_content(page, 'en-us', 'body'),
            'changed body')

        page_data['body'] = 'changed body 2'
        response = c.post('/admin/pages/page/%d/' % page.id, page_data)
        page.invalidate()
        self.assertEqual(Content.objects.get_content(page, 'en-us', 'body'),
            'changed body 2')

        response = c.get(page.get_url_path())
        self.assertContains(response, 'changed body 2', 1)

        self.set_setting("PAGE_CONTENT_REVISION", False)

        self.assertEqual(Content.objects.get_content(page, 'en-us', 'body'),
            'changed body 2')

    def test_placeholder(self):
        """
        Test that the placeholder is correctly displayed in
        the admin
        """
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['template'] = 'pages/examples/nice.html'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Page.objects.all()[0]
        response = c.get('/admin/pages/page/%d/' % page.id)
        self.assertEqual(response.status_code, 200)

        self.assertContains(response, 'name="right-column"', 1)

    def test_directory_slug(self):
        """
        Test diretory slugs
        """
        self.set_setting("PAGE_UNIQUE_SLUG_REQUIRED", False)
        c = self.get_admin_client()
        c.login(username='batiste', password='b')

        page_data = self.get_new_page_data()
        page_data['title'] = 'parent title'
        page_data['slug'] = 'same-slug'
        response = c.post('/admin/pages/page/add/', page_data)
        # the redirect tell that the page has been create correctly
        self.assertRedirects(response, '/admin/pages/page/')
        response = c.get(self.get_page_url('same-slug/'))
        self.assertEqual(response.status_code, 200)

        page = Page.objects.all()[0]

        response = c.post('/admin/pages/page/add/', page_data)
        # we cannot create 2 root page with the same slug
        # this assert test that the creation fails as wanted
        self.assertEqual(response.status_code, 200)

        page1 = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page1.id, page.id)

        page_data['title'] = 'children title'
        page_data['target'] = page1.id
        page_data['position'] = 'first-child'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # finaly test that we can get every page according the path
        response = c.get(self.get_page_url('same-slug'))
        self.assertContains(response, "parent title", 3)

        response = c.get(self.get_page_url('same-slug/same-slug'))
        self.assertContains(response, "children title", 3)

    def test_page_admin_view(self):
        """Test page admin view"""
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page-1'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, 1)
        response = c.post('/admin/pages/page/%d/change-status/' %
            page.id, {'status':Page.DRAFT})
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, Page.DRAFT)

        url = '/admin/pages/page/%d/modify-content/title/en-us/' % page.id
        response = c.post(url, {'content': 'test content'})
        self.assertEqual(page.title(), 'test content')

        # TODO: realy test these methods
        url = '/admin/pages/page/%d/traduction/en-us/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)

        url = '/admin/pages/page/%d/sub-menu/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)

        url = '/admin/pages/page/%d/get-content/%d/' % (page.id,
            Content.objects.get_content_slug_by_slug('page-1').id)

        response = c.get(url)
        self.assertEqual(response.status_code, 200)

        url = '/admin/pages/page/%d/delete-content/en-us/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 302)

    def test_page_alias(self):
        """Test page aliasing system"""

        c = self.get_admin_client()
        c.login(username='batiste', password='b')

        # create some pages
        page_data = self.get_new_page_data()
        page_data['title'] = 'home-page-title'
        page_data['slug'] = 'home-page'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page_data['title'] =  'downloads-page-title'
        page_data['slug'] = 'downloads-page'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # create aliases for the pages
        page = Page.objects.from_path('home-page', None)
        self.assertTrue(page)
        p = PageAlias(page=page, url='/index.php')
        p.save()

        page = Page.objects.from_path('downloads-page', None)
        self.assertTrue(page)
        p = PageAlias(page=page, url='index.php?page=downloads')
        p.save()

        # now check whether we can retrieve the pages.
        # is the homepage available from is alias
        response = c.get(self.get_page_url('index.php'))
        self.assertRedirects(response, self.get_page_url('home-page'), 301)

        # for the download page, the slug is canonical
        response = c.get(self.get_page_url('downloads-page/'))
        self.assertContains(response, "downloads-page-title", 3)

        # calling via its alias must cause redirect
        response = c.get(self.get_page_url('index.php')+'?page=downloads')
        self.assertRedirects(response,
            self.get_page_url('downloads-page'), 301)

    def test_page_redirect_to(self):
        """Test page redirected to an other page."""

        client = self.get_admin_client()

        # create some pages
        page1 = self.create_new_page(client)
        page2 = self.create_new_page(client)

        page1.redirect_to = page2
        page1.save()

        # now check whether you go to the target page.
        response = client.get(page1.get_url_path())
        self.assertRedirects(response, page2.get_url_path(), 301)

    def test_page_valid_targets(self):
        """Test page valid_targets method"""
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'root'
        response = c.post('/admin/pages/page/add/', page_data)
        root_page = Content.objects.get_content_slug_by_slug('root').page
        page_data['position'] = 'first-child'
        page_data['target'] = root_page.id
        page_data['slug'] = 'child-1'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 302)
        c1 = Content.objects.get_content_slug_by_slug('child-1').page

        root_page = Content.objects.get_content_slug_by_slug('root').page
        self.assertEqual(len(root_page.valid_targets()), 0)
        self.assertEqual(str(c1.valid_targets()),
                                            "[<Page: root>]")

    def test_ajax_language(self):
        """Test that language is working properly"""
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        # Activate a language other than settings.LANGUAGE_CODE
        response = c.post('/i18n/setlang/', {'language':'fr-ch' })
        self.assertEqual(c.session.get('django_language', False), 'fr-ch')

        # Make sure we're in french
        response = c.get('/admin/pages/page/')
        self.assertEqual(response.status_code, 200)
        self.assertTrue('Auteur' in response.content)

        # Create some pages (taken from test_tree_admin_interface)
        page_data = self.get_new_page_data()
        page_data['slug'] = 'root'
        response = c.post('/admin/pages/page/add/', page_data)

        root_page = Content.objects.get_content_slug_by_slug('root').page
        page_data['position'] = 'first-child'
        page_data['target'] = root_page.id
        page_data['slug'] = 'child-1'
        response = c.post('/admin/pages/page/add/', page_data)

        child_1 = Content.objects.get_content_slug_by_slug('child-1').page

        page_data['slug'] = 'child-2'
        response = c.post('/admin/pages/page/add/', page_data)

        child_2 = Content.objects.get_content_slug_by_slug('child-2').page

        self.assertEqual(str(Page.objects.all()),
            "[<Page: root>, <Page: child-2>, <Page: child-1>]")

        """
        The relevant bit, fixed by rev 501: the response issued by a move
        command returns content localized in settings.LANGUAGE_CODE (i.e. 'en´)
        even though the original AJAX request passed in a the correct
        session ID localizing this client as fr-ch

        This is probably because the LocaleMiddleware gets instantiated
        with a couple request_mocks which have no real connection to the
        AJAX request *but* django.utils.translation caches the active
        language on a per thread basis.

        This means that the first "bogus" call to
        LocaleMiddleware.process_request will "kill" the localization
        data for the AJAX request.

        Rev. 501 fixes this by passing in the language code from the original
        request.
        """
        response = c.post('/admin/pages/page/%d/move-page/' % child_1.id,
            {'position':'first-child', 'target':root_page.id})

        # Make sure the content response we got was in french
        self.assertTrue('Auteur' in response.content)

    def test_view_context(self):
        """
        Test that the default view can only return the context
        """
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        # create a page for the example otherwise you will get a Http404 error
        response = c.post('/admin/pages/page/add/', page_data)
        page1 = Content.objects.get_content_slug_by_slug('page1').page

        from pages.views import details
        from pages.utils import get_request_mock
        request = get_request_mock()
        context = details(request, path='/page1/', only_context=True)
        self.assertEqual(context['current_page'], page1)

    def test_request_mockup(self):
        from pages.utils import get_request_mock
        request = get_request_mock()
        self.assertEqual(hasattr(request, 'session'), True)

    def test_tree_admin_interface(self):
        """
        Test that moving/creating page in the tree is working properly
        using the admin interface
        """
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'root'

        response = c.post('/admin/pages/page/add/', page_data)

        root_page = Content.objects.get_content_slug_by_slug('root').page
        self.assertTrue(root_page.is_first_root())
        page_data['position'] = 'first-child'
        page_data['target'] = root_page.id
        page_data['slug'] = 'child-1'
        response = c.post('/admin/pages/page/add/', page_data)

        child_1 = Content.objects.get_content_slug_by_slug('child-1').page
        self.assertFalse(child_1.is_first_root())

        page_data['slug'] = 'child-2'
        response = c.post('/admin/pages/page/add/', page_data)

        child_2 = Content.objects.get_content_slug_by_slug('child-2').page

        self.assertEqual(str(Page.objects.all()),
            "[<Page: root>, <Page: child-2>, <Page: child-1>]")
        # move page 1 in the first position
        response = c.post('/admin/pages/page/%d/move-page/' % child_1.id,
            {'position':'first-child', 'target':root_page.id})

        self.assertEqual(str(Page.objects.all()),
            "[<Page: root>, <Page: child-1>, <Page: child-2>]")

        # move page 2 in the first position
        response = c.post('/admin/pages/page/%d/move-page/' % child_2.id,
            {'position': 'left', 'target': child_1.id})

        self.assertEqual(str(Page.objects.all()),
            "[<Page: root>, <Page: child-2>, <Page: child-1>]")

        # try to create a sibling with the same slug, via left, right
        from pages import settings as pages_settings
        setattr(pages_settings, "PAGE_UNIQUE_SLUG_REQUIRED", False)
        page_data['target'] = child_2.id
        page_data['position'] = 'left'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 200)

        # try to create a sibling with the same slug, via first-child
        page_data['target'] = root_page.id
        page_data['position'] = 'first-child'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 200)
        # try to create a second page 2 in root
        del page_data['target']
        del page_data['position']

        setattr(pages_settings, "PAGE_UNIQUE_SLUG_REQUIRED", True)
        # cannot create because slug exists
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 200)
        # Now it should work beause the page is not a sibling
        setattr(pages_settings, "PAGE_UNIQUE_SLUG_REQUIRED", False)
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Page.objects.count(), 4)
        # Should not work because we already have sibling at the same level
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(response.status_code, 200)

        # try to change the page 2 slug into page 1
        page_data['slug'] = 'child-1'
        response = c.post('/admin/pages/page/%d/' % child_2.id, page_data)
        self.assertEqual(response.status_code, 200)
        setattr(pages_settings, "PAGE_UNIQUE_SLUG_REQUIRED", True)
        response = c.post('/admin/pages/page/%d/' % child_2.id, page_data)
        self.assertEqual(response.status_code, 200)

    def test_tree(self):
        """
        Test that the navigation tree works properly with mptt.
        """
        c = self.get_admin_client()
        c.login(username='batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        response = c.post('/admin/pages/page/add/', page_data)
        page_data['slug'] = 'page2'
        response = c.post('/admin/pages/page/add/', page_data)
        page_data['slug'] = 'page3'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertEqual(str(Page.objects.navigation()),
            "[<Page: page1>, <Page: page2>, <Page: page3>]")

        p1 = Content.objects.get_content_slug_by_slug('page1').page
        p2 = Content.objects.get_content_slug_by_slug('page2').page
        p3 = Content.objects.get_content_slug_by_slug('page3').page

        p2.move_to(p1, 'left')
        p2.save()

        self.assertEqual(str(Page.objects.navigation()),
            "[<Page: page2>, <Page: page1>, <Page: page3>]")

        p3.move_to(p2, 'left')
        p3.save()

        self.assertEqual(str(Page.objects.navigation()),
            "[<Page: page3>, <Page: page2>, <Page: page1>]")

        p1 = Content.objects.get_content_slug_by_slug('page1').page
        p2 = Content.objects.get_content_slug_by_slug('page2').page
        p3 = Content.objects.get_content_slug_by_slug('page3').page

        p3.move_to(p1, 'first-child')
        p2.move_to(p1, 'first-child')

        self.assertEqual(str(Page.objects.navigation()),
            "[<Page: page1>]")

        p3 = Content.objects.get_content_slug_by_slug('page3').page
        p3.move_to(p1, 'left')

        self.assertEqual(str(Page.objects.navigation()),
            "[<Page: page3>, <Page: page1>]")

    def test_page_redirect_to_url(self):
        """Test page redirected to external url."""

        client = self.get_admin_client()

        page1 = self.create_new_page(client)
        url = 'http://code.google.com/p/django-page-cms/'
        page1.redirect_to_url = url
        page1.save()

        # now check whether we can retrieve the page.
        response = client.get(page1.get_url_path())
        self.assertTrue(response.status_code == 301)
        self.assertTrue(response['Location'] == url)

    def test_page_freeze_date(self):
        """Test page freezing feature."""
        c = self.get_admin_client()
        page_data = self.get_new_page_data()
        page_data['title'] = 'before'
        page_data['slug'] = 'before'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        page = Page.objects.from_path('before', None)
        self.assertEqual(page.freeze_date, None)
        limit = datetime.datetime.now()
        page.freeze_date = limit
        page.save()

        page_data['title'] = 'after'
        page_data['slug'] = 'after'
        # this post erase the limit
        response = c.post('/admin/pages/page/%d/' % page.id, page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Page.objects.from_path('after', None)
        page.freeze_date = limit
        self.assertEqual(page.slug(), 'before')
        page.freeze_date = None
        page.save()
        self.assertEqual(page.slug(), 'after')
        page.freeze_date = limit
        page.save()
        self.assertEqual(page.slug(), 'before')

    def test_delegate_to(self):
        """Test the view delegate feature."""
        c = self.get_admin_client()
        page_data = self.get_new_page_data()
        page_data['title'] = 'delegate'
        page_data['slug'] = 'delegate'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Page.objects.from_path('delegate', None)

        from pages import urlconf_registry as reg
        reg.register_urlconf('test', 'pages.testproj.documents.urls',
            label='test')
        page.delegate_to = 'test'
        page.save()

        response = c.get(self.get_page_url('delegate'))
        self.assertEqual(response.status_code, 200)

        from pages.testproj.documents.models import Document
        doc = Document(title='doc title 1', text='text', page=page)
        doc.save()

        response = c.get(self.get_page_url('delegate/doc-%d' % doc.id))
        self.assertEqual(response.status_code, 200)

        self.assertContains(response, "doc title 1")
        reg.registry = []

    def test_untranslated(self):
        """Test the untranslated feature in the admin."""
        c = self.get_admin_client()
        page_data = self.get_new_page_data()
        page_data['title'] = 'untranslated'
        page_data['slug'] = 'untranslated'
        unstranslated_string = 'the untranslated string'
        page_data['untrans'] = unstranslated_string
        page_data['template'] = 'pages/tests/untranslated.html'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Page.objects.from_path('untranslated', None)
        self.assertEqual(
            Content.objects.get_content(page, 'en-us', 'untrans'),
            unstranslated_string
        )

        page_data['untrans'] = ''
        response = c.get('/admin/pages/page/%d/?language=fr-ch' % page.id)
        self.assertContains(response, unstranslated_string)

    def test_root_page(self):
        """Test that the root page doesn't trigger a 404."""
        c = self.get_admin_client()
        page1 = self.new_page(content={'slug': 'this-is-not-a-404'})
        self.assertEqual(Page.objects.count(), 1)
        page = Page.objects.on_site()[0]
        self.assertTrue(page.is_first_root())

        response = c.get(self.get_page_url())
        self.assertEqual(response.status_code, 200)

    def test_page_with_trailing_slash(self):
        """
        Test that a page is also available with and without a trailing slash.
        """
        c = self.get_admin_client()
        page1 = self.new_page(content={'slug': 'root'})
        page2 = self.new_page(content={'slug': 'other'})
        response = c.get(self.get_page_url('other'))
        self.assertEqual(response.status_code, 200)
        response = c.get(self.get_page_url('other/'))
        self.assertEqual(response.status_code, 200)

    def test_page_sitemap(self):
        """
        Test the sitemap class
        """
        c = self.get_admin_client()
        page1 = self.new_page(content={'slug': 'english-slug'})
        page1.save()
        Content(page=page1, language='fr-ch', type='slug',
            body='french-slug').save()

        response = c.get('/sitemap.xml')

        self.assertContains(response, 'english-slug')
        self.assertNotContains(response, 'french-slug')

        response = c.get('/sitemap2.xml')

        self.assertContains(response, 'english-slug')
        self.assertContains(response, 'french-slug')