text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace ArmyOfCreatures.Logic.Battles
{
    public class BattleManager : IBattleManager
    {
        private const string LogFormat = "--- {0} - {1}";
        //CHANGED FROM "PRIVATE" TO "pROTECTED"!
        protected readonly ICollection<ICreaturesInBattle> firstArmyCreatures;
        //CHANGED FROM "PRIVATE" TO "pROTECTED"!
        protected readonly ICollection<ICreaturesInBattle> secondArmyCreatures;

        private readonly ICreaturesFactory creaturesFactory;

        private readonly ILogger logger;

        public BattleManager(ICreaturesFactory creaturesFactory, ILogger logger)
        {
            this.firstArmyCreatures = new List<ICreaturesInBattle>();
            this.secondArmyCreatures = new List<ICreaturesInBattle>();
            this.creaturesFactory = creaturesFactory;
            this.logger = logger;
        }

        public ICreaturesFactory CreaturesFactory
        {
            get { return this.creaturesFactory; }
        }

        public void AddCreatures(CreatureIdentifier creatureIdentifier, int count)
        {
            if (creatureIdentifier == null)
            {
                throw new ArgumentNullException("creatureIdentifier");
            }

            var creature = this.creaturesFactory.CreateCreature(creatureIdentifier.CreatureType);
            var creaturesInBattle = new CreaturesInBattle(creature, count);
            this.AddCreaturesByIdentifier(creatureIdentifier, creaturesInBattle);

            this.logger.WriteLine(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LogFormat,
                    string.Format(CultureInfo.InvariantCulture, "Creature added to army {0}", creatureIdentifier.ArmyNumber),
                    creature));
        }

        public void Attack(CreatureIdentifier attackerIdentifier, CreatureIdentifier defenderIdentifier)
        {
            var attackerCreature = this.GetByIdentifier(attackerIdentifier);
            if (attackerCreature == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.InvariantCulture, "Attacker not found: {0}", attackerIdentifier));
            }

            var defenderCreature = this.GetByIdentifier(defenderIdentifier);
            if (defenderCreature == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.InvariantCulture, "Defender not found: {0}", defenderIdentifier));
            }

            attackerCreature.StartNewTurn();
            defenderCreature.StartNewTurn();

            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "Attacker before", attackerCreature));
            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "Defender before", defenderCreature));

            // Call ApplyWhenAttacking on attacker
            foreach (var speciallity in attackerCreature.Creature.Specialties)
            {
                speciallity.ApplyWhenAttacking(attackerCreature, defenderCreature);
            }

            // Call ApplyWhenDefending on defender
            foreach (var speciallity in defenderCreature.Creature.Specialties)
            {
                speciallity.ApplyWhenDefending(defenderCreature, attackerCreature);
            }

            // Call ChangeDamage on attacker
            attackerCreature.DealDamage(defenderCreature);

            // Call ApplyAfterDefending on defender
            foreach (var speciallity in defenderCreature.Creature.Specialties)
            {
                speciallity.ApplyAfterDefending(defenderCreature);
            }

            if (attackerIdentifier.ArmyNumber == defenderIdentifier.ArmyNumber)
            {
                throw new ArgumentException();
            }

            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "Attacker after", attackerCreature));
            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "Defender after", defenderCreature));
        }

        public void Skip(CreatureIdentifier creatureIdentifier)
        {
            var creature = this.GetByIdentifier(creatureIdentifier);
            if (creature == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.InvariantCulture, "Skip creature not found: {0}", creatureIdentifier));
            }

            creature.StartNewTurn();

            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "Before skip", creature));

            creature.Skip();
            creature.StartNewTurn();

            this.logger.WriteLine(string.Format(CultureInfo.InvariantCulture, LogFormat, "After skip", creature));
        }

        protected virtual void AddCreaturesByIdentifier(CreatureIdentifier creatureIdentifier, ICreaturesInBattle creaturesInBattle)
        {
            if (creatureIdentifier == null)
            {
                throw new ArgumentNullException("creatureIdentifier");
            }

            if (creaturesInBattle == null)
            {
                throw new ArgumentNullException("creaturesInBattle");
            }

            if (creatureIdentifier.ArmyNumber == 1)
            {
                this.firstArmyCreatures.Add(creaturesInBattle);
            }
            else if (creatureIdentifier.ArmyNumber == 2)
            {
                this.secondArmyCreatures.Add(creaturesInBattle);
            }
            else
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.InvariantCulture, "Invalid ArmyNumber: {0}", creatureIdentifier.ArmyNumber));
            }
        }

        protected virtual ICreaturesInBattle GetByIdentifier(CreatureIdentifier identifier)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException("identifier");
            }

            if (identifier.ArmyNumber == 1)
            {
                return this.firstArmyCreatures.FirstOrDefault(x => x.Creature.GetType().Name == identifier.CreatureType);
            }

            if (identifier.ArmyNumber == 2)
            {
                return this.secondArmyCreatures.FirstOrDefault(x => x.Creature.GetType().Name == identifier.CreatureType);
            }

            throw new ArgumentException(
                string.Format(CultureInfo.InvariantCulture, "Invalid ArmyNumber: {0}", identifier.ArmyNumber));
        }
    }
}


text:
import requests
import urllib
from config import setting
from model import user

config = setting.config

class oauthbase(object):
    def __init__(self,user=None):
        self.set_user(user)

    def check_err(self,json):
        code = self.str_err_code
        msg = self.str_err_msg
        name = self.name
        if code in json:
            if name == "douban" and json[msg].startswith("access_token_has_expired"):
                user.update_access_token(name,self.user[name+"_id"],None)
            else:
                raise Exception(json[msg])

    def signed_request(self,method,url,data={}):
        if not self._token:
            return {}
        req = requests.request(method,url,data=data,headers={"Authorization":self.header_str + " "+self._token})
        json = req.json()
        self.check_err(json)
        return json

    def signed_post(self,url,data={}):
        return self.signed_request("post",url,data=data)

    def signed_get(self,url):
        return self.signed_request("get",url)

    def get_access_token(self,code):
        name = self.name
        data = {
            "client_id":config["auth_"+name+"_key"],
            "client_secret":config["auth_"+name+"_secret"],
            "redirect_uri":config["auth_"+name+"_callback"],
            "grant_type":"authorization_code",
            "code":code
        }
        res_access_token = requests.post(self.access_token_url,data=data)
        res_json = res_access_token.json()
        try:
            self.check_err(res_json)
        except Exception,e:
            return str(e)
        return res_json["access_token"]

    def set_user(self,user):
        token_name = self.name + "_access_token"
        self.user = user
        if user and token_name in user:
            self._token = user[token_name]

    def redirect(self):
        name = self.name
        base = self.authorize_url

        key = config["auth_"+name+"_key"]
        secret = config["auth_"+name+"_secret"]
        callback = config["auth_"+name+"_callback"]
        qs = urllib.urlencode({"redirect_uri":callback,"client_id":key,"response_type":"code"})
        url = base+"?"+qs
        return url

redpajama_set_name: RedPajamaGithub


text: ck detect soft tags=compiler,lang-python


text:
namespace apache { namespace thrift { namespace transport {

using namespace std;

TBufPairTransport::TBufPairTransport() : input_(new TMemoryBuffer()), output_(new TMemoryBuffer()) {
}

TBufPairTransport::~TBufPairTransport() {
}

bool TBufPairTransport::isOpen() {
  return input_->isOpen() && output_->isOpen();
}

bool TBufPairTransport::peek() {
  return input_->peek();
}

uint32_t TBufPairTransport::read(uint8_t* buf, uint32_t len) {
  return input_->read(buf, len);
}

uint32_t TBufPairTransport::readEnd() {
  return input_->readEnd();
}

void TBufPairTransport::write(const uint8_t* buf, uint32_t len) {
  output_->write(buf, len);
}

void TBufPairTransport::flush() {
  output_->flush();
}

boost::shared_ptr<TMemoryBuffer> TBufPairTransport::getIn() {
  return input_;
}

boost::shared_ptr<TMemoryBuffer> TBufPairTransport::getOut() {
  return output_;
}

}}}


text:
//
//  SIXBannerCollectionViewCell.h
//  sixLive
//
//  Created by li'Pro on 2017/6/28.
//  Copyright © 2017年 li'Pro. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "SIXEvent.h"

// banner cell
@interface SIXBannerCollectionViewCell : UICollectionViewCell

@property (strong, nonatomic) NSArray<SIXEvent *> *arrEvent;

/** 注册 cell 的 id  */
+ (NSString *)cellReuseIdentifier ;

+ (CGSize)cellSize ;

@end


text:
package net.minidev.ovh.api.hosting.web;

import java.util.Date;
import net.minidev.ovh.api.hosting.web.localseo.location.OvhCountryEnum;
import net.minidev.ovh.api.hosting.web.localseo.location.OvhOfferEnum;
import net.minidev.ovh.api.hosting.web.localseo.location.OvhStatusEnum;

/**
 * Local SEO locations
 */
public class OvhLocalSeoLocation {
	/**
	 * Local SEO offer for this location
	 *
	 * canBeNull && readOnly
	 */
	public OvhOfferEnum offer;

	/**
	 * Account id
	 *
	 * canBeNull && readOnly
	 */
	public Long accountId;

	/**
	 * Country of the location
	 *
	 * canBeNull && readOnly
	 */
	public OvhCountryEnum country;

	/**
	 * Address of the location
	 *
	 * canBeNull && readOnly
	 */
	public String address;

	/**
	 * Date of the last location's update
	 *
	 * canBeNull && readOnly
	 */
	public Date lastUpdate;

	/**
	 * Name of the location
	 *
	 * canBeNull && readOnly
	 */
	public String name;

	/**
	 * Location id
	 *
	 * canBeNull && readOnly
	 */
	public Long id;

	/**
	 * Date of the installation of the location
	 *
	 * canBeNull && readOnly
	 */
	public Date creationDate;

	/**
	 * Running task associated to the location
	 *
	 * canBeNull && readOnly
	 */
	public Long taskId;

	/**
	 * Current status of the location
	 *
	 * canBeNull && readOnly
	 */
	public OvhStatusEnum status;
}


text:
<?php
namespace Urgence\View\Helper;

use ZendPdf;
use ZendPdf\Page;
use ZendPdf\Font;
use Urgence\Model\Consultation;
use Urgence\View\Helper\DateHelper;

class FacturePdf
{
	protected $_page;
	protected $_yPosition;
	protected $_leftMargin;
	protected $_pageWidth;
	protected $_pageHeight;
	protected $_normalFont;
	protected $_boldFont;
	protected $_newTime;
	protected $_newTimeGras;
	protected $_year;
	protected $_headTitle;
	protected $_introText;
	protected $_graphData;
	protected $_patient;
	protected $_date;
	protected $_note;
	protected $_idPersonne;
	protected $_Service;
	protected $_DonneesPatient;
	protected $_infos;

	public function __construct()
	{
		$this->_page = new Page(Page::SIZE_A4 );

 		$this->_yPosition = 750;
 		$this->_leftMargin = 50;
 		$this->_pageHeight = $this->_page->getHeight();
 		$this->_pageWidth = $this->_page->getWidth();
 		/**
 		 * Pas encore utilisé
 		 */
 		$this->_normalFont = Font::fontWithName( ZendPdf\Font::FONT_HELVETICA);
 		$this->_boldFont = Font::fontWithName( ZendPdf\Font::FONT_HELVETICA_BOLD);
 		/**
 		 *****************
 		 */
 		$this->_newTime = Font::fontWithName(ZendPdf\Font::FONT_TIMES_ROMAN);
 		$this->_newTimeGras = Font::fontWithName(ZendPdf\Font::FONT_TIMES_BOLD);
	}

	public function getPage(){
		return $this->_page;
	}

	public function addNote(){
		$this->_page->saveGS();

		$this->setEnTete();
		$this->getNoteInformations();
		$this->getPiedPage();

		$this->_page->restoreGS();
	}

	public function setEnTete(){
		$baseUrl = $_SERVER['SCRIPT_FILENAME'];
		$tabURI  = explode('public', $baseUrl);

		$imageHeader = ZendPdf\Image::imageWithPath($tabURI[0].'public/img/polycliniquelogo.png');
		$this->_page->drawImage($imageHeader, 445, //-x
				$this->_pageHeight - 130, //-y
				528, //+x
				787); //+y

		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('République du Sénégal',
				$this->_leftMargin,
				$this->_pageHeight - 50);
		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('Ministère de la santé et de l\'action sociale',
				$this->_leftMargin,
				$this->_pageHeight - 65);
		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('Polyclinique de l\'UGB de Saint-Louis',
				$this->_leftMargin,
				$this->_pageHeight - 80);
		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('Service: '.$this->_Service,
				$this->_leftMargin,
				$this->_pageHeight - 95);
		$font = ZendPdf\Font::fontWithName(ZendPdf\Font::FONT_TIMES_ROMAN);
		$this->_page->setFont($font, 8);
		$today = new \DateTime ();
		$dateNow = $today->format ( 'd/m/Y' );
		$this->_page->drawText('Saint-Louis le, ' . $dateNow,
				450,
				$this->_pageHeight - 50);
	}

	public function setDonneesPatient($donneesPatient){
		$this->_DonneesPatient = $donneesPatient;
	}

	public function setService($service){
		$this->_Service = $service;
	}

	public function setInformations($infos){
		$this->_infos = $infos;
	}

	public function getNewItalique(){
		$font = ZendPdf\Font::fontWithName(ZendPdf\Font::FONT_HELVETICA_OBLIQUE);
		$this->_page->setFont($font, 12);
	}

	public function getNewTime(){
		$font = ZendPdf\Font::fontWithName(ZendPdf\Font::FONT_TIMES_ROMAN);
		$this->_page->setFont($font, 13);
	}

	public function getNewTimeBold(){
		$font = ZendPdf\Font::fontWithName(ZendPdf\Font::FONT_TIMES_BOLD);
		$this->_page->setFont($font, 16);
	}

	public function getStyle(){
		$font = ZendPdf\Font::fontWithName(ZendPdf\Font::FONT_TIMES_ITALIC);
		$this->_page->setFont($font, 14);
	}

	protected function nbAnnees($debut, $fin) {
		//60 secondes X 60 minutes X 24 heures dans une journee
		$nbSecondes = 60*60*24*365;

		$debut_ts = strtotime($debut);
		$fin_ts = strtotime($fin);
		$diff = $fin_ts - $debut_ts;
		return round($diff / $nbSecondes);
	}

	protected function scinderText($Text){
		$tab = array();
		$tab[1] = substr($Text, 0, 65).'.';
		$tab[2] = substr($Text, 65, 60);
		$tab[3] = substr($Text, 110, 60);
		return $tab;
	}

	protected  function getNoteInformations(){
		$Control = new DateHelper();

		$this->_yPosition -= 35;
		$this->_page->setFont($this->_newTime, 15);
		$this->_page->setFillColor(new ZendPdf\Color\Html('green'));
		$this->_page->drawText('FACTURE',
				$this->_leftMargin+200,
				$this->_yPosition);
		$this->_yPosition -= 5;
		$this->_page->setlineColor(new ZendPdf\Color\Html('green'));
		$this->_page->drawLine($this->_leftMargin,
				$this->_yPosition,
				$this->_pageWidth -
				$this->_leftMargin,
				$this->_yPosition);
		$noteLineHeight = 30;
		$this->_yPosition -= 15;

		$this->_page->setFillColor(new ZendPdf\Color\Html('black')); //Pour le text

		$this->_page->setLineColor(new ZendPdf\Color\Html('#999999')); //Pour les ligne
		//$this->_page->setLineWidth(5);
		//$this->_page->setLineDashingPattern(array(1, 2));

		$l = 1;
		$i = 0;
		$d = 1;
		$cpt = 0;

		//-----------------------------------------------
		$value = $this->_DonneesPatient;
			//-----------------------------------------------
			$this->_page->setFont($this->_newTimeGras, 9);
			$this->_page->drawText('PRENOM & NOM :',
					$this->_leftMargin+123,
					$this->_yPosition);
			$this->_page->setFont($this->_newTime, 10);
			$this->_page->drawText(iconv ('UTF-8' ,'ISO-8859-1' , $value['PRENOM'].'  '.$value['NOM']),
					$this->_leftMargin+210,
					$this->_yPosition);
			//-----------------------------------------------
			$this->_yPosition -= 15;// allez a ligne suivante
			//----------------------------------------------
			$this->_page->setFont($this->_newTimeGras, 9);
			$this->_page->drawText('SEXE :',
					$this->_leftMargin+173,
					$this->_yPosition);
			$this->_page->setFont($this->_newTime, 10);
			$this->_page->drawText(iconv ('UTF-8' ,'ISO-8859-1' , $value['SEXE']),
					$this->_leftMargin+210,
					$this->_yPosition);
 			//-----------------------------------------------
    		$this->_yPosition -= 15;// allez a ligne suivante
 			//----- -----------------------------------------
			$date_naissance = $value['DATE_NAISSANCE'];
			if($date_naissance){ $date_naissance = $Control->convertDate($date_naissance); } else {$date_naissance = null; }

			if($date_naissance){
				$this->_page->setFont($this->_newTimeGras, 9);
				$this->_page->drawText('DATE DE NAISSANCE :',
						$this->_leftMargin+102,
						$this->_yPosition);
				$this->_page->setFont($this->_newTime, 10);

				$this->_page->drawText($date_naissance."  (".$value['AGE']." ans)",
						$this->_leftMargin+210,
						$this->_yPosition);
			}else {
				$this->_page->setFont($this->_newTimeGras, 9);
				$this->_page->drawText('AGE :',
						$this->_leftMargin+176,
						$this->_yPosition);
				$this->_page->setFont($this->_newTime, 10);

				$this->_page->drawText($value['AGE']." ans",
						$this->_leftMargin+210,
						$this->_yPosition);
			}

			//-----------------------------------------------
			$this->_yPosition -= 15;// allez a ligne suivante
			//----------------------------------------------
			$this->_page->setFont($this->_newTimeGras, 9);
			$this->_page->drawText('ADRESSE :',
					$this->_leftMargin+155,
					$this->_yPosition);
			$this->_page->setFont($this->_newTime, 10);
			$this->_page->drawText(iconv ('UTF-8' ,'ISO-8859-1' , $value['ADRESSE']),
					$this->_leftMargin+210,
					$this->_yPosition);
			//-----------------------------------------------

			$this->_page->setlineColor(new ZendPdf\Color\Html('green'));
			$this->_page->setLineWidth(0.2);
			$this->_page->setLineDashingPattern(array(0, 0));
			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition-10,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition-10);

			$this->_page->setLineColor(new ZendPdf\Color\Html('#999999')); //Pour les ligne
			$this->_page->setLineWidth(0.2);
			$this->_page->setLineDashingPattern(array(1, 2));

		//-----------------------------------------------
		$this->_yPosition -= $noteLineHeight+12;//aller a la ligne suivante

		//-----------------------------------------------
		//-----------------------------------------------
		$this->getStyle();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Numéro : "),
				$this->_leftMargin+5,
				$this->_yPosition);

		$this->getNewTime();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->_infos['numero']),
				$this->_leftMargin+80,
				$this->_yPosition);

		$this->_page->drawLine($this->_leftMargin,
				$this->_yPosition,
				$this->_pageWidth -
				$this->_leftMargin,
				$this->_yPosition);
		$this->_yPosition -= $noteLineHeight;

		//-----------------------------------------------
		//-----------------------------------------------
		$this->getStyle();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Service d'admission : "),
				$this->_leftMargin+5,
				$this->_yPosition);

		$this->getNewTime();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->_infos['service']),
				$this->_leftMargin+140,
				$this->_yPosition);

		$this->_page->drawLine($this->_leftMargin,
				$this->_yPosition,
				$this->_pageWidth -
				$this->_leftMargin,
				$this->_yPosition);
		$this->_yPosition -= $noteLineHeight;

		//-----------------------------------------------
		//-----------------------------------------------
		$this->getStyle();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Tarif de la consultation : "),
				$this->_leftMargin+5,
				$this->_yPosition);

		$this->getNewTimeBold();
		$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->_infos['montant']),
				$this->_leftMargin+160,
				$this->_yPosition);
		$this->getNewTime();
		$this->_page->drawText('  francs',
				$this->_leftMargin+200,
				$this->_yPosition);

		$this->_page->drawLine($this->_leftMargin,
				$this->_yPosition,
				$this->_pageWidth -
				$this->_leftMargin,
				$this->_yPosition);
		$this->_yPosition -= $noteLineHeight;

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

		if($this->_infos['type_facturation'] == 2){

			$this->_page->setLineColor(new ZendPdf\Color\Html('#ffffff')); //Pour les ligne
			$this->_page->setLineWidth(0.1);
			$this->_page->setLineDashingPattern(array(0, 0));

			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition);
			$this->_yPosition -= $noteLineHeight;

			$this->_page->setLineColor(new ZendPdf\Color\Html('#999999')); //Pour les ligne
			$this->_page->setLineWidth(0.2);
			$this->_page->setLineDashingPattern(array(1, 2));
			//-----------------------------------------------
			//-----------------------------------------------
			$this->getStyle();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Prise en charge par : "),
					$this->_leftMargin+5,
					$this->_yPosition);

			$this->getNewTime();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->scinderText($this->_infos['organisme'])[1]),
					$this->_leftMargin+160,
					$this->_yPosition);

			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition);
			$this->_yPosition -= $noteLineHeight;
			//-----------------------------------------------
			//-----------------------------------------------
			$this->getStyle();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Taux de la majoration : "),
					$this->_leftMargin+5,
					$this->_yPosition);

			$this->getNewTime();

			if($this->_infos['taux']){
				$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->_infos['taux'].' %'),
						$this->_leftMargin+160,
						$this->_yPosition);
			}else {
				$this->_page->drawText( '00 %',
						$this->_leftMargin+160,
						$this->_yPosition);
			}

			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition);
			$this->_yPosition -= $noteLineHeight;

			//-----------------------------------------------
			//-----------------------------------------------
			$this->getStyle();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "valeur de la majoration : "),
					$this->_leftMargin+5,
					$this->_yPosition);

			$this->getNewTime();
			$this->_page->drawText( ($this->_infos['montant']/100) * $this->_infos['taux'] .' francs',
					$this->_leftMargin+160,
					$this->_yPosition);

			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition);
			$this->_yPosition -= $noteLineHeight;

			//-----------------------------------------------
			//-----------------------------------------------
			$this->getStyle();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', "Tarif avec majoration : "),
					$this->_leftMargin+5,
					$this->_yPosition);

			$this->getNewTimeBold();
			$this->_page->drawText(iconv ( 'UTF-8', 'ISO-8859-1', $this->_infos['montant_avec_majoration']),
					$this->_leftMargin+160,
					$this->_yPosition);
			$this->getNewTime();
			$this->_page->drawText('  francs',
					$this->_leftMargin+200,
					$this->_yPosition);

			$this->_page->drawLine($this->_leftMargin,
					$this->_yPosition,
					$this->_pageWidth -
					$this->_leftMargin,
					$this->_yPosition);
			$this->_yPosition -= $noteLineHeight;
		}

		//-----------------------------------------------
		//-----------------------------------------------
	}

	public function getPiedPage(){
		$this->_page->setlineColor(new ZendPdf\Color\Html('green'));
		$this->_page->setLineWidth(1.5);
		$this->_page->setLineDashingPattern(array(0, 0));
		$this->_page->drawLine($this->_leftMargin,
				120,
				$this->_pageWidth -
				$this->_leftMargin,
				120);

		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('Téléphone: 33 726 25 36   BP: 24000',
				$this->_leftMargin,
				$this->_pageWidth - ( 100 + 390));

		$this->_page->setFont($this->_newTime, 10);
		$this->_page->drawText('SIMENS+: ',
				$this->_leftMargin + 355,
				$this->_pageWidth - ( 100 + 390));
		$this->_page->setFont($this->_newTimeGras, 11);
		$this->_page->drawText('www.simens.sn',
				$this->_leftMargin + 405,
				$this->_pageWidth - ( 100 + 390));
	}

}


text:
package es.logongas.ix3.security.model;

import java.util.Set;

/**
 *
 * @author Lorenzo González
 */
public class Group extends Identity {
    private Set<GroupMember> groupMembers;

    public Group() {
    }

    public Group(int idIdentity, String login, String name) {
        super(idIdentity, login, name);
    }

    /**
     * @return the groupMembers
     */
    public Set<GroupMember> getGroupMembers() {
        return groupMembers;
    }

    /**
     * @param groupMembers the groupMembers to set
     */
    public void setGroupMembers(Set<GroupMember> groupMembers) {
        this.groupMembers = groupMembers;
    }
}


text:
package org.theospi.portfolio.wizard.taggable.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.metaobj.shared.mgt.EntityProducerBase;

public class WizardReferenceEntityProducer extends EntityProducerBase {

	protected final Log logger = LogFactory.getLog(getClass());

	public void init() {
		logger.info("init()");
		try {
			getEntityManager().registerEntityProducer(this, WizardReference.REF_SEPARATOR + WizardReference.REF_BASE);
		}
		catch (Exception e) {
			logger.warn("Error registering WizardReference Entity Producer", e);
		}
	}

	public void destroy() {
		logger.info("destroy()");
	}

	public boolean parseEntityReference(String reference, Reference ref) {
		if (reference.startsWith(getContext())) {
			String[] parts = reference.split(WizardReference.REF_SEPARATOR, 4);
			if (parts.length < 4) {
				return false;
			}
			String type = parts[1];
			/*
			 * This is only really used so we know what kind of object we are
			 * referencing
			 */
			String subtype = parts[2];

			//String context = parts[2];
			/*
			 * This is only used when we have a reference to a specific object
			 */
			String id = parts[3];

			ref.set(type, subtype, id, null, null);

			return true;
		}
		return false;
	}

	public String getLabel()
	{
		return WizardReference.REF_BASE;
	}

	/*
	public Entity getEntity(Reference ref) {
		return null;
	}
	 */
}


text:
/** @namespace utils */
// @flow

import fs from 'fs'
import util from 'util'
import { typeOf } from 'ne-types'
import { sync as readPkg } from 'read-pkg-up'
import { merge } from 'lodash'

export { dedent as joinLines } from 'ne-tag-fns'

const { Stats } = fs;

/**
 * Deferred is modeled after jQuery's deferred object. It inverts a promise
 * such that its resolve and reject methods can be invoked without wrapping
 * all of the related code within a Promise's function.
 *
 * @memberof utils
 * @class Deferred
 */
export class Deferred {
  /**
   * This property holds a `resolve` function from within the promise this
   * deferred inverts.
   *
   * @type {Function}
   * @memberof Deferred
   * @instance
   */
  resolve: Function;

  /**
   * This property holds a `reject` function from within the promise this
   * deferred inverts
   *
   * @type {Function}
   * @memberof Deferred
   * @instance
   */
  reject: Function;

  /**
   * This is the promise wrapped by and inverted in this deferred instance
   *
   * @type {Promise}
   * @memberof Deferred
   * @instance
   */
  promise: any;

  /**
   * An at a glance boolean property that denotes whether or not this
   * deferred has been resolved or rejected yet.
   *
   * @type {boolean}
   * @memberof Deferred
   * @instance
   */
  complete: boolean;

  /**
   * Creates an object with four properties of note; promise, resolve, reject
   * and a flag complete that will be set once either resolve or reject have
   * been called. A Deferred is considered to be pending while complete is set
   * to false.
   *
   * Once constructed, resolve and reject can be called later, at which point,
   * the promise is completed. The promise property is the promise resolved
   * or rejected by the associated properties and can be used with other
   * async/await or Promise based code.
   *
   * @instance
   * @memberof Deferred
   * @method ⎆⠀constructor
   *
   * @param {any} resolveWith a deferred resolved as Promise.resolve() might do
   * @param {any} rejectWith a deferred rejected as Promise.reject() might do
   */
  constructor(resolveWith: any, rejectWith: any) {
    this.promise = new Promise((resolve, reject) => {
      this.complete = false;

      this.resolve = (...args) => {
        this.complete = true;
        return resolve(...args);
      };

      this.reject = (...args) => {
        this.complete = true;
        return reject(...args);
      };

      if (resolveWith && !rejectWith) { this.resolve(resolveWith) }
      if (rejectWith && !resolveWith) { this.reject(rejectWith) }
    });
  }

  /**
   * Shorthand getter that denotes true if the deferred is not yet complete.
   *
   * @instance
   * @memberof Deferred
   * @method ⬇⠀pending
   *
   * @return {boolean} true if the promise is not yet complete; false otherwise
   */
  get pending(): boolean { return !this.complete }

  /**
   * Promises are great but if the code never resolves or rejects a deferred,
   * then things will become eternal; in a bad way. This makes that less likely
   * of an event.
   *
   * If the number of milliseconds elapses before a resolve or reject occur,
   * then the deferred is rejected.
   *
   * @static
   * @memberof Deferred
   * @method ⌾⠀TimedDeferred
   *
   * @param {Number} timeOut a number of milliseconds to wait before rejecting
   * the deferred.
   * @param {Promise} proxyPromise a promise to proxy then/catch through to the
   * deferreds resolve/reject.
   * @return {Deferred} an instance of deferred that will timeout after
   * `timeOut` milliseconds have elapsed. If `proxyPromise` is a `Promise`
   * then the deferred's reject and resolve will be tied to the Promise's
   * catch() and then() methods, respectively.
   */
  static TimedDeferred(timeOut: Number, proxyPromise: ?any): Deferred {
    const deferred = new Deferred();

    if (proxyPromise && typeOf(proxyPromise) === Promise.name) {
      proxyPromise.then((...args) => deferred.resolve(...args))
      proxyPromise.catch(reason => deferred.reject(reason))
    }

    setTimeout(() => deferred.reject(new Error('Deferred timed out'), timeOut))

    return deferred;
  }
}

/**
 * A simply promisify style function that returns an async function wrapped
 * around a supplied function designed for the standard callback methodology.
 * If the callback is the last parameter, and that callback is in the form of
 * (error, ...results) then this wrapper will do the trick for you.
 *
 * @method utils~⌾⠀promisify
 * @since 2.7.0
 *
 * @param {Function} method a function to wrap in an asynchronous function
 * @param {mixed} context an optional `this` object for use with the supplied
 * function.
 * @return {Function} an asynchronous function, i.e. one that returns a promise
 * containing the contents the callback results, that wraps the supplied
 * function.
 */
export function promisify(method: Function, context?: mixed): Function {
  return async function(...args) {
    return new Promise((resolve, reject) => {
      args.push(function(error, ...callbackArgs) {
        if (error) {
          reject(error);
        }
        else {
          resolve(...callbackArgs);
        }
      });

      method.apply(context, args);
    })
  }
}

/**
 * It may be necessary to read GraphQL Lattice preferences from the nearest
 * `package.json` object to the excuting code. `getLatticePrefs()` does this
 * and merges any subsequently found options in said file on top of the
 * default values specified here in this file.
 *
 * @method utils~⌾⠀getLatticePrefs
 * @since 2.13.0
 *
 * @return {Object} an object containing at least the defaults plus any other
 * values specified in `package.json`
 */
export function getLatticePrefs(readPkgUpOpts: ?Object): Object {
  let { pkg } = readPkg(readPkgUpOpts)
  let options = {
    ModuleParser: {
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
      failOnError: false
    }
  }

  if (pkg.lattice) {
    merge(options, pkg.lattice || {})
  }

  return options;
}

/**
 * A small near pass-thru facility for logging within Lattice such that error
 * objects supplied get mapped to their message unless `LATTICE_ERRORS=STACK`
 * is set in `process.env`.
 *
 * Note the order of log levels for Lattice may be somewhat non-standard. Info
 * has been taken out of flow and placed above error to solve issues with jest
 * logging.
 *
 * @memberof utils
 * @type Object
 * @static
 */
export const LatticeLogs = {
  get LOG(): string { return 'log' },

  get WARN(): string { return 'warn' },

  get ERROR(): string { return 'error' },

  get INFO(): string { return 'info' },

  get TRACE(): string { return 'trace' },

  /**
   * Ordering of log levels for LatticeLogs. `INFO` is a non error log level
   * that is non-crucial and appears if LATTICE_LOGLEVEL is set to `INFO` or
   * `TRACE`
   */
  get LEVELS(): Array<string> {
    const ll = LatticeLogs

    return [ll.LOG, ll.WARN, ll.ERROR, ll.INFO, ll.TRACE]
  },

  equalOrBelow(testedLevel: string, lessThan: string = 'error') {
    const ll = LatticeLogs

    return ll.LEVELS.indexOf(testedLevel) <= ll.LEVELS.indexOf(lessThan)
  },

  atLeast(testedLevel: string, atLeastLevel: string): boolean {
    const ll = LatticeLogs

    return ll.LEVELS.indexOf(testedLevel) >= ll.LEVELS.indexOf(atLeastLevel)
  },

  /**
   * All arguments of any logging function in `LatticeLogs` get passed through
   * this function first to modify or alter the type of value being logged.
   *
   * @param {mixed} arg the argument being passed to the `map()` function
   * @param {number} index the index in the array of arguments
   * @param {Array<mixed>} array the array containing this element
   */
  argMapper(arg: mixed, index: number, array: Array<mixed>): mixed {
    let isError = typeOf(arg) === Error.name
    let showStack = /\bSTACK\b/i.test(process.env.LATTICE_ERRORS || '')

    // $FlowFixMe
    return !isError ? arg : (showStack ? arg : arg.message)
  },

  /** A function that, when it returns true, will cause logging to be skipped */
  failFast(logLevel: ?string, lessThan: ?string) {
    const ll = LatticeLogs

    if (logLevel) {
      let compareTo = lessThan || process.env.LATTICE_LOGLEVEL || ll.ERROR
      if (!ll.equalOrBelow(logLevel, compareTo)) return true
    }

    return /\b(NONE|OFF|NO|0)\b/i.test(process.env.LATTICE_ERRORS || '')
  },

  /** Pass-thru to console.log; arguments parsed via `argMapper` */
  log(...args: Array<mixed>) {
    if (LatticeLogs.failFast(LatticeLogs.LOG)) return;
    console.log(...args.map(LatticeLogs.argMapper))
  },

  /** Pass-thru to console.warn; arguments parsed via `argMapper` */
  warn(...args: Array<mixed>) {
    if (LatticeLogs.failFast(LatticeLogs.WARN)) return;
    console.warn(...args.map(LatticeLogs.argMapper))
  },

  /** Pass-thru to console.error; arguments parsed via `argMapper` */
  error(...args: Array<mixed>) {
    if (LatticeLogs.failFast(LatticeLogs.ERROR)) return;
    console.error(...args.map(LatticeLogs.argMapper))
  },

  /** Pass-thru to console.info; arguments parsed via `argMapper` */
  info(...args: Array<mixed>) {
    if (LatticeLogs.failFast(LatticeLogs.INFO)) return;
    console.info(...args.map(LatticeLogs.argMapper))
  },

  /** Pass-thru to console.trace; arguments parsed via `argMapper` */
  trace(...args: Array<mixed>) {
    if (LatticeLogs.failFast(LatticeLogs.TRACE)) return;
    console.trace(...args.map(LatticeLogs.argMapper))
  },

  outWrite(
    chunk: string|Uint8Array|Buffer,
    encoding: ?string,
    callback: ?Function
  ) {
    if (LatticeLogs.failFast(LatticeLogs.LOG)) return
    // $FlowFixMe
    process.stdout.write(chunk, encoding, callback)
  },

  errWrite(
    chunk: string|Uint8Array|Buffer,
    encoding: ?string,
    callback: ?Function
  ) {
    if (LatticeLogs.failFast(LatticeLogs.ERROR)) return
    // $FlowFixMe
    process.stderr.write(chunk, encoding, callback)
  }
}


text:
'use strict';

var SymbolNode = require('../../expression/node/SymbolNode');
var isBoolean = require('../../util/boolean').isBoolean;
var argsToArray = require('../../util/array').argsToArray;
var ArgumentsError = require('../../error/ArgumentsError');

/**
 * Attach a transform function to math.filter
 * Adds a property transform containing the transform function.
 *
 * This transform adds support for equations as test function for math.filter,
 * so you can do something like 'filter([3, -2, 5], x > 0)'.
 * @param {Object} math
 */
module.exports = function (math) {
  var _filter = math.filter;

  _filter.transform = function (args, math, scope) {
    if (args.length !== 2) {
      throw new ArgumentsError('filter', arguments.length, 2);
    }

    var x = args[0].compile(math).eval(scope);
    var test;
    if (args[1] instanceof SymbolNode) {
      // a function pointer, like filter([3, -2, 5], myTestFunction);
      test = args[1].compile(math).eval(scope);
    }
    else {
      // an equation like filter([3, -2, 5], x > 0)

      // find an undefined symbol
      var _scope = scope || {};
      var symbol = args[1]
          .find({
            type: SymbolNode
          })
          .filter(function (symbol) {
            return !(symbol.name in math) && !(symbol.name in _scope);
          })[0];

      // create a test function for this equation
      var sub = Object.create(_scope);
      var eq = args[1].compile(math);
      if (symbol) {
        var name = symbol.name;
        test = function (x) {
          sub[name] = x;
          return eq.eval(sub);
        }
      }
      else {
        throw new Error('No undefined variable found in filter equation');
      }
    }

    return _filter(x, test);
  };

  math.filter.transform.rawArgs = true;
};


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Echium argentae Pau.

### Remarks
null


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpikeHurt : MonoBehaviour {

    /*public GameObject player1;
    public GameObject player2;

    public bool P1Spike;
    public bool P2Spike;

    public Transform P1spikeCheckPoint;
    public Transform P2spikeCheckPoint;
    public float spikeCheckRadius;
    public LayerMask whatIsSpike;*/

    // Use this for initialization
    void Start () {

	}

    // Update is called once per frame
    void Update ()
    {
       // StartCoroutine(count());
        /*
        P1Spike = Physics2D.OverlapCircle(P1spikeCheckPoint.position, spikeCheckRadius, whatIsSpike);
        P2Spike = Physics2D.OverlapCircle(P2spikeCheckPoint.position, spikeCheckRadius, whatIsSpike);

        if (P1Spike)
        {

            FindObjectOfType<GameManager>().HurtP1();

        }
        if (P2Spike)
        {
            FindObjectOfType<GameManager>().HurtP2();
        }*/
    }
    /*
        IEnumerator count()
        {
            //yield return new WaitForSeconds(1);
            P1Spike = Physics2D.OverlapCircle(P1spikeCheckPoint.position, spikeCheckRadius, whatIsSpike);
            P2Spike = Physics2D.OverlapCircle(P2spikeCheckPoint.position, spikeCheckRadius, whatIsSpike);

            while (P1Spike)
            {
                yield return new WaitForSeconds(1);
                FindObjectOfType<GameManager>().HurtP1();
                println("");
                yield return new WaitForSeconds(1);
                break;
            }
            if (P2Spike)
            {
                FindObjectOfType<GameManager>().HurtP2();
            }
            //yield return new WaitForSeconds(100);
        }*/

    //  IEnumerator
    IEnumerator OnTriggerEnter2D(Collider2D other)
    {
        /*if (other.tag == "Buddy")
        {
            */if (other.tag == "Buddy")
            {
                for (int i=0; i<2; i++)
                {
                    FindObjectOfType<GameManager>().HurtP1();
                    yield return new WaitForSeconds(1);
                }

            }/*
            FindObjectOfType<GameManager>().HurtP1();
            FindObjectOfType<GameManager>().HurtP1();*/

        //}
        if (other.tag == "Stela")
        {
            for (int i = 0; i < 2; i++)
            {
                FindObjectOfType<GameManager>().HurtP2();
                yield return new WaitForSeconds(1);
            }
        }
    }
}


text:
package org.vaadin.spring.samples.mvp.ui.component.nav;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import org.vaadin.spring.samples.mvp.util.JSONUtil;

import com.google.gwt.thirdparty.guava.common.reflect.TypeToken;

/**
 * Constructs a list of navigation beans from a JSON file on the classpath
 * @author Chris Phillipson (fastnsilver@gmail.com)
 *
 */
public class NavElementFactory {

    @SuppressWarnings("serial")
    public List<NavElement> getNavElements(String resource) {
        Type collectionType = new TypeToken<Collection<NavElement>>(){}.getType();
        List<NavElement> result = JSONUtil.restoreFromJson(resource, collectionType);
        return result;
    }

}


text:
package com.woorea.openstack.keystone.v3.model;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;

@JsonRootName("token")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Token implements Serializable {

	private String id;

	@JsonProperty("expires_at")
	private Calendar expiresAt;

	@JsonProperty("issued_at")
	private Calendar issuedAt;

	private List<String> methods;

	@JsonIgnoreProperties(ignoreUnknown=true)
	public static final class Domain {

		private String id;

		private String name;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	private Domain domain;

	@JsonIgnoreProperties(ignoreUnknown=true)
	public static final class Project {

		private Domain domain;

		private String id;

		private String name;

		public Domain getDomain() {
			return domain;
		}

		public void setDomain(Domain domain) {
			this.domain = domain;
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	private Project project;

	@JsonIgnoreProperties(ignoreUnknown=true)
	public static final class User {

		@JsonIgnoreProperties(ignoreUnknown=true)
		private static final class Domain {

			private String id;

			private String name;

			public String getId() {
				return id;
			}

			public void setId(String id) {
				this.id = id;
			}

			public String getName() {
				return name;
			}

			public void setName(String name) {
				this.name = name;
			}

		}

		private String id;

		private String name;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	private User user;

	@JsonIgnoreProperties(ignoreUnknown=true)
	public static final class Role {

		private String id;

		private String name;

	}

	private List<Role> roles;

	public static final class Service {

		public static final class Endpoint {

			private String id;

			private String url;

			private String region;

			private Boolean enabled;

			@JsonProperty("legacy_endpoint_id")
			private String legacyEndpointId;

			@JsonProperty("interface")
			private String iface;

			public String getId() {
				return id;
			}

			public void setId(String id) {
				this.id = id;
			}

			public String getUrl() {
				return url;
			}

			public void setUrl(String url) {
				this.url = url;
			}

			public String getRegion() {
				return region;
			}

			public void setRegion(String region) {
				this.region = region;
			}

			public Boolean getEnabled() {
				return enabled;
			}

			public void setEnabled(Boolean enabled) {
				this.enabled = enabled;
			}

			public String getLegacyEndpointId() {
				return legacyEndpointId;
			}

			public void setLegacyEndpointId(String legacyEndpointId) {
				this.legacyEndpointId = legacyEndpointId;
			}

			public String getInterface() {
				return iface;
			}

			public void setInterface(String iface) {
				this.iface = iface;
			}

		}

		private String id;

		private String type;

		private List<Endpoint> endpoints;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getType() {
			return type;
		}

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

		public List<Endpoint> getEndpoints() {
			return endpoints;
		}

		public void setEndpoints(List<Endpoint> endpoints) {
			this.endpoints = endpoints;
		}

	}

	private List<Service> catalog;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Calendar getExpiresAt() {
		return expiresAt;
	}

	public void setExpiresAt(Calendar expiresAt) {
		this.expiresAt = expiresAt;
	}

	public Calendar getIssuedAt() {
		return issuedAt;
	}

	public void setIssuedAt(Calendar issuedAt) {
		this.issuedAt = issuedAt;
	}

	public List<String> getMethods() {
		return methods;
	}

	public void setMethods(List<String> methods) {
		this.methods = methods;
	}

	public Domain getDomain() {
		return domain;
	}

	public void setDomain(Domain domain) {
		this.domain = domain;
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public List<Service> getCatalog() {
		return catalog;
	}

	public void setCatalog(List<Service> catalog) {
		this.catalog = catalog;
	}

	@Override
	public String toString() {
		return "Token [id=" + id + ", expiresAt=" + expiresAt + ", issuedAt="
				+ issuedAt + ", methods=" + methods + ", domain=" + domain
				+ ", project=" + project + ", user=" + user + ", roles="
				+ roles + ", catalog=" + catalog + "]";
	}

}


text:
import mock

from neutron.common import constants
from neutron.common import topics
from neutron import context
from neutron.db import agents_db
from neutron.db import api as db_api
from neutron.extensions import portbindings
from neutron.extensions import providernet as pnet
from neutron import manager
from neutron.openstack.common import timeutils
from neutron.plugins.ml2 import config as config
from neutron.plugins.ml2.drivers.l2pop import constants as l2_consts
from neutron.plugins.ml2 import managers
from neutron.plugins.ml2 import rpc
from neutron.tests.unit import test_db_plugin as test_plugin

HOST = 'my_l2_host'
L2_AGENT = {
    'binary': 'neutron-openvswitch-agent',
    'host': HOST,
    'topic': constants.L2_AGENT_TOPIC,
    'configurations': {'tunneling_ip': '20.0.0.1',
                       'tunnel_types': ['vxlan']},
    'agent_type': constants.AGENT_TYPE_OVS,
    'tunnel_type': [],
    'start_flag': True
}

L2_AGENT_2 = {
    'binary': 'neutron-openvswitch-agent',
    'host': HOST + '_2',
    'topic': constants.L2_AGENT_TOPIC,
    'configurations': {'tunneling_ip': '20.0.0.2',
                       'tunnel_types': ['vxlan']},
    'agent_type': constants.AGENT_TYPE_OVS,
    'tunnel_type': [],
    'start_flag': True
}

L2_AGENT_3 = {
    'binary': 'neutron-openvswitch-agent',
    'host': HOST + '_3',
    'topic': constants.L2_AGENT_TOPIC,
    'configurations': {'tunneling_ip': '20.0.0.2',
                       'tunnel_types': []},
    'agent_type': constants.AGENT_TYPE_OVS,
    'tunnel_type': [],
    'start_flag': True
}

PLUGIN_NAME = 'neutron.plugins.ml2.plugin.Ml2Plugin'
NOTIFIER = 'neutron.plugins.ml2.rpc.AgentNotifierApi'

class TestL2PopulationRpcTestCase(test_plugin.NeutronDbPluginV2TestCase):

    def setUp(self):
        # Enable the test mechanism driver to ensure that
        # we can successfully call through to all mechanism
        # driver apis.
        config.cfg.CONF.set_override('mechanism_drivers',
                                     ['openvswitch', 'linuxbridge',
                                      'l2population'],
                                     'ml2')
        super(TestL2PopulationRpcTestCase, self).setUp(PLUGIN_NAME)
        self.addCleanup(config.cfg.CONF.reset)

        self.adminContext = context.get_admin_context()

        self.type_manager = managers.TypeManager()
        self.notifier = rpc.AgentNotifierApi(topics.AGENT)
        self.callbacks = rpc.RpcCallbacks(self.notifier, self.type_manager)

        self.orig_supported_agents = l2_consts.SUPPORTED_AGENT_TYPES
        l2_consts.SUPPORTED_AGENT_TYPES = [constants.AGENT_TYPE_OVS]

        net_arg = {pnet.NETWORK_TYPE: 'vxlan',
                   pnet.SEGMENTATION_ID: '1'}
        self._network = self._make_network(self.fmt, 'net1', True,
                                           arg_list=(pnet.NETWORK_TYPE,
                                                     pnet.SEGMENTATION_ID,),
                                           **net_arg)

        notifier_patch = mock.patch(NOTIFIER)
        notifier_patch.start()

        self.fanout_topic = topics.get_topic_name(topics.AGENT,
                                                  topics.L2POPULATION,
                                                  topics.UPDATE)
        fanout = ('neutron.openstack.common.rpc.proxy.RpcProxy.fanout_cast')
        fanout_patch = mock.patch(fanout)
        self.mock_fanout = fanout_patch.start()

        cast = ('neutron.openstack.common.rpc.proxy.RpcProxy.cast')
        cast_patch = mock.patch(cast)
        self.mock_cast = cast_patch.start()

        uptime = ('neutron.plugins.ml2.drivers.l2pop.db.L2populationDbMixin.'
                  'get_agent_uptime')
        uptime_patch = mock.patch(uptime, return_value=190)
        uptime_patch.start()

        self.addCleanup(mock.patch.stopall)
        self.addCleanup(db_api.clear_db)

    def tearDown(self):
        l2_consts.SUPPORTED_AGENT_TYPES = self.orig_supported_agents
        super(TestL2PopulationRpcTestCase, self).tearDown()

    def _register_ml2_agents(self):
        callback = agents_db.AgentExtRpcCallback()
        callback.report_state(self.adminContext,
                              agent_state={'agent_state': L2_AGENT},
                              time=timeutils.strtime())
        callback.report_state(self.adminContext,
                              agent_state={'agent_state': L2_AGENT_2},
                              time=timeutils.strtime())
        callback.report_state(self.adminContext,
                              agent_state={'agent_state': L2_AGENT_3},
                              time=timeutils.strtime())

    def test_fdb_add_called(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port1:
                with self.port(subnet=subnet,
                               arg_list=(portbindings.HOST_ID,),
                               **host_arg):
                    p1 = port1['port']

                    device = 'tap' + p1['id']

                    self.mock_fanout.reset_mock()
                    self.callbacks.update_device_up(self.adminContext,
                                                    agent_id=HOST,
                                                    device=device)

                    p1_ips = [p['ip_address'] for p in p1['fixed_ips']]
                    expected = {'args':
                                {'fdb_entries':
                                 {p1['network_id']:
                                  {'ports':
                                   {'20.0.0.1': [[p1['mac_address'],
                                                  p1_ips[0]]]},
                                   'network_type': 'vxlan',
                                   'segment_id': 1}}},
                                'namespace': None,
                                'method': 'add_fdb_entries'}

                    self.mock_fanout.assert_called_with(
                        mock.ANY, expected, topic=self.fanout_topic)

    def test_fdb_add_not_called_type_local(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST + '_3'}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port1:
                with self.port(subnet=subnet,
                               arg_list=(portbindings.HOST_ID,),
                               **host_arg):
                    p1 = port1['port']

                    device = 'tap' + p1['id']

                    self.mock_fanout.reset_mock()
                    self.callbacks.update_device_up(self.adminContext,
                                                    agent_id=HOST,
                                                    device=device)

                    self.assertFalse(self.mock_fanout.called)

    def test_fdb_add_two_agents(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST,
                        'admin_state_up': True}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID, 'admin_state_up',),
                           **host_arg) as port1:
                host_arg = {portbindings.HOST_ID: HOST + '_2',
                            'admin_state_up': True}
                with self.port(subnet=subnet,
                               arg_list=(portbindings.HOST_ID,
                                         'admin_state_up',),
                               **host_arg) as port2:
                    p1 = port1['port']
                    p2 = port2['port']

                    device = 'tap' + p1['id']

                    self.mock_cast.reset_mock()
                    self.mock_fanout.reset_mock()
                    self.callbacks.update_device_up(self.adminContext,
                                                    agent_id=HOST,
                                                    device=device)

                    p1_ips = [p['ip_address'] for p in p1['fixed_ips']]
                    p2_ips = [p['ip_address'] for p in p2['fixed_ips']]

                    expected1 = {'args':
                                 {'fdb_entries':
                                  {p1['network_id']:
                                   {'ports':
                                    {'20.0.0.2': [constants.FLOODING_ENTRY,
                                                  [p2['mac_address'],
                                                   p2_ips[0]]]},
                                    'network_type': 'vxlan',
                                    'segment_id': 1}}},
                                 'namespace': None,
                                 'method': 'add_fdb_entries'}

                    topic = topics.get_topic_name(topics.AGENT,
                                                  topics.L2POPULATION,
                                                  topics.UPDATE,
                                                  HOST)

                    self.mock_cast.assert_called_with(mock.ANY,
                                                      expected1,
                                                      topic=topic)

                    expected2 = {'args':
                                 {'fdb_entries':
                                  {p1['network_id']:
                                   {'ports':
                                    {'20.0.0.1': [constants.FLOODING_ENTRY,
                                                  [p1['mac_address'],
                                                   p1_ips[0]]]},
                                    'network_type': 'vxlan',
                                    'segment_id': 1}}},
                                 'namespace': None,
                                 'method': 'add_fdb_entries'}

                    self.mock_fanout.assert_called_with(
                        mock.ANY, expected2, topic=self.fanout_topic)

    def test_fdb_add_called_two_networks(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST + '_2'}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port1:
                with self.subnet(cidr='10.1.0.0/24') as subnet2:
                    with self.port(subnet=subnet2,
                                   arg_list=(portbindings.HOST_ID,),
                                   **host_arg):
                        host_arg = {portbindings.HOST_ID: HOST}
                        with self.port(subnet=subnet,
                                       arg_list=(portbindings.HOST_ID,),
                                       **host_arg) as port3:
                            p1 = port1['port']
                            p3 = port3['port']

                            device = 'tap' + p3['id']

                            self.mock_cast.reset_mock()
                            self.mock_fanout.reset_mock()
                            self.callbacks.update_device_up(
                                self.adminContext, agent_id=HOST,
                                device=device)

                            p1_ips = [p['ip_address']
                                      for p in p1['fixed_ips']]
                            expected1 = {'args':
                                         {'fdb_entries':
                                          {p1['network_id']:
                                           {'ports':
                                            {'20.0.0.2':
                                             [constants.FLOODING_ENTRY,
                                              [p1['mac_address'],
                                               p1_ips[0]]]},
                                            'network_type': 'vxlan',
                                            'segment_id': 1}}},
                                         'namespace': None,
                                         'method': 'add_fdb_entries'}

                            topic = topics.get_topic_name(topics.AGENT,
                                                          topics.L2POPULATION,
                                                          topics.UPDATE,
                                                          HOST)

                            self.mock_cast.assert_called_with(mock.ANY,
                                                              expected1,
                                                              topic=topic)

                            p3_ips = [p['ip_address']
                                      for p in p3['fixed_ips']]
                            expected2 = {'args':
                                         {'fdb_entries':
                                          {p1['network_id']:
                                           {'ports':
                                            {'20.0.0.1':
                                             [constants.FLOODING_ENTRY,
                                              [p3['mac_address'],
                                               p3_ips[0]]]},
                                            'network_type': 'vxlan',
                                            'segment_id': 1}}},
                                         'namespace': None,
                                         'method': 'add_fdb_entries'}

                            self.mock_fanout.assert_called_with(
                                mock.ANY, expected2,
                                topic=self.fanout_topic)

    def test_fdb_remove_called_from_rpc(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg):
                with self.port(subnet=subnet,
                               arg_list=(portbindings.HOST_ID,),
                               **host_arg) as port:
                    p1 = port['port']

                    device = 'tap' + p1['id']

                    self.mock_fanout.reset_mock()
                    self.callbacks.update_device_up(self.adminContext,
                                                    agent_id=HOST,
                                                    device=device)

                    self.callbacks.update_device_down(self.adminContext,
                                                      agent_id=HOST,
                                                      device=device)

                    p1_ips = [p['ip_address'] for p in p1['fixed_ips']]
                    expected = {'args':
                                {'fdb_entries':
                                 {p1['network_id']:
                                  {'ports':
                                   {'20.0.0.1': [[p1['mac_address'],
                                                  p1_ips[0]]]},
                                   'network_type': 'vxlan',
                                   'segment_id': 1}}},
                                'namespace': None,
                                'method': 'remove_fdb_entries'}

                    self.mock_fanout.assert_called_with(
                        mock.ANY, expected, topic=self.fanout_topic)

    def test_fdb_remove_called(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}
            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg):

                with self.port(subnet=subnet,
                               arg_list=(portbindings.HOST_ID,),
                               **host_arg) as port:
                    p1 = port['port']

                    device = 'tap' + p1['id']

                    self.mock_fanout.reset_mock()
                    self.callbacks.update_device_up(self.adminContext,
                                                    agent_id=HOST,
                                                    device=device)

                p1_ips = [p['ip_address'] for p in p1['fixed_ips']]
                expected = {'args':
                            {'fdb_entries':
                             {p1['network_id']:
                              {'ports':
                               {'20.0.0.1': [[p1['mac_address'],
                                              p1_ips[0]]]},
                               'network_type': 'vxlan',
                               'segment_id': 1}}},
                            'namespace': None,
                            'method': 'remove_fdb_entries'}

                self.mock_fanout.assert_any_call(
                    mock.ANY, expected, topic=self.fanout_topic)

    def test_fdb_remove_called_last_port(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}

            with self.port(subnet=subnet,
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port:
                p1 = port['port']

                device = 'tap' + p1['id']

                self.callbacks.update_device_up(self.adminContext,
                                                agent_id=HOST,
                                                device=device)

            p1_ips = [p['ip_address'] for p in p1['fixed_ips']]
            expected = {'args':
                        {'fdb_entries':
                         {p1['network_id']:
                          {'ports':
                           {'20.0.0.1': [constants.FLOODING_ENTRY,
                                         [p1['mac_address'],
                                          p1_ips[0]]]},
                           'network_type': 'vxlan',
                           'segment_id': 1}}},
                        'namespace': None,
                        'method': 'remove_fdb_entries'}

            self.mock_fanout.assert_any_call(
                mock.ANY, expected, topic=self.fanout_topic)

    def test_fixed_ips_changed(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}
            with self.port(subnet=subnet, cidr='10.0.0.0/24',
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port1:
                p1 = port1['port']

                device = 'tap' + p1['id']

                self.callbacks.update_device_up(self.adminContext,
                                                agent_id=HOST,
                                                device=device)

                self.mock_fanout.reset_mock()

                data = {'port': {'fixed_ips': [{'ip_address': '10.0.0.2'},
                                               {'ip_address': '10.0.0.10'}]}}
                req = self.new_update_request('ports', data, p1['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 2)

                add_expected = {'args':
                                {'fdb_entries':
                                 {'chg_ip':
                                  {p1['network_id']:
                                   {'20.0.0.1':
                                    {'after': [[p1['mac_address'],
                                                '10.0.0.10']]}}}}},
                                'namespace': None,
                                'method': 'update_fdb_entries'}

                self.mock_fanout.assert_any_call(
                    mock.ANY, add_expected, topic=self.fanout_topic)

                self.mock_fanout.reset_mock()

                data = {'port': {'fixed_ips': [{'ip_address': '10.0.0.2'},
                                               {'ip_address': '10.0.0.16'}]}}
                req = self.new_update_request('ports', data, p1['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 2)

                upd_expected = {'args':
                                {'fdb_entries':
                                 {'chg_ip':
                                  {p1['network_id']:
                                   {'20.0.0.1':
                                    {'before': [[p1['mac_address'],
                                                 '10.0.0.10']],
                                     'after': [[p1['mac_address'],
                                                '10.0.0.16']]}}}}},
                                'namespace': None,
                                'method': 'update_fdb_entries'}

                self.mock_fanout.assert_any_call(
                    mock.ANY, upd_expected, topic=self.fanout_topic)

                self.mock_fanout.reset_mock()

                data = {'port': {'fixed_ips': [{'ip_address': '10.0.0.16'}]}}
                req = self.new_update_request('ports', data, p1['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 1)

                del_expected = {'args':
                                {'fdb_entries':
                                 {'chg_ip':
                                  {p1['network_id']:
                                   {'20.0.0.1':
                                    {'before': [[p1['mac_address'],
                                                 '10.0.0.2']]}}}}},
                                'namespace': None,
                                'method': 'update_fdb_entries'}

                self.mock_fanout.assert_any_call(
                    mock.ANY, del_expected, topic=self.fanout_topic)

    def test_no_fdb_updates_without_port_updates(self):
        self._register_ml2_agents()

        with self.subnet(network=self._network) as subnet:
            host_arg = {portbindings.HOST_ID: HOST}
            with self.port(subnet=subnet, cidr='10.0.0.0/24',
                           arg_list=(portbindings.HOST_ID,),
                           **host_arg) as port1:
                p1 = port1['port']

                device = 'tap' + p1['id']

                self.callbacks.update_device_up(self.adminContext,
                                                agent_id=HOST,
                                                device=device)
                p1['status'] = 'ACTIVE'
                self.mock_fanout.reset_mock()

                fanout = ('neutron.plugins.ml2.drivers.l2pop.rpc.'
                          'L2populationAgentNotifyAPI._notification_fanout')
                fanout_patch = mock.patch(fanout)
                mock_fanout = fanout_patch.start()

                plugin = manager.NeutronManager.get_plugin()
                plugin.update_port(self.adminContext, p1['id'], port1)

                self.assertFalse(mock_fanout.called)
                fanout_patch.stop()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.3.3: v8::Date Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

V8 API Reference Guide for node.js v0.3.3

Main Page

Namespaces

Classes

Files

Examples

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

v8

Date

Public Member Functions |
Static Public Member Functions |
List of all members

v8::Date Class Reference

#include <v8.h>

Inheritance diagram for v8::Date:

  <map id="v8::Date_map" name="v8::Date_map">
<area href="classv8_1_1_value.html" alt="v8::Value" shape="rect" coords="0,56,65,80"/>
<area href="classv8_1_1_data.html" alt="v8::Data" shape="rect" coords="0,0,65,24"/>
</map>

Public Member Functions

V8EXPORT double 	NumberValue () const

 Public Member Functions inherited from v8::Value

V8EXPORT bool 	IsUndefined () const

V8EXPORT bool 	IsNull () const

V8EXPORT bool 	IsTrue () const

V8EXPORT bool 	IsFalse () const

bool 	IsString () const

V8EXPORT bool 	IsFunction () const

V8EXPORT bool 	IsArray () const

V8EXPORT bool 	IsObject () const

V8EXPORT bool 	IsBoolean () const

V8EXPORT bool 	IsNumber () const

V8EXPORT bool 	IsExternal () const

V8EXPORT bool 	IsInt32 () const

V8EXPORT bool 	IsUint32 () const

V8EXPORT bool 	IsDate () const

V8EXPORT bool 	IsRegExp () const

V8EXPORT Local< Boolean > 	ToBoolean () const

V8EXPORT Local< Number > 	ToNumber () const

V8EXPORT Local< String > 	ToString () const

V8EXPORT Local< String > 	ToDetailString () const

V8EXPORT Local< Object > 	ToObject () const

V8EXPORT Local< Integer > 	ToInteger () const

V8EXPORT Local< Uint32 > 	ToUint32 () const

V8EXPORT Local< Int32 > 	ToInt32 () const

V8EXPORT Local< Uint32 > 	ToArrayIndex () const

V8EXPORT bool 	BooleanValue () const

V8EXPORT double 	NumberValue () const

V8EXPORT int64_t 	IntegerValue () const

V8EXPORT uint32_t 	Uint32Value () const

V8EXPORT int32_t 	Int32Value () const

V8EXPORT bool 	Equals (Handle< Value > that) const

V8EXPORT bool 	StrictEquals (Handle< Value > that) const

Static Public Member Functions

static V8EXPORT Local< Value > 	New (double time)

static Date * 	Cast (v8::Value *obj)

static V8EXPORT void 	DateTimeConfigurationChangeNotification ()

Detailed Description

An instance of the built-in Date constructor (ECMA-262, 15.9).

Member Function Documentation

          static V8EXPORT void v8::Date::DateTimeConfigurationChangeNotification
          (
          	)

static

Notification that the embedder has changed the time zone, daylight savings time, or other date / time configuration parameters. V8 keeps a cache of various values used for date / time computation. This notification will reset those cached values for the current context so that date / time configuration changes would be reflected in the Date object.

This API should not be called more than needed as it will negatively impact the performance of date operations.

          V8EXPORT double v8::Date::NumberValue
          (
          	)
           const

A specialization of Value::NumberValue that is more efficient because we know the structure of this object.

The documentation for this class was generated from the following file:

deps/v8/include/v8.h

<address class="footer">
Generated on Tue Aug 11 2015 23:46:45 for V8 API Reference Guide for node.js v0.3.3 by

 1.8.9.1
</address>


text:
package be.trojkasoftware.android.diagramming;

import java.util.EventObject;

public class ItemMovedEvent extends EventObject {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public ItemMovedEvent(Object source) {
        super(source);
    }
}


text:
Add-Type -Path "c:\Program Files\ByteScout Text Recognition SDK\net40\ByteScout.TextRecognition.dll"

$InputDocument = "bad-quality.png"
$OutputDocument = ".\result.txt"

# Create and activate TextRecognizer instance
$textRecognizer = New-Object ByteScout.TextRecognition.TextRecognizer
$textRecognizer.RegistrationName = "demo"
$textRecognizer.RegistrationKey = "demo"

try {
    # Load document (image or PDF)
    $textRecognizer.LoadDocument($InputDocument)

    # Set the location of OCR language data files
    $textRecognizer.OCRLanguageDataFolder = "c:\Program Files\ByteScout Text Recognition SDK\ocrdata_fast\"

    # Set OCR language.
    # "eng" for english, "deu" for German, "fra" for French, "spa" for Spanish, etc. - according to files in "ocrdata" folder
    # Find more language files at https://github.com/bytescout/ocrdata
    $textRecognizer.OCRLanguage = "eng"

    # Add error corrections that will be applied after the recognition.
    $textRecognizer.Corrections.Add("Tut ", "Test ")
    $textRecognizer.Corrections.Add("Recog\w{1,}on", "Recognition", $true) # regular expression (regex) replacement

    # Recognize text from all pages and save it to file
    $textRecognizer.SaveText($OutputDocument)

    # Open the result file in default associated application (for demo purposes)
    & $OutputDocument
}
catch {
    # Display exception
    Write-Host $_.Exception.Message
}

$textRecognizer.Dispose()


text:
package com.google.common.collect;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.annotations.GwtCompatible;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;

/**
 * Unit test for {@link ComparisonChain}.
 *
 * @author Kevin Bourrillion
 */
@GwtCompatible
public class ComparisonChainTest extends TestCase {
  private static final DontCompareMe DONT_COMPARE_ME = new DontCompareMe();

  private static class DontCompareMe implements Comparable<DontCompareMe> {
    @Override
    public int compareTo(DontCompareMe o) {
      throw new AssertionFailedError();
    }
  }

  @SuppressWarnings("deprecation")
  public void testCompareBooleans() {
    assertThat(
            ComparisonChain.start()
                .compare(true, true)
                .compare(true, Boolean.TRUE)
                .compare(Boolean.TRUE, true)
                .compare(Boolean.TRUE, Boolean.TRUE)
                .result())
        .isEqualTo(0);
  }

  public void testDegenerate() {
    // kinda bogus, but who cares?
    assertThat(ComparisonChain.start().result()).isEqualTo(0);
  }

  public void testOneEqual() {
    assertThat(ComparisonChain.start().compare("a", "a").result()).isEqualTo(0);
  }

  public void testOneEqualUsingComparator() {
    assertThat(ComparisonChain.start().compare("a", "A", String.CASE_INSENSITIVE_ORDER).result())
        .isEqualTo(0);
  }

  public void testManyEqual() {
    assertThat(
            ComparisonChain.start()
                .compare(1, 1)
                .compare(1L, 1L)
                .compareFalseFirst(true, true)
                .compare(1.0, 1.0)
                .compare(1.0f, 1.0f)
                .compare("a", "a", Ordering.usingToString())
                .result())
        .isEqualTo(0);
  }

  public void testShortCircuitLess() {
    assertThat(
            ComparisonChain.start()
                .compare("a", "b")
                .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
                .result())
        .isLessThan(0);
  }

  public void testShortCircuitGreater() {
    assertThat(
            ComparisonChain.start()
                .compare("b", "a")
                .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
                .result())
        .isGreaterThan(0);
  }

  public void testShortCircuitSecondStep() {
    assertThat(
            ComparisonChain.start()
                .compare("a", "a")
                .compare("a", "b")
                .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
                .result())
        .isLessThan(0);
  }

  public void testCompareFalseFirst() {
    assertThat(ComparisonChain.start().compareFalseFirst(true, true).result()).isEqualTo(0);
    assertThat(ComparisonChain.start().compareFalseFirst(true, false).result()).isGreaterThan(0);
    assertThat(ComparisonChain.start().compareFalseFirst(false, true).result()).isLessThan(0);
    assertThat(ComparisonChain.start().compareFalseFirst(false, false).result()).isEqualTo(0);
  }

  public void testCompareTrueFirst() {
    assertThat(ComparisonChain.start().compareTrueFirst(true, true).result()).isEqualTo(0);
    assertThat(ComparisonChain.start().compareTrueFirst(true, false).result()).isLessThan(0);
    assertThat(ComparisonChain.start().compareTrueFirst(false, true).result()).isGreaterThan(0);
    assertThat(ComparisonChain.start().compareTrueFirst(false, false).result()).isEqualTo(0);
  }
}


text:
package org.pathvisio.desktop.gex;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import org.bridgedb.DataSource;
import org.bridgedb.IDMapperException;
import org.bridgedb.Xref;
import org.bridgedb.rdb.construct.DBConnector;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.data.DataException;
import org.pathvisio.data.DataInterface;
import org.pathvisio.data.IRow;
import org.pathvisio.data.ISample;

/**
 * Responsible for creating and querying a pgex database.
 * SimpleGex wraps SQL statements in methods,
 * so the rest of the apps don't need to know the
 * details of the Database schema.
 * For this, SimpleGex uses the generic JDBC interface.
 *
 * It delegates dealing with the differences between Derby, Hsqldb etc.
 * to a DBConnector instance.
 * You need to pass a correct DBConnector instance at creation of
 * SimpleGex.
 *
 * In the PathVisio GUI environment, use GexManager
 * to create and connect to a centralized Gex.
 * This will also automatically
 * find the right DBConnector from the preferences.
 *
 * In a head-less or test environment, you can bypass GexManager
 * to create or connect to one or more databases of any type.
 */
//TODO: add function to query # of samples
public class SimpleGex implements DataInterface
{
	private static final int GEX_COMPAT_VERSION = 2; //Preferred schema version
	private static final int SAMPLE_NAME_LEN = 50; // max length of sample names

	private Connection con;
	private DBConnector dbConnector;
	private int commitCount = 0;

	private static CachedData cachedData;

	/**
	 * Get the {@link Connection} to the Expression-data database
	 * @deprecated Shouldn't be exposed
	 */
	public Connection getCon() { return con; }
	/**
	 * Check whether a connection to the database exists
	 * @return	true is a connection exists, false if not
	 */
	public boolean isConnected() { return con != null; }

	private String dbName;
	/**
	 * Get the database name of the expression data currently loaded
	 */
	public String getDbName() { return dbName; }

	/**
	 * Set the database name of the expression data currently loaded
	 * (Connection is not reset)
	 */
	private void setDbName(String name) { dbName = name; }

	// cache of samples
	private Map<Integer, Sample> samples;

	PreparedStatement pstSample = null;
	PreparedStatement pstExpr = null;

	public void prepare() throws SQLException
	{
		pstSample = con.prepareStatement(
				" INSERT INTO SAMPLES " +
				"	(idSample, name, dataType)  " +
		" VALUES (?, ?, ?)		  ");
		pstExpr = con.prepareStatement(
				"INSERT INTO expression			" +
				"	(id, code,      			" +
				"	 idSample, data, groupId)	" +
		"VALUES	(?, ?, ?, ?, ?)			");
	}

	/**
	 * add a Sample to the db.
	 * Must call preprare() before.
	 */
	public void addSample(int sampleId, String value, int type) throws SQLException
	{
		assert (pstSample != null);
		if (value.length() >= SAMPLE_NAME_LEN)
			throw new IllegalArgumentException ("Sample name can't be longer than " + SAMPLE_NAME_LEN + " chars");
		pstSample.setInt(1, sampleId);
		pstSample.setString(2, value);
		pstSample.setInt(3, type);
		pstSample.execute();
		con.commit();
	}

	/**
	 * Add an expression row to the db. Must call prepare() before.
	 */
	public void addExpr(Xref ref, String idSample, String value, int group)
		throws SQLException
	{
		assert (pstExpr != null);
		pstExpr.setString(1, ref.getId());
		pstExpr.setString(2, ref.getDataSource().getSystemCode());
		pstExpr.setString(3, idSample);
		//TODO: this is a hack.
		// Proper solution: ask user which columns contain data
		// don't even try to import annotation and other stuff
		// give an exception if a data value is longer than 50
		String truncValue = value;
		if (value.length() > 50) truncValue = value.substring(0, 50);
		pstExpr.setString(4, truncValue);
		pstExpr.setInt(5, group);
		pstExpr.execute();
		if (++commitCount % 1000 == 0) con.commit();
	}

	public ISample getSample(int id) throws DataException
	{
		return getSamples().get(id);
	}

	public Sample findSample(String name) throws DataException
	{
		//TODO: create a map for faster lookups.
		for (Sample s : samples.values())
		{
			if (s.getName().equals(name)) return s;
		}
		return null;
	}

	/**
	 * Returns samples as a list, ordered by Id.
	 * <p>
	 * Note that there is no guarantee that the index of a Sample in the list
	 * is equal to the id of that sample.
	 * In other words, result.get(n).getId() < result.get(n+1).getId(), but
	 * NOT: result.get(n).getId() == n
	 */
	@Override
	public List<? extends ISample> getOrderedSamples() throws DataException
	{
		List<ISample> result = new ArrayList<ISample>(getSamples().values());
		Collections.sort (result);
		return result;
	}

	/**
	 * Reads a list of Samples from the database,
	 * and returns them, indexed by key.
	 *
	 * This data is cached, so you can safely call this repeatedly.
	 */
	@Override
	public Map<Integer, ? extends ISample> getSamples() throws DataException
	{
		if(samples == null)
		{
			try {
				ResultSet r = con.createStatement().executeQuery(
						"SELECT idSample, name, dataType FROM samples"
				);
				samples = new HashMap<Integer, Sample>();
				while(r.next())
				{
					int id = r.getInt(1);
					samples.put(id, new Sample(id, r.getString(2), "undefined", r.getInt(3)));
				}
			} catch (SQLException e) {
				throw new DataException ("SQL exception while setting samples", e);
			}
		}
		return samples;
	}

	@Override
	public List<String> getSampleNames() {
		return getSampleNames(-1);
	}

	@Override
	public List<String> getSampleNames(int dataType) {
		List<String> names = new ArrayList<String>();
		List<Sample> sorted = new ArrayList<Sample>(samples.values());
		Collections.sort(sorted);
		for(Sample s : sorted) {
			if(dataType == s.getDataType() || dataType == -1)
				names.add(s.getName());
		}
		return names;
	}

	PreparedStatement pst1 = null;
	private PreparedStatement getPst1() throws SQLException
	{
		if (pst1 == null)
		{
			pst1 = con.prepareStatement(
			"SELECT id, code, data, idSample, groupId FROM expression " +
			" WHERE id = ? AND code = ?");
		}
		return pst1;
	}

	PreparedStatement pst2 = null;
	private PreparedStatement getPst2() throws SQLException
	{
		if (pst2 == null)
		{
			pst2 = con.prepareStatement("SELECT code FROM expression GROUP BY code");
		}
		return pst2;
	}

	/**
	 * get all datasouces used in this gex.
	 */
	@Override
	public Set<DataSource> getUsedDatasources() throws DataException
	{
		try
		{
			Set<DataSource> destFilter = new HashSet<DataSource>();
			PreparedStatement pst = getPst2();
			ResultSet r = pst.executeQuery();
			while (r.next())
			{
				destFilter.add(DataSource.getBySystemCode(r.getString(1)));
			}
			return destFilter;
		}
		catch (SQLException ex)
		{
			throw new DataException (ex);
		}
	}

	@Override
	public Collection<? extends IRow> getData(Set<Xref> destRefs) throws DataException
	{
		try
		{
			PreparedStatement pst = getPst1();
			Map<Integer, ReporterData> groupData = new HashMap<Integer, ReporterData>();

			for (Xref destRef : destRefs)
			{
				pst.setString(1, destRef.getId());
				pst.setString(2, destRef.getDataSource().getSystemCode());
				ResultSet r = pst.executeQuery();

				//r contains all data mapping to the destref
				//there could be multiple data items
				while(r.next())
				{
					int group = r.getInt("groupId");
					ReporterData data = groupData.get(group);
					if(data == null) {
						data = new ReporterData(destRef, group);
						groupData.put(group, data);
					}
					int idSample = r.getInt("idSample");
					data.setSampleData(samples.get(idSample), r.getString("data"));
				}
			}
			return groupData.values();
		}
		catch (SQLException ex)
		{
			throw new DataException(ex);
		}
	}

	/**
	 * Connects to the Expression database with
	 * option to remove the old database
	 * Will use the passed connector type (of which a new instance is created)
	 * @param 	create true if the old database has to be removed, false for just connecting
	 */
	public SimpleGex(String dbName, boolean create, DBConnector connector) throws DataException
	{
		this.dbName = dbName;
		try
		{
			dbConnector = connector.getClass().newInstance();
		}
		catch (InstantiationException e)
		{
			throw new DataException (e);
		}
		catch (IllegalAccessException e)
		{
			throw new DataException (e);
		}

		dbConnector.setDbType(DBConnector.TYPE_GEX);
		if(create)
		{
			createNewGex(dbName);
		}
		else
		{
			try
			{
				con = dbConnector.createConnection(dbName, DBConnector.PROP_NONE);
			}
			catch (IDMapperException ex)
			{
				throw new DataException (ex);
			}
			getSamples(); // init samples cache
		}
	}

	/**
	 * Close the connection to the Expression database, with option to execute the 'SHUTDOWN COMPACT'
	 * statement before calling {@link Connection#close()}
	 */
	public void close() throws DataException
	{
		if(con != null)
		{
			try
			{
				dbConnector.closeConnection(con);
				con.close();
			}
			catch (IDMapperException e)
			{
				throw new DataException (e);
			}
			catch (SQLException ex)
			{
				throw new DataException (ex);
			}
			con = null;
		}
	}

	/**
	 * Create a new database with the given name. This includes creating tables.
	 * @param dbName The name of the database to create
	 * @return A connection to the newly created database
	 * @throws Exception
	 * @throws Exception
	 */
	public final void createNewGex(String dbName) throws DataException
	{
		try
		{
			con = dbConnector.createConnection(dbName, DBConnector.PROP_RECREATE);
			this.dbName = dbName;
			createGexTables();
		}
		catch (IDMapperException ex)
		{
			throw new DataException(ex);
		}
	}

	/**
	 * Excecutes several SQL statements to create the tables and indexes for storing
	 * the expression data
	 */
	protected void createGexTables() throws IDMapperException
	{
		try
		{
			con.setReadOnly(false);
			Statement sh = con.createStatement();
			try { sh.execute("DROP TABLE info"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); }
			try { sh.execute("DROP TABLE samples"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); }
			try { sh.execute("DROP TABLE expression"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); }

			sh.execute(
					"CREATE TABLE					" +
					"		info							" +
					"(	  version INTEGER PRIMARY KEY		" +
					")");
			sh.execute( //Add compatibility version of GEX
					"INSERT INTO info VALUES ( " + GEX_COMPAT_VERSION + ")");
			sh.execute(
					"CREATE TABLE                    " +
					"		samples							" +
					" (   idSample INTEGER PRIMARY KEY,		" +
					"     name VARCHAR(" + SAMPLE_NAME_LEN + "),					" +
					"	  dataType INTEGER					" +
			" )										");

			sh.execute(
					"CREATE TABLE					" +
					"		expression						" +
					" (   id VARCHAR(50),					" +
					"     code VARCHAR(50),					" +
					"     idSample INTEGER,					" +
					"     data VARCHAR(50),					" +
					"	  groupId INTEGER 					" +
	//				"     PRIMARY KEY (id, code, idSample, data)	" +
			")										");
			con.setAutoCommit(false);
			commitCount = 0;
		}
		catch (SQLException e)
		{
			throw new IDMapperException (e);
		}
	}

	/**
	 * Creates indices for a newly created expression database.
	 * @param con The connection to the expression database
	 * @throws SQLException
	 */
	public void createGexIndices() throws IDMapperException
	{
		try
		{
			con.setReadOnly(false);
			Statement sh = con.createStatement();
			sh.execute(
					"CREATE INDEX i_expression_id " +
			"ON expression(id)			 ");
			sh.execute(
					"CREATE INDEX i_expression_idSample " +
			"ON expression(idSample)	 ");
			sh.execute(
					"CREATE INDEX i_expression_data " +
			"ON expression(data)	     ");
			sh.execute(
					"CREATE INDEX i_expression_code " +
			"ON expression(code)	 ");
			sh.execute(
					"CREATE INDEX i_expression_groupId" +
			" ON expression(groupId)	");
		}
		catch (SQLException e)
		{
			// wrap up the sql exception
			throw new IDMapperException (e);
		}
	}

	/**
	 * Run this after insterting all sample / expression data
	 * once, to defragment the db and create indices.
	 * This method closes the current database connection in order
	 * for the {@link DBConnector} to clean up.
	 */
	public void finalize() throws IDMapperException
	{
		try
		{
			con.commit();
		}
		catch (SQLException e)
		{
			throw new IDMapperException (e);
		}
		dbConnector.compact(con);
		createGexIndices();
		dbConnector.closeConnection(con, DBConnector.PROP_FINALIZE);
		//The dbConnector may change the database file after cleaning up,
		//for example, the derby connector first creates the database as directory
		//and then adds the database to a zip file and removes the directory.
		//The database name needs to be changed to the zip file in this case.
		String newDb = dbConnector.finalizeNewDatabase(dbName);
		setDbName(newDb);
	}

	/**
	   commit inserted data
	 */
	public void commit() throws IDMapperException
	{
		try
		{
			con.commit();
		}
		catch (SQLException e)
		{
			throw new IDMapperException (e);
		}
	}

	PreparedStatement pstRow = null;

	// lazy instantiation of pstRow
	private PreparedStatement getPstRow() throws SQLException
	{
		if (pstRow == null)
		{
			pstRow = con.prepareStatement (
					"SELECT id, code, idSample, data, groupId " +
					"FROM expression " +
					"WHERE groupId = ?");
		}
		return pstRow;
	}

	@Override
	public ReporterData getRow(int rowId) throws DataException
	{
		Map<Integer, ? extends ISample> samples = getSamples();
		try
		{
			ReporterData result;
			PreparedStatement ps = getPstRow();
			ps.setInt(1, rowId);
			ResultSet rs = ps.executeQuery();

			Xref ref = null;
			result = new ReporterData (null, rowId);

			while (rs.next())
			{
				if (ref == null)
				{
					//TODO: this redundancy in ref is not normalized
					ref = new Xref (rs.getString(1), DataSource.getBySystemCode(rs.getString(2)));
					result.setXref(ref);
				}

				int sample = rs.getInt(3);
				String value = rs.getString (4);
				result.setSampleData(samples.get(sample), value);
			}

			return result;
		}
		catch (SQLException e)
		{
			throw new DataException (e);
		}
	}

	@Override
	public int getNrRow() throws DataException
	{
		try
		{
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("SELECT MAX(groupId) FROM expression");
			rs.next();
			return rs.getInt(1) + 1;
		}
		catch (SQLException e)
		{
			throw new DataException (e);
		}
	}

	PreparedStatement pstRowIt = null;

	// lazy instantiation of pstRow
	private PreparedStatement getPstRowIterator() throws SQLException
	{
		if (pstRowIt == null)
		{
			pstRowIt = con.prepareStatement (
					"SELECT id, code, idSample, data, groupId " +
					"FROM expression " +
					"ORDER BY groupId");
		}
		return pstRowIt;
	}

	/**
	 * Go over groups in database one by one.
	 */
	private class RowIterator implements Iterator<IRow>
	{
		private ResultSet rs;
		private boolean hasNext;

		RowIterator() throws SQLException
		{
			PreparedStatement ps = getPstRowIterator();
			ResultSet rs = ps.executeQuery();
			hasNext = rs.next();
		}

		@Override
		public boolean hasNext()
		{
			return hasNext;
		}

		@Override
		public IRow next()
		{
			if (!hasNext) throw new NoSuchElementException();

			// at this point, resultset should already be at beginning of new group.
			try
			{
				Map<Integer, ? extends ISample> samples = getSamples();
				ReporterData result;

				int currentGroup = rs.getInt(5);
				result = new ReporterData (null, rs.getInt(5));

				Xref ref = new Xref (rs.getString(1), DataSource.getBySystemCode(rs.getString(2)));
				result.setXref(ref);

				do
				{
					int groupId = rs.getInt(5);

					if (groupId != currentGroup)
					{
						// we're done tallying this group, and recordset is ready for next group
						return result;
					}

					int sample = rs.getInt(3);
					String value = rs.getString (4);
					result.setSampleData(samples.get(sample), value);
				}
				while  ((hasNext = rs.next()) == true);

				return result;
			}
			catch (SQLException e)
			{
				Logger.log.error ("Error while iterating over elements", e);
				throw new NoSuchElementException("Error fetching next element: " + e.getMessage());
			} catch (DataException e) {
				Logger.log.error ("Error while iterating over elements", e);
				throw new NoSuchElementException("Error fetching next element: " + e.getMessage());
			}
		}

		@Override
		public void remove()
		{
			throw new UnsupportedOperationException();
		}

	}

	@Override
	public Iterable<IRow> getIterator() throws DataException
	{
		try
		{
			final RowIterator it = new RowIterator();
			return new Iterable<IRow>()
			{
				@Override
				public Iterator<IRow> iterator()
				{
					return it;
				}
			};
		}
		catch (SQLException ex)
		{
			throw new DataException(ex);
		}

	}
}


text:
      <button id="remove-all-cookies-button"
          i18n-content="remove_all_cookie"></button>
      <input id="cookies-search-box" type="search"
          i18n-values="placeholder:search_cookies" incremental
          results="10" autosave="org.chromium.options.cookies.search">

  <list id="cookies-list"></list>


text:
<?php

namespace Yoast\WP\SEO\Actions\Indexation;

/**
 * Interface definition of reindexation action for indexables.
 */
interface Indexation_Action_Interface {

	/**
	 * Returns the total number of unindexed objects.
	 *
	 * @return int The number of unindexed objects.
	 */
	public function get_total_unindexed();

	/**
	 * Index a number of objects.
	 *
	 * NOTE: ALWAYS use limits, this method is intended to be called multiple times over several requests.
	 *
	 * For indexation that requires JavaScript simply return the objects that should be indexed.
	 *
	 * @return array The reindexed objects.
	 */
	public function index();

	/**
	 * Returns the number of objects that will be indexed in a single indexation pass.
	 *
	 * @return int The limit.
	 */
	public function get_limit();
}