text:
/*!
 * Modified by: Michael Hadjiosif
 *    on: 9/20/13
 *
 *    NOTE: If you use <a> tags inside the <li> elements of your sidebar menu,
 *    make sure you add the class "sidebar-link" to each <a> tag inside your sidebar menu.
 */
* {
  margin: 0;
  padding: 0; }

.sidebar-root {
  position: relative;
  overflow: hidden; }

.sidebar-root div.sidebar-container {
  position: absolute; }

/*
div.sidebar-container {
    width : 175px;
    height : 75px;
    position:fixed;
    background-color:#2f96b4;
    filter: alpha(opacity=87);
    -moz-opacity:0.87;
    opacity:0.87;
    -moz-box-shadow:0px 0px 20px #000000;
    -webkit-box-shadow:0px 0px 20px #000000;
    box-shadow:0px 0px 20px #000000;
}
*/
div.sidebar-container {
  width: 175px;
  height: 75px;
  position: fixed;
  color: #ffffff;
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
  background-color: #49afcd;
  *background-color: #246679;
  background-image: -moz-linear-gradient(top, #5bc0de, #246679);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#246679));
  background-image: -webkit-linear-gradient(top, #5bc0de, #246679);
  background-image: -o-linear-gradient(top, #5bc0de, #246679);
  background-image: linear-gradient(to bottom, #5bc0de, #246679);
  background-repeat: repeat-x;
  border-color: #246679 #246679 #1f6377;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); }

div.sidebar-container.left {
  top: 50%;
  left: 0px;
  -moz-border-radius-bottomright: 10px;
  -moz-border-radius-topright: 10px;
  -webkit-border-top-right-radius: 10px;
  -webkit-border-bottom-right-radius: 10px;
  border-bottom-right-radius: 10px;
  border-top-right-radius: 10px; }

div.sidebar-container.right {
  top: 50%;
  right: 0px;
  -moz-border-radius-bottomleft: 10px;
  -moz-border-radius-topleft: 10px;
  -webkit-border-bottom-left-radius: 10px;
  -webkit-border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  border-top-left-radius: 10px; }

div.sidebar-container.top {
  top: 0px;
  left: 50%;
  -moz-border-radius-bottomright: 10px;
  -moz-border-radius-bottomleft: 10px;
  -webkit-border-bottom-right-radius: 10px;
  -webkit-border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px; }

div.sidebar-container.bottom {
  bottom: 0px;
  left: 50%;
  -moz-border-radius-topright: 10px;
  -moz-border-radius-topleft: 10px;
  -webkit-border-top-right-radius: 10px;
  -webkit-border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px; }

div.sidebar-inject {
  position: absolute; }

div.sidebar-inject.left {
  background: url("inject-left.png") center no-repeat;
  top: 0px;
  right: 0px;
  width: 50px; }

div.sidebar-inject.right {
  background: url("inject-right.png") center no-repeat;
  top: 0px;
  left: 0px;
  width: 50px; }

div.sidebar-inject.top {
  bottom: 0px;
  left: 0px;
  height: 15px; }

div.sidebar-inject.top > span.sidebar-label {
  height: 15px;
  width: inherit;
  display: block;
  text-align: center;
  line-height: normal;
  color: white;
  font-weight: bold;
  letter-spacing: 0.15em; }

div.sidebar-inject.bottom {
  top: 0px;
  right: 0px;
  height: 50px; }

div.sidebar-body {
  margin: 0px;
  position: absolute;
  top: 0px;
  left: 0px;
  color: #FFFFFF;
  text-align: center; }

ul.sidebar-menu {
  font-size: 12pt;
  font-weight: bold;
  list-style: none;
  text-decoration: none;
  color: white;
  margin-left: 0px; }

ul.sidebar-menu li {
  line-height: 1.5em; }

a.sidebar-link, a.sidebar-link:visited {
  color: white;
  text-decoration: none;
  font-weight: bold; }


text:
package com.percolate.sdk.enums;

import org.apache.commons.lang3.StringUtils;

import java.util.Locale;

/**
 * Valid values for Activity API requests.
 */
public enum ActivityStreamType {

    CREATE_BRIEF,
    UPDATE_CAMPAIGN,
    CREATE_BRIEF_COMMENT,
    CREATE_BRIEF_FOLLOW,
    CREATE_BRIEF_POST,
    UPDATE_BRIEF_POST,
    CREATE_BRIEF_SECTION,
    UPDATE_BRIEF_SECTION,
    CREATE_WORKSPACE_SECTION,
    UPDATE_WORKSPACE_SECTION,
    SUBMIT_BRIEF_FOR_APPROVAL,
    APPROVE_BRIEF,
    CREATE_POST,
    UPDATE_POST,
    CREATE_POST_COMMENT,
    CREATE_POST_FOLLOW,
    SUBMIT_POST_FOR_APPROVAL,
    APPROVE,
    COMPLETE_POST_APPROVAL,
    COMPLETE_BRIEF_APPROVAL,
    COMPLETE_POST_APPROVAL_STEP,
    COMPLETE_BRIEF_APPROVAL_STEP,
    UNKNOWN;

    /**
     * Returns an {@link ActivityStreamType} enum based on a string returned by the API.
     *
     * @param activityStreamTypeName    activity type string
     * @return  ActivityStreamType
     */
    public static ActivityStreamType fromString(final String activityStreamTypeName){
        for (ActivityStreamType activityStreamType : ActivityStreamType.values()) {
            if(StringUtils.equalsIgnoreCase(activityStreamType.toString(), activityStreamTypeName)){
                return activityStreamType;
            }
        }
        return UNKNOWN;
    }

    /**
     * @return true or false if activity type is for creating and updating a campaign only.
     */
    public boolean isCampaignType() {
        return (this == CREATE_BRIEF || this == UPDATE_CAMPAIGN || this == CREATE_BRIEF_COMMENT
                || this == CREATE_BRIEF_FOLLOW);
    }

    /**
     * @return true or false if activity type is for creating or updating brief or workspace sections.
     */
    public boolean isCampaignSectionType() {
        return (this == CREATE_BRIEF_SECTION || this == CREATE_WORKSPACE_SECTION || this == UPDATE_BRIEF_SECTION
                || this == UPDATE_WORKSPACE_SECTION || this == SUBMIT_BRIEF_FOR_APPROVAL || this == APPROVE_BRIEF);
    }

    /**
     * @return true if stream type is creating or updating a post, otherwise false.
     */
    public boolean isPostType() {
        return (this == CREATE_BRIEF_POST  || this == UPDATE_BRIEF_POST || this == CREATE_POST
                || this == UPDATE_POST || this == SUBMIT_POST_FOR_APPROVAL || this == APPROVE
                || this == CREATE_POST_COMMENT || this == CREATE_POST_FOLLOW || this == COMPLETE_POST_APPROVAL
                || this == COMPLETE_POST_APPROVAL_STEP);
    }

    /**
     * @return true if activity type is for comment creation, otherwise false.
     */
    public boolean isCommentType() {
        return (this == CREATE_BRIEF_COMMENT || this == CREATE_POST_COMMENT);
    }

    /**
     * @return true if activity type is for creating, updating, submitting for approval or approving
     * a brief section, otherwise false.
     */
    public boolean isBriefSectionType() {
        return (this == CREATE_BRIEF_SECTION || this == UPDATE_BRIEF_SECTION
                || this == SUBMIT_BRIEF_FOR_APPROVAL || this == APPROVE_BRIEF
                || this == COMPLETE_BRIEF_APPROVAL || this == COMPLETE_BRIEF_APPROVAL_STEP);
    }

    /**
     * @return true if stream type is for an update to a campaign, brief section, workspace section or post
     * otherwise return false.
     */
    public boolean isUpdateType() {
        return (this == UPDATE_CAMPAIGN || this == UPDATE_BRIEF_SECTION ||
                this == UPDATE_WORKSPACE_SECTION || this == UPDATE_BRIEF_POST ||
                this == UPDATE_POST);
    }

    /**
     * @return true if stream type is for an new top-level data type.
     */
    public boolean isTopLevelCreationType() {
        return (this == CREATE_BRIEF || this == CREATE_BRIEF_SECTION ||
                this == CREATE_WORKSPACE_SECTION || this == CREATE_BRIEF_POST ||
                this == CREATE_POST);
    }

    /**
     * @return true if stream type is for an approval (send for approval event or an approved event).
     */
    public boolean isApprovalType() {
        return (this == SUBMIT_POST_FOR_APPROVAL || this == SUBMIT_BRIEF_FOR_APPROVAL ||
                this == APPROVE || this == APPROVE_BRIEF ||
                this == COMPLETE_POST_APPROVAL || this == COMPLETE_BRIEF_APPROVAL ||
                this == COMPLETE_POST_APPROVAL_STEP || this == COMPLETE_BRIEF_APPROVAL_STEP);
    }

    @Override
    public String toString() {
        return name().toLowerCase(Locale.getDefault());
    }
}

redpajama_set_name: RedPajamaGithub


text:
function settingsPage(el){
    var dom = YAHOO.util.Dom;
    for(var i = 1; i <= 20; i++){
	dom.setStyle('settingsPage' + i,'display','none');
	var elPage = document.getElementById('Page' + i);
	if (elPage) dom.removeClass(elPage.parentNode,'sel');
    }

    dom.setStyle('settings' + el.id,'display','block');
    dom.addClass(el.parentNode,'sel');
    el.blur();
    return false;
}

function toggleAdvance(el){
    var dom = YAHOO.util.Dom;
    var s = dom.getStyle('advancedSettings','display');
    if(s && s == 'block'){
	dom.setStyle('advancedSettings','display','none');
	el.firstChild.src = 'img/cbn/f_plus.gif'
    }
    else{
	dom.setStyle('advancedSettings','display','block');
	el.firstChild.src = 'img/cbn/f_minus.gif'
    }

    el.blur();
    return false;
}

function validFieldName(e){
    var ev = YAHOO.util.Event;
    var cc = ev.getCharCode(e);
    if((cc >= 32 & cc < 127) && !(cc == 45 || (cc >= 65 && cc <= 90) || (cc >= 97 && cc <= 122))) ev.stopEvent(e);
}

function customHdrAdd(idTable){
    var frag = document.createDocumentFragment();
    var div = document.createElement('div');
    frag.appendChild(div);
    div.setAttribute('align','center');
    div.innerHTML = '<p>Add a new custom header by entering the new header name on the left and an optional value on the left<p>';

    div = document.createElement('div');
    frag.appendChild(div);
    div.setAttribute('align','center');

    var elName = createInputElement('text','field');
    div.appendChild(elName);
    elName.setAttribute('size','12');
    elName.setAttribute('maxlength','36');
    YAHOO.util.Event.addListener(elName,'keypress',validFieldName);
    YAHOO.util.Event.addListener(elName,'keyup',panelDialogInputChange);
    el = document.createTextNode(' : ');
    div.appendChild(el);
    var elValue = createInputElement('text','value');
    div.appendChild(elValue);
    elValue.setAttribute('size','40');

    panelDialog('New Custom Field',
		frag,
		{
		    label:' Add ',
		    disabled: true,
		    fn: function() {
			var elTD, elTR, elTable = document.getElementById(idTable);
			var el = document.getElementById('customHdrFields');
			var n = (el.value - 0) + 1;
			el.value = n;
			if(elTable && elName.value.length){
			    elTR = elTable.insertRow(elTable.rows.length);

			    elTD = elTR.insertCell(elTR.cells.length);
			    el = document.createTextNode(elName.value +':');
			    elTD.appendChild(el);
			    el = createInputElement('hidden','customHdrField'+n);
			    elTD.appendChild(el);
			    el.setAttribute('value',elName.value);

			    elTD = elTR.insertCell(elTR.cells.length);
			    el = createInputElement('text','customHdrData' + n);
			    elTD.appendChild(el);
			    el.setAttribute('value',elValue.value);
			    el.setAttribute('size','45');

			    el = document.createElement('a');
			    elTD.appendChild(el);
			    el.setAttribute('href','#');
			    YAHOO.util.Event.addListener(el,'click',removeTableRowEvent);
			    var img = document.createElement('img');
			    img.setAttribute('src','img/cbn/remove.gif');
			    YAHOO.util.Dom.addClass(img,'wap');
			    el.appendChild(img);
			}
		    }
		});

    elName.focus();
    return false;
}

function removeTableRow(el){
    if(el){
	var iRow = el.parentNode.parentNode.rowIndex;
	el.parentNode.parentNode.parentNode.parentNode.deleteRow(iRow);
    }
    return false;
}

function removeTableRowEvent(e){
    var ev = YAHOO.util.Event;
    removeTableRow(ev.getTarget(e).parentNode);
    ev.stopEvent(e);
}

function listAdd(idTable,listName){
    var elTD, elTR, elTable = document.getElementById(idTable);
    var el = document.getElementById(listName+'s');
    var n = el.value - 0;
    el.value = ++n;
    if(elTable.rows.length < 12){
	if(elTable){
	    elTR = elTable.insertRow(elTable.rows.length);
	    elTD = elTR.insertCell(elTR.cells.length);

	    el = createInputElement('text',listName + n);
	    elTD.appendChild(el);
	    el.setAttribute('size','45');

	    el = document.createElement('a');
	    elTD.appendChild(el);
	    el.setAttribute('href','#');
	    YAHOO.util.Event.addListener(el,'click',removeTableRowEvent);
	    var img = document.createElement('img');
	    img.setAttribute('src','img/cbn/remove.gif');
	    YAHOO.util.Dom.addClass(img,'wap');
	    el.appendChild(img);
	}
    }

    return false;
}

function saveSettings(){
    showLoading();
    document.getElementById('settingsForm').submit();
    return false;
}

function restoreDefaultSettings(){
    var el = document.getElementById('restore');
    if(el){
	el.value = 'restore';
	showLoading();
	document.getElementById('settingsForm').submit();
    }
    return false;
}

function settingsSuccess(){
    var alp = YAHOO.alpine;
    window.location.href = alp.cgi_base + 'browse/' + alp.current.c + '/' + alp.current.f;
}

function settingsFailure(m){
    hideLoading();
    addStatusMessage('Settings Failure: ' + m);
    displayStatusMessages();
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. Linn. Soc. N. S. W. 186 (1931)

#### Original name
Colus javanicus Penz., 1899

### Remarks
null


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model \common\modules\vendorManagement\models\VendorVehicle */
/* @var $form yii\widgets\ActiveForm */

//Ajax for autofill
//                    'ajax' => [
//                        'url' => \yii\helpers\Url::to(['vendor-management/vendor/vendor-list']),
//                        'dataType' => 'json',
//                        'data' => new \yii\web\JsExpression('function(params) { return {q:params.term}; }')
//                    ],
//                    'escapeMarkup' => new \yii\web\JsExpression('function (markup) { return markup; }'),
//                    'templateResult' => new \yii\web\JsExpression('function(city) { return city.text; }'),
//                    'templateSelection' => new \yii\web\JsExpression('function (city) { return city.text; }'),

?>

    <?php $form = ActiveForm::begin([
        'enableAjaxValidation'=>true,
    ]); ?>

            <?php
            $vendorList=\common\modules\vendorManagement\models\Vendor::getVendorList();
            $vendorList=\yii\helpers\ArrayHelper::map($vendorList,'id','vendorName');
            echo $form->field($model, 'vendor_id')->widget(\kartik\widgets\Select2::classname(), [
                'data' => $vendorList,
                'language' => 'en',
                'options' => [
                    'placeholder' => 'Select Vendor...',
                ],
                'pluginOptions' => [
                    'allowClear' => true,
                ],
            ]);
            ?>

            <?php
            $vehicleList=\common\modules\vehicleManagement\models\Vehicle::getVehicleList();
            $vehicleList=\yii\helpers\ArrayHelper::map($vehicleList,'id','vehicleName');
            echo $form->field($model, 'vehicle_id')->widget(\kartik\widgets\Select2::classname(), [
                'data' => $vehicleList,
                'language' => 'en',
                'options' => [
                    'placeholder' => 'Select Vehicle...',
                ],
                'pluginOptions' => [
                    'allowClear' => true,
                ],
            ]);
            ?>

            <?= $form->field($model, 'is_available')->checkbox() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
require "espial/version"
require "espial/errors"
require "espial/engine"
require "espial/specs"

module Espial

  class Config
    include Singleton
    attr_accessor :specs

    def initialize
      @specs = {}
    end
  end

end


text:
<!DOCTYPE html>

    {% include head.html %}

        {% include navigation.html %}

      {{ content }}

          该博客基于Jekyll。使用了brume作为模板。感谢这些作者的贡献。


text:
category = Category.create!(name: 'Toiletries')
p1 = Product.create!(name: 'Radox', category: category, description: "Radox Men's shower gel")
p2 = Product.create!(name: 'Imperial Leather', category: category, description: "Bar Soap 200gm")
p3 = Product.create!(name: 'Sunsense', category: category, description: "Sunsense sun cream 100gm")

ProductPrice.create!(product: p1, price: 1.99, effective_start_date: 1.day.ago)
ProductPrice.create!(product: p2, price: 2.69, effective_start_date: 1.day.ago)
ProductPrice.create!(product: p3, price: 14.99, effective_start_date: 1.day.ago)

AddressType.create!(description: "Delivery")
AddressType.create!(description: "Billing")

PhoneType.create!(description: "Home")
PhoneType.create!(description: "Mobile")


text:
<?php

namespace Laminas\Serializer\Adapter;

use Laminas\Stdlib\AbstractOptions;

class AdapterOptions extends AbstractOptions
{
}


text:
require 'spec_helper'

module ImageResizer
  describe Format do
    let(:output) { subject.to_s }

    describe 'operations' do
      let(:format) { described_class.new }

      describe '#optimize' do
        subject { format.optimize(quality: 80) }
        specify { expect(output).to eq 'O=80'}
      end

      describe '#effects' do
        describe 'sharpen with default value' do
          subject { format.effects(sharpen: 10) }
          specify { expect(output).to eq 'E=S'}
        end

        describe 'sharpen with custom value' do
          subject { format.effects(sharpen: 20) }
          specify { expect(output).to eq 'E=S20'}
        end

        describe 'greyscale only' do
          subject { format.effects(greyscale: true) }
          specify { expect(output).to eq 'E=G'}
        end

        describe 'greyscale and sharpen' do
          subject { format.effects(sharpen: 20, greyscale: true) }
          specify { expect(output).to eq 'E=S20,G'}
        end
      end

      describe '#aspect_ratio' do
        subject { format.aspect_ratio('16x9') }
        specify { expect(output).to eq 'C=AR16x9' }
      end

      describe '#square_crop' do
        subject { format.square_crop }
        specify { expect(output).to eq 'C=SQ' }
      end

      describe '#resize' do
        subject { format.resize(width: 80, height: 70,
          upscale: true) }
        specify { expect(output).to eq 'S=W80,H70,U' }
      end

      describe '#crop' do
        context 'with normal crop' do
          subject { format.crop(width: 80, height: 70,
            x_offset: 10, y_offset: 20) }
          specify { expect(output).to eq 'C=W80,H70,X10,Y20' }
        end

        context 'with a relative crop offset' do
          subject { format.crop(width: 80, height: 70,
            x_offset: 'OF10', y_offset: 'OF20') }
          specify { expect(output).to eq 'C=W80,H70,XOF10,YOF20' }
        end
      end

      describe '#resize_wxh' do
        subject { format.resize_wxh('1024x768') }
        specify { expect(output).to eq 'S=W1024,H768' }
      end

      describe '#crop_from_jcrop' do
        subject { format.crop_from_jcrop('10:20;30,40') }
        it 'parses the custom string correctly' do
          expect(output).to eq 'C=W10,H20,X30,Y40'
        end
      end
    end

    describe '.from_hash' do
      specify do
        expect(
          described_class.from_hash(optimize: {quality: 50}).to_s
        ).to eq('O=50')
      end

      specify do
        expect(
          described_class.from_hash(resize: {width: 100}).to_s
        ).to eq('S=W100')
      end

      specify do
        expect(described_class.from_hash(resize: {width: 100},
                                         optimize: {quality: 90}).to_s
        ).to eq('S=W100/O=90')
      end
    end

    describe '#valid?' do
      context 'a normal format' do
        it { is_expected.to be_valid }
      end

      context 'a regular crop' do
        subject { described_class.new.crop(width: 10, height: 20) }

        it 'is considered valid if we ignore the original image size' do
          expect(subject).to be_valid
        end

        context 'with original image size available' do
          subject do
            described_class.new.tap do |f|
              f.original_image_width  = 400
              f.original_image_height = 300
            end
          end

          it 'honours good crop values' do
            expect(subject.crop(width: 100, height: 100)).to be_valid
          end

          it 'detects bad crop values' do
            expect(subject.crop(width: 500, height: 400)).to_not be_valid
            expect(subject.crop(width: 0, height: 400)).to_not be_valid
          end
        end
      end

      context 'a zero-dimension crop' do
        specify do
          expect(subject.crop(width: 0, height: 400)).to_not be_valid
        end
      end
    end

    describe '#fix_crop!' do
      subject do
        described_class.new.tap do |f|
          f.original_image_width  = 400
          f.original_image_height = 300
        end
      end

      it "doesn't change healthy crops" do
        expect(
          subject.crop(width: 100, height: 200).fix_crop!.to_s
          ).to eq('C=W100,H200,X0,Y0')
      end

      it 'fixes bad crops' do
        expect(
          subject.crop(width: 500, height: 900).fix_crop!.to_s
          ).to eq('C=W400,H300,X0,Y0')
      end

      it 'fixes bad crops' do
        expect(
          subject.crop(width: 300, height: 200, x_offset: 150, y_offset: 200).fix_crop!.to_s
          ).to eq('C=W250,H100,X150,Y200')
      end
    end

  end # describe Format
end # ImageResizer


text:
package io.crate.sql;

import io.crate.sql.tree.AllColumns;
import io.crate.sql.tree.ArithmeticExpression;
import io.crate.sql.tree.ArrayComparisonExpression;
import io.crate.sql.tree.ArrayLikePredicate;
import io.crate.sql.tree.ArrayLiteral;
import io.crate.sql.tree.ArraySubQueryExpression;
import io.crate.sql.tree.AstVisitor;
import io.crate.sql.tree.BetweenPredicate;
import io.crate.sql.tree.BooleanLiteral;
import io.crate.sql.tree.Cast;
import io.crate.sql.tree.CollectionColumnType;
import io.crate.sql.tree.ColumnType;
import io.crate.sql.tree.ComparisonExpression;
import io.crate.sql.tree.CurrentTime;
import io.crate.sql.tree.DoubleLiteral;
import io.crate.sql.tree.EscapedCharStringLiteral;
import io.crate.sql.tree.ExistsPredicate;
import io.crate.sql.tree.Expression;
import io.crate.sql.tree.Extract;
import io.crate.sql.tree.FrameBound;
import io.crate.sql.tree.FunctionCall;
import io.crate.sql.tree.GenericProperties;
import io.crate.sql.tree.IfExpression;
import io.crate.sql.tree.InListExpression;
import io.crate.sql.tree.InPredicate;
import io.crate.sql.tree.IntegerLiteral;
import io.crate.sql.tree.IntervalLiteral;
import io.crate.sql.tree.IsNotNullPredicate;
import io.crate.sql.tree.IsNullPredicate;
import io.crate.sql.tree.LikePredicate;
import io.crate.sql.tree.LogicalBinaryExpression;
import io.crate.sql.tree.LongLiteral;
import io.crate.sql.tree.MatchPredicate;
import io.crate.sql.tree.MatchPredicateColumnIdent;
import io.crate.sql.tree.NegativeExpression;
import io.crate.sql.tree.Node;
import io.crate.sql.tree.NotExpression;
import io.crate.sql.tree.NullLiteral;
import io.crate.sql.tree.ObjectColumnType;
import io.crate.sql.tree.ObjectLiteral;
import io.crate.sql.tree.ParameterExpression;
import io.crate.sql.tree.QualifiedNameReference;
import io.crate.sql.tree.RecordSubscript;
import io.crate.sql.tree.SearchedCaseExpression;
import io.crate.sql.tree.SimpleCaseExpression;
import io.crate.sql.tree.SortItem;
import io.crate.sql.tree.StringLiteral;
import io.crate.sql.tree.SubqueryExpression;
import io.crate.sql.tree.SubscriptExpression;
import io.crate.sql.tree.TryCast;
import io.crate.sql.tree.WhenClause;
import io.crate.sql.tree.Window;
import io.crate.sql.tree.WindowFrame;

import javax.annotation.Nullable;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static io.crate.sql.SqlFormatter.formatSql;

public final class ExpressionFormatter {

    private static final Formatter DEFAULT_FORMATTER = new Formatter();

    private static final Collector<CharSequence, ?, String> COMMA_JOINER = Collectors.joining(", ");

    private static final Set<String> FUNCTION_CALLS_WITHOUT_PARENTHESIS = Set.of(
        "current_catalog", "current_schema", "current_user", "session_user", "user");

    private ExpressionFormatter() {
    }

    /**
     * Formats the given expression and removes the outer most parenthesis, which are optional from an expression
     * correctness perspective, but clutter for the user (in case of nested expressions the inner expression will still
     * be enclosed in parenthesis, as that is a requirement for correctness, but the outer most expression will not be
     * surrounded by parenthesis)
     */
    public static String formatStandaloneExpression(Expression expression, @Nullable List<Expression> parameters) {
        return formatStandaloneExpression(expression, parameters, DEFAULT_FORMATTER);
    }

    public static String formatStandaloneExpression(Expression expression) {
        return formatStandaloneExpression(expression, null, DEFAULT_FORMATTER);
    }

    public static <T extends Formatter> String formatStandaloneExpression(Expression expression,
                                                                          @Nullable List<Expression> parameters,
                                                                          T formatter) {
        String formattedExpression = expression.accept(formatter, parameters);
        if (formattedExpression.startsWith("(") && formattedExpression.endsWith(")")) {
            return formattedExpression.substring(1, formattedExpression.length() - 1);
        } else {
            return formattedExpression;
        }
    }

    public static String formatExpression(Expression expression) {
        return expression.accept(DEFAULT_FORMATTER, null);
    }

    public static class Formatter extends AstVisitor<String, List<Expression>> {

        @Override
        protected String visitNode(Node node, @Nullable List<Expression> parameters) {
            throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "cannot handle node '%s'", node.toString()));
        }

        @Override
        protected String visitExpression(Expression node, @Nullable List<Expression> parameters) {
            throw new UnsupportedOperationException(String.format(Locale.ENGLISH,
                "not yet implemented: %s.visit%s", getClass().getName(), node.getClass().getSimpleName()));
        }

        @Override
        public String visitIntervalLiteral(IntervalLiteral node, List<Expression> context) {
            return IntervalLiteral.format(node);
        }

        @Override
        public String visitRecordSubscript(RecordSubscript recordSubscript, List<Expression> parameters) {
            return '('
                + recordSubscript.base().accept(this, parameters)
                + ")."
                + recordSubscript.field();
        }

        @Override
        public String visitArrayComparisonExpression(ArrayComparisonExpression node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();

            String array = node.getRight().toString();
            String left = node.getLeft().toString();
            String type = node.getType().getValue();

            builder.append(left + " " + type + " ANY(" + array + ")");
            return builder.toString();
        }

        @Override
        protected String visitArraySubQueryExpression(ArraySubQueryExpression node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();
            String subqueryExpression = node.subqueryExpression().toString();

            return builder.append("ARRAY(").append(subqueryExpression).append(")").toString();
        }

        @Override
        protected String visitCurrentTime(CurrentTime node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();
            switch (node.getType()) {
                case TIME:
                    builder.append("current_time");
                    break;
                case DATE:
                    builder.append("current_date");
                    break;
                case TIMESTAMP:
                    builder.append("current_timestamp");
                    break;
                default:
                    throw new UnsupportedOperationException("not yet implemented: " + node.getType());
            }

            if (node.getPrecision().isPresent()) {
                builder.append('(')
                    .append(node.getPrecision().get())
                    .append(')');
            }

            return builder.toString();
        }

        @Override
        protected String visitExtract(Extract node, @Nullable List<Expression> parameters) {
            return "EXTRACT(" + node.getField() + " FROM " + node.getExpression().accept(this, parameters) + ")";
        }

        @Override
        protected String visitBooleanLiteral(BooleanLiteral node, @Nullable List<Expression> parameters) {
            return String.valueOf(node.getValue());
        }

        @Override
        protected String visitSubscriptExpression(SubscriptExpression node, @Nullable List<Expression> parameters) {
            return node.base() + "[" + node.index() + "]";
        }

        @Override
        public String visitParameterExpression(ParameterExpression node, @Nullable List<Expression> parameters) {
            if (parameters == null) {
                return "$" + node.position();
            } else {
                int index = node.index();
                if (index >= parameters.size()) {
                    throw new IllegalArgumentException(
                        "Invalid parameter number " + node.position() +
                        ". Only " + parameters.size() + " parameters are available");
                }
                return parameters.get(index).accept(this, parameters);
            }
        }

        @Override
        protected String visitStringLiteral(StringLiteral node, @Nullable List<Expression> parameters) {
            return Literals.quoteStringLiteral(node.getValue());
        }

        @Override
        protected String visitEscapedCharStringLiteral(EscapedCharStringLiteral node, @Nullable List<Expression> parameters) {
            return Literals.quoteEscapedStringLiteral(node.getRawValue());
        }

        @Override
        protected String visitLongLiteral(LongLiteral node, @Nullable List<Expression> parameters) {
            return Long.toString(node.getValue());
        }

        @Override
        protected String visitIntegerLiteral(IntegerLiteral node, @Nullable List<Expression> parameters) {
            return Integer.toString(node.getValue());
        }

        @Override
        protected String visitDoubleLiteral(DoubleLiteral node, @Nullable List<Expression> parameters) {
            return Double.toString(node.getValue());
        }

        @Override
        protected String visitNullLiteral(NullLiteral node, @Nullable List<Expression> parameters) {
            return "NULL";
        }

        @Override
        public String visitArrayLiteral(ArrayLiteral node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder("[");
            boolean first = true;
            for (Expression element : node.values()) {
                if (!first) {
                    builder.append(", ");
                } else {
                    first = false;
                }
                builder.append(element.accept(this, parameters));

            }
            return builder.append("]").toString();
        }

        @Override
        public String visitObjectLiteral(ObjectLiteral node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder("{");
            boolean first = true;
            TreeMap<String, Expression> sorted = new TreeMap<>(Comparator.nullsLast(Comparator.naturalOrder()));
            sorted.putAll(node.values());
            for (Map.Entry<String, Expression> entry : sorted.entrySet()) {
                if (!first) {
                    builder.append(", ");
                } else {
                    first = false;
                }
                builder.append(formatIdentifier(entry.getKey()))
                    .append("= ")
                    .append(entry.getValue().accept(this, parameters));

            }
            return builder.append("}").toString();
        }

        @Override
        protected String visitSubqueryExpression(SubqueryExpression node, @Nullable List<Expression> parameters) {
            return "(" + formatSql(node.getQuery()) + ")";
        }

        @Override
        protected String visitExists(ExistsPredicate node, @Nullable List<Expression> parameters) {
            return "EXISTS (" + formatSql(node.getSubquery()) + ")";
        }

        @Override
        protected String visitQualifiedNameReference(QualifiedNameReference node, @Nullable List<Expression> parameters) {
            return node.getName().getParts().stream()
                .map(Formatter::formatIdentifier)
                .collect(Collectors.joining("."));
        }

        @Override
        protected String visitFunctionCall(FunctionCall node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();

            String arguments = joinExpressions(node.getArguments());
            if (node.getArguments().isEmpty() && "count".equalsIgnoreCase(node.getName().getSuffix())) {
                arguments = "*";
            }
            if (node.isDistinct()) {
                arguments = "DISTINCT " + arguments;
            }

            builder.append(node.getName());
            if (!FUNCTION_CALLS_WITHOUT_PARENTHESIS.contains(node.getName().toString())) {
                builder.append('(').append(arguments).append(')');
            }

            node.filter()
                .ifPresent(filter -> builder
                    .append(" FILTER (WHERE ")
                    .append(formatExpression(filter))
                    .append(")"));

            node.getWindow()
                .ifPresent(window -> builder
                    .append(" OVER ")
                    .append(visitWindow(window, parameters)));

            return builder.toString();
        }

        @Override
        public String visitWindow(Window node, @Nullable List<Expression> parameters) {
            StringBuilder sb = new StringBuilder("(");
            if (node.windowRef() != null) {
                sb.append(node.windowRef()).append(" ");
            }
            if (!node.getPartitions().isEmpty()) {
                sb.append("PARTITION BY ");
                sb.append(joinExpressions(node.getPartitions()));
                sb.append(" ");
            }
            if (!node.getOrderBy().isEmpty()) {
                sb.append(formatOrderBy(node.getOrderBy(), parameters));
            }
            if (node.getWindowFrame().isPresent()) {
                sb.append(node.getWindowFrame().get().accept(this, parameters));
            }
            if (Character.isWhitespace(sb.charAt(sb.length() - 1))) {
                sb.setLength(sb.length() - 1);
            }
            sb.append(')');
            return sb.toString();
        }

        private static String formatOrderBy(List<SortItem> orderBy, @Nullable List<Expression> parameters) {
            return "ORDER BY " + orderBy.stream()
                .map(e -> SqlFormatter.formatSortItem(e, parameters))
                .collect(Collectors.joining(", "));
        }

        @Override
        public String visitWindowFrame(WindowFrame node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder(" ");

            builder.append(node.mode().toString()).append(' ');

            if (node.getEnd().isPresent()) {
                builder.append("BETWEEN ")
                    .append(node.getStart().accept(this, parameters))
                    .append(" AND ")
                    .append(node.getEnd().get().accept(this, parameters));
            } else {
                builder.append(node.getStart().accept(this, parameters));
            }
            return builder.toString();
        }

        @Override
        public String visitFrameBound(FrameBound node, @Nullable List<Expression> parameters) {
            switch (node.getType()) {
                case UNBOUNDED_PRECEDING:
                    return "UNBOUNDED PRECEDING";
                case PRECEDING: {
                    Expression value = node.getValue();
                    assert value != null : "Value for FrameBound must be available if type is PRECEDING";
                    return value.accept(this, parameters) + " PRECEDING";
                }
                case CURRENT_ROW:
                    return "CURRENT ROW";
                case FOLLOWING: {
                    Expression value = node.getValue();
                    assert value != null : "Value for FrameBound must be available if type is FOLLOWING";
                    return value.accept(this, parameters) + " FOLLOWING";
                }
                case UNBOUNDED_FOLLOWING:
                    return "UNBOUNDED FOLLOWING";
                default:
                    throw new IllegalArgumentException("unhandled type: " + node.getType());
            }
        }

        @Override
        protected String visitLogicalBinaryExpression(LogicalBinaryExpression node, @Nullable List<Expression> parameters) {
            return formatBinaryExpression(
                node.getType().toString(),
                node.getLeft(),
                node.getRight(),
                parameters
            );
        }

        @Override
        protected String visitNotExpression(NotExpression node, @Nullable List<Expression> parameters) {
            return "(NOT " + node.getValue().accept(this, parameters) + ")";
        }

        @Override
        protected String visitComparisonExpression(ComparisonExpression node, @Nullable List<Expression> parameters) {
            return formatBinaryExpression(
                node.getType().getValue(),
                node.getLeft(),
                node.getRight(),
                parameters
            );
        }

        @Override
        protected String visitIsNullPredicate(IsNullPredicate node, @Nullable List<Expression> parameters) {
            return "(" + node.getValue().accept(this, parameters) + " IS NULL)";
        }

        @Override
        protected String visitIsNotNullPredicate(IsNotNullPredicate node, @Nullable List<Expression> parameters) {
            return "(" + node.getValue().accept(this, parameters) + " IS NOT NULL)";
        }

        @Override
        protected String visitIfExpression(IfExpression node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();
            builder.append("IF(")
                .append(node.getCondition().accept(this, parameters))
                .append(", ")
                .append(node.getTrueValue().accept(this, parameters));
            if (node.getFalseValue().isPresent()) {
                builder.append(", ")
                    .append(node.getFalseValue().get().accept(this, parameters));
            }
            builder.append(")");
            return builder.toString();
        }

        @Override
        protected String visitNegativeExpression(NegativeExpression node, @Nullable List<Expression> parameters) {
            return "- " + node.getValue().accept(this, parameters);
        }

        @Override
        protected String visitArithmeticExpression(ArithmeticExpression node, @Nullable List<Expression> parameters) {
            return formatBinaryExpression(
                node.getType().getValue(),
                node.getLeft(),
                node.getRight(),
                parameters);
        }

        @Override
        protected String visitLikePredicate(LikePredicate node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();

            builder.append('(')
                .append(node.getValue().accept(this, parameters))
                .append(node.ignoreCase() ? " ILIKE " : " LIKE ")
                .append(node.getPattern().accept(this, parameters));

            if (node.getEscape() != null) {
                builder.append(" ESCAPE ")
                    .append(node.getEscape().accept(this, parameters));
            }

            builder.append(')');

            return builder.toString();
        }

        @Override
        public String visitArrayLikePredicate(ArrayLikePredicate node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();
            builder.append('(')
                .append(node.getPattern().accept(this, parameters))
                .append(node.inverse() ? " NOT" : "")
                .append(node.ignoreCase() ? " ILIKE " : " LIKE ")
                .append(node.quantifier().name())
                .append(" (")
                .append(node.getValue().accept(this, parameters))
                .append(") ");
            if (node.getEscape() != null) {
                builder.append("ESCAPE ")
                    .append(node.getEscape().accept(this, parameters));
            }
            builder.append(')');
            return builder.toString();
        }

        @Override
        public String visitMatchPredicate(MatchPredicate node, @Nullable List<Expression> parameters) {
            StringBuilder builder = new StringBuilder();
            builder.append("MATCH (");
            if (node.idents().size() == 1) {
                builder.append(node.idents().get(0).columnIdent().accept(this, parameters));
            } else {
                builder.append("(");
                List<MatchPredicateColumnIdent> idents = node.idents();
                for (int i = 0, identsSize = idents.size(); i < identsSize; i++) {
                    MatchPredicateColumnIdent ident = idents.get(i);
                    builder.append(ident.accept(this, parameters));
                    if (i < (identsSize - 1)) {
                        builder.append(", ");
                    }
                }
                builder.append(")");
            }
            builder.append(", ").append(node.value().accept(this, parameters));
            builder.append(")");
            if (node.matchType() != null) {
                builder.append(" USING ").append(node.matchType()).append(" ");
                if (node.properties().properties().size() > 0) {
                    builder.append(node.properties().accept(this, parameters));
                }
            }
            return builder.toString();
        }

        @Override
        public String visitMatchPredicateColumnIdent(MatchPredicateColumnIdent node, @Nullable List<Expression> parameters) {
            String column = node.columnIdent().accept(this, null);
            if (!(node.boost() instanceof NullLiteral)) {
                column = column + " " + node.boost().toString();
            }
            return column;
        }

        @Override
        public String visitGenericProperties(GenericProperties<?> node, @Nullable List<Expression> parameters) {
            return " WITH (" +
                node.properties().entrySet().stream()
                    .map(prop -> prop.getKey() + "=" + ((Expression) prop.getValue()).accept(this, null))
                    .collect(COMMA_JOINER) +
                ")";
        }

        @Override
        protected String visitAllColumns(AllColumns node, @Nullable List<Expression> parameters) {
            if (node.getPrefix().isPresent()) {
                return node.getPrefix().get() + ".*";
            }

            return "*";
        }

        @Override
        public String visitCast(Cast node, @Nullable List<Expression> parameters) {
            return "CAST(" + node.getExpression().accept(this, parameters) + " AS " +
                   node.getType().accept(this, parameters) + ")";
        }

        @Override
        protected String visitTryCast(TryCast node, @Nullable List<Expression> parameters) {
            return "TRY_CAST(" + node.getExpression().accept(this, parameters) + " AS " +
                   node.getType().accept(this, parameters) +
                   ")";
        }

        @Override
        protected String visitSearchedCaseExpression(SearchedCaseExpression node, @Nullable List<Expression> parameters) {
            var parts = new StringJoiner(" ", "(", ")");
            parts.add("CASE");
            for (WhenClause whenClause : node.getWhenClauses()) {
                parts.add(whenClause.accept(this, parameters));
            }
            if (node.getDefaultValue() != null) {
                parts.add("ELSE");
                parts.add(node.getDefaultValue().accept(this, parameters));
            }
            parts.add("END");
            return parts.toString();
        }

        @Override
        protected String visitSimpleCaseExpression(SimpleCaseExpression node, @Nullable List<Expression> parameters) {
            var parts = new StringJoiner(" ", "(", ")");
            parts.add("CASE");
            parts.add(node.getOperand().accept(this, parameters));
            for (WhenClause whenClause : node.getWhenClauses()) {
                parts.add(whenClause.accept(this, parameters));
            }
            if (node.getDefaultValue() != null) {
                parts.add("ELSE");
                parts.add(node.getDefaultValue().accept(this, parameters));
            }
            parts.add("END");
            return parts.toString();
        }

        @Override
        protected String visitWhenClause(WhenClause node, @Nullable List<Expression> parameters) {
            return "WHEN " + node.getOperand().accept(this, parameters) + " THEN " +
                   node.getResult().accept(this, parameters);
        }

        @Override
        protected String visitBetweenPredicate(BetweenPredicate node, @Nullable List<Expression> parameters) {
            return "(" + node.getValue().accept(this, parameters) + " BETWEEN " +
                   node.getMin().accept(this, parameters) + " AND " +
                   node.getMax().accept(this, parameters) + ")";
        }

        @Override
        protected String visitInPredicate(InPredicate node, @Nullable List<Expression> parameters) {
            return "(" + node.getValue().accept(this, parameters) + " IN " +
                   node.getValueList().accept(this, parameters) + ")";
        }

        @Override
        protected String visitInListExpression(InListExpression node, @Nullable List<Expression> parameters) {
            return "(" + joinExpressions(node.getValues()) + ")";
        }

        @Override
        public String visitColumnType(ColumnType<?> node, @Nullable List<Expression> parameters) {
            var builder = new StringBuilder(node.name());
            if (node.parametrized()) {
                builder
                    .append("(")
                    .append(node.parameters().stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(", ")))
                    .append(")");
            }
            return builder.toString();
        }

        @Override
        public String visitCollectionColumnType(CollectionColumnType<?> node, @Nullable List<Expression> parameters) {
            return node.name() + "(" + node.innerType().accept(this, parameters) + ")";
        }

        @Override
        public String visitObjectColumnType(ObjectColumnType<?> node, @Nullable List<Expression> parameters) {
            return node.name();
        }

        private String formatBinaryExpression(String operator,
                                              Expression left,
                                              Expression right,
                                              @Nullable List<Expression> parameters) {
            return '(' + left.accept(this, parameters) + ' ' + operator + ' ' +
                   right.accept(this, parameters) + ')';
        }

        private String joinExpressions(List<Expression> expressions) {
            return expressions.stream()
                .map(expression -> expression.accept(this, null))
                .collect(COMMA_JOINER);
        }

        private static String formatIdentifier(String s) {
            return Identifiers.quote(s);
        }
    }
}


text: extern cute::suite make_suite_ProcessVersionSuite();


text:
package org.pikater.web.visualisation.implementation.renderer;

import java.awt.Color;

/**
 * Interface representing functions necessary to draw the charts for dataset visualisation.
 * @author siposp
 *
 */
public interface RendererInterface {

	public enum TextAlignment {
		Left, Center, Right
	};

	/**
	 * Does all the preprocessing needed by the renderer.
	 */
	public void begin();

	/**
	 * Does all the postprocessing needed by the renderer.
	 */
	public void end();

	/**
	 * Draws a circle with center point at [x,y].
	 * @param x coordinate of the center point
	 * @param y coordinate of the center point
	 * @param radius of the circle
	 */
	public void drawCircle(int x, int y, int radius);

	/**
	 * Draws a circle with center point at [x,y], filled with given color and with stroke in specified color and width.
	 * @param x coordinate of the center point
	 * @param y coordinate of the center point
	 * @param radius of the circle
	 * @param stroke color of the stroke
	 * @param fill color of the filled circle
	 * @param strokeWidth width of the stroke
	 */
	public void drawCircle(int x, int y, int radius, Color stroke, Color fill, int strokeWidth);

	/**
	 * Draws a text to the position [x,y] in given color with specified text alignment
	 * @param text {@link String} object containing the text
	 * @param x coordinate of the text
	 * @param y coordiante of the text
	 * @param textAlignment of the text
	 * @param color of the text
	 */
	public void drawText(String text, int x, int y, TextAlignment textAlignment, Color color);

	/**
	 * Draws a text to the position [x,y] in given color with specified text alignment, rotated by certain degree.
	 * @param text {@link String} object containing the text
	 * @param x coordinate of the text
	 * @param y coordiante of the text
	 * @param textAlignment of the text
	 * @param color of the text
	 * @param rotationDegree of the rotated text
	 */
	public void drawText(String text, int x, int y, TextAlignment textAlignment, Color color, int rotationDegree);

	/**
	 * Draws a text to the position [x,y] in given color with specified text alignment, rotated by certain degree. The text also has size specified.
	 * @param text {@link String} object containing the text
	 * @param x coordinate of the text
	 * @param y coordiante of the text
	 * @param textAlignment of the text
	 * @param color of the text
	 * @param rotationDegree of the rotated text
	 * @param size of text
	 */
	public void drawText(String text, int x, int y, TextAlignment textAlignment, Color color, int rotationDegree, int size);

	/**
	 * Draws a text to the position [x,y] in given color with specified text alignment, rotated by certain degree. Text is rotated around a certain point.
	 * @param text {@link String} object containing the text
	 * @param x coordinate of the text
	 * @param y coordiante of the text
	 * @param textAlignment of the text
	 * @param color of the text
	 * @param rotationDegree of the rotated text
	 * @param rotationX X coordinate of center of rotation
	 * @param rotationY Y coordinate of center of rotation
	 */
	public void drawText(String text, int x, int y, TextAlignment textAlignment, Color color, int rotationDegree, int rotationX, int rotationY);

	/**
	 * Draws a text to the position [x,y] in given color with specified text alignment, rotated by certain degree. Text has also size specified and is rotated around a certain point.
	 * @param text {@link String} object containing the text
	 * @param x coordinate of the text
	 * @param y coordiante of the text
	 * @param textAlignment of the text
	 * @param color of the text
	 * @param rotationDegree of the rotated text
	 * @param rotationX X coordinate of center of rotation
	 * @param rotationY Y coordinate of center of rotation
	 * @param size of text
	 */
	public void drawText(String text, int x, int y, TextAlignment textAlignment, Color color, int rotationDegree, int rotationX, int rotationY, int size);

	/**
	 * Draws a line from position [x1,y1] to position [x2,y2]. The line's color and width is also set.
	 * @param x1 X coordinate of the starting point
	 * @param y1 Y coordinate of the starting point
	 * @param x2 X coordinate of the ending point
	 * @param y2 Y coordinate of the ending point
	 * @param color of line
	 * @param strokeWidth width of line
	 */
	public void drawLine(int x1, int y1, int x2, int y2, Color color, int strokeWidth);

	/**
	 * Draws a rectangle with top-left corner at [x,y] position. Rectangle has specified width and height, is filled with certain color and the line around the rectangle has its own color and thickness.
	 * @param x coordinate of top-left corner
	 * @param y coordinate of top-left corner
	 * @param width of the rectangle
	 * @param height of the rectangle
	 * @param fillColor color rectangle is filled with
	 * @param strokeColor color of line around rectangle
	 * @param strokeWidth thickness of line around the rectangle
	 */
	public void drawRectangle(int x, int y, int width, int height, Color fillColor, Color strokeColor, int strokeWidth);
}


text:
<?php

session_start();
require_once(realpath(dirname(__FILE__) . "/../resources/config.php"));

require_once(LIBRARY_PATH . "/templateFunctions.php");
require_once(LIBRARY_PATH . "/connection_open.php");

if ((isset($_SESSION["admin_username"]) && isset($_SESSION["isadmin"]) && $_SESSION['isadmin'] == "true"))
    renderLayoutWithContentFile("adminHome.php");
else
    renderLayoutWithContentFile("login.php");
?>


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Castle.Core.Logging;
using SOURCE.Infrastructure.Services.Depots;
using SOURCE.Infrastructure.Services.Encryption;
using SOURCE.BackOffice.Web.Controllers.Modularity;
using SOURCE.BackOffice.Web.Controllers.Helpers;
using SOURCE.Infrastructure.Constant;
using SOURCE.BackOffice.Web.Controllers.Filters;
using System.Net;
using SOURCE.BackOffice.Web.Controllers.ActionResults;
using SOURCE.Infrastructure.Extensions;
using SOURCE.Domaine.Composite;
using SOURCE.Domaine.Results;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Common;
using System.Text;
using System;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Intervenant.Intervenant;
using SOURCE.Infrastructure.Attributes.Modularity;
using SOURCE.BackOffice.Web.ViewModels.Pages.Common;
using SOURCE.Infrastructure.Services.Caching;
using SOURCE.Infrastructure.Services.Exports;
using SOURCE.BackOffice.Web.ViewModels;

namespace SOURCE.BackOffice.Web.Controllers.Intervenant
{
    public class IntervenantControllerBase : ModularController
    {
        protected long? _intervenantID { get; set; }
        public IntervenantControllerBase(
            ILogger logger,
            ICryptography encryption,
            IDepotFactory depotFactory,
            ICommonModelBuilder commonModelBuilder,
            ICaching cachingService,
            IExcelExport exportService)
            : base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
        {

        }

        public virtual ActionResult Index(long id)
        {
            return ProcessPage(id);
        }

        public override void SetIdentifiantFonctionnelLiee(PageViewModel page, long? idFonctionnelLiee)
        {
            if (_intervenantID.HasValue && _intervenantID.Value > 0)
            {
                base.SetIdentifiantFonctionnelLiee(page, _intervenantID.Value);
            }
            else
            {
                base.SetIdentifiantFonctionnelLiee(page, idFonctionnelLiee);
            }
        }

        public override void ProcessNavBar(PageViewModel page)
        {
            page.NavBar = _commonModelBuilder.BuildNavBarStaticViewModel(Context, _cachingService.Translate("FICHE_INTERVENANT"));
        }

        public override void ProcessPageTitle(PageViewModel page)
        {
            if (page.IdFonctionnel > 0)
            {
                if (page.CodePage == "INTERVENANT")
                {
                    var intervenant = _depotFactory.IntervenantDepot.GetById(page.IdFonctionnel);
                    if (intervenant != null && intervenant.Personne != null)
                    {
                        var roles = _depotFactory.IntervenantRoleDepot.Find(x => x.IntervenantID == intervenant.ID);

                        if (roles != null && roles.Count() > 1)
                        {
                            page.Title = string.Format("{0}, {1} - {2} ({3})", intervenant.Personne.Nom, intervenant.Personne.Prenom, intervenant.ID, _cachingService.Translate("MULTIROLE")).Trim();
                        }
                        else
                        {
                            page.Title = string.Format("{0}, {1} - {2}", intervenant.Personne.Nom, intervenant.Personne.Prenom, intervenant.ID).Trim();
                        }

                    }
                }
                else
                {
                    var intervenantRole = _depotFactory.IntervenantRoleDepot.GetById(page.IdFonctionnel);
                    if (intervenantRole != null && intervenantRole.Intervenant != null && intervenantRole.Intervenant.Personne != null)
                    {
                        string roleLibelle = _depotFactory.TraductionRoleDepot.Find(x => x.RoleID == intervenantRole.RoleID && x.LangueID == Context.User.LangueID).Select(x => x.Libelle).FirstOrDefault();
                        page.Title = string.Format("{0}, {1} - {2} ({3})", intervenantRole.Intervenant.Personne.Nom, intervenantRole.Intervenant.Personne.Prenom, intervenantRole.IntervenantID, roleLibelle);
                    }
                }
            }
            else
            {
                page.Title = _cachingService.Translate("NOUVEL_INTERVENANT");
            }
        }

        protected override void BuildActionContext(PageEnum? page = null, VueEnum? vue = null, long? idFonctionnel = null, long? timeStamp = null, long? typeActionID = null, long? actionGeneraleID = null, long? actionSpecifiqueID = null, bool checkPermissions = true, bool checkCachedPermissions = true)
        {
            ActionContext = new ActionContext()
            {
                Page = page,
                Vue = vue,
                IdFonctionnel = idFonctionnel,
                TimeStamp = timeStamp,
                TypeActionID = typeActionID,
                ActionGeneraleID = actionGeneraleID,
                ActionSpecifiqueID = actionSpecifiqueID,
            };

            if (checkPermissions)
            {
                CheckPermissions(false); //vérifier les droits dans la bdd
            }
        }
    }
}


text:
<?php xml version="1.0"?>
<ruleset name="Syncs">
  <description>Syncs rules for PHP_CodeSniffer</description>

  <exclude-pattern>vendor/*</exclude-pattern>

  <rule ref="Isotop">
		<exclude name="WordPress.Files.FileName.InvalidClassFileName" />
		<exclude name="WordPress.Arrays.ArrayDeclarationSpacing.NoSpaceAfterArrayOpener" />
		<exclude name="WordPress.Arrays.ArrayDeclarationSpacing.NoSpaceBeforeArrayCloser" />
		<exclude name="WordPress.Arrays.ArrayDeclarationSpacing.AssociativeKeyFound" />
		<exclude name="Squiz.Commenting.LongConditionClosingComment.Missing" />
		<exclude name="WordPress.WP.I18n.MissingTranslatorsComment" />
	</rule>
</ruleset>


text:
set -ex

# Install ccache from source.
# Needs specific branch to work with nvcc (ccache/ccache#145)
# Also pulls in a commit that disables documentation generation,
# as this requires asciidoc to be installed (which pulls in a LOT of deps).
pushd /tmp
git clone https://github.com/pietern/ccache -b ccbin
pushd ccache
./autogen.sh
./configure --prefix=/usr/local
make "-j$(nproc)" install
popd
popd

# Install sccache from binary release.
# Note: this release does NOT yet work with nvcc.
pushd /tmp
curl -LOs https://github.com/mozilla/sccache/releases/download/0.2.5/sccache-0.2.5-x86_64-unknown-linux-musl.tar.gz
tar -zxvf sccache-0.2.5-x86_64-unknown-linux-musl.tar.gz
mv sccache-0.2.5-x86_64-unknown-linux-musl/sccache /usr/local/bin/sccache
rm -rf sccache-0.2.5-x86_64-unknown-linux-musl*
popd


text:
layout: page
title: Shepard Enterprises Seminar
date: 2016-05-24
author: Susan Woodard
tags: weekly links, java
status: published
summary: Donec finibus, sem et pellentesque sagittis.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 07/10/2019
  endDate: 07/13/2019
  ctyhocn: WASALHX
  groupCode: SES
published: true
---
Integer eget congue nibh, vitae hendrerit ex. Nulla ipsum risus, dignissim ac rhoncus vitae, tincidunt pretium est. Nullam volutpat convallis dictum. In non erat vitae mi vestibulum consectetur. Nam hendrerit laoreet justo. Sed in erat a urna pharetra vehicula. Pellentesque porta semper odio, ac euismod nibh auctor at. Nulla molestie purus in tortor dictum, at viverra erat finibus. Duis et quam lobortis, rutrum magna ut, maximus massa. Donec bibendum turpis a maximus lobortis. Cras egestas ligula iaculis, sodales sapien vitae, accumsan felis. Morbi et tempus enim. Aenean vulputate accumsan scelerisque. Fusce tempus, lectus eu bibendum aliquet, ex elit consectetur dui, at pharetra odio dui ut augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

* Aenean nec sem consectetur urna hendrerit cursus.

Pellentesque nisl sapien, accumsan id neque id, congue ultrices velit. Donec suscipit pretium quam, a tincidunt mauris egestas id. Nullam fermentum velit et bibendum rhoncus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer eget elit nunc. Ut a lectus sapien. Morbi pharetra justo commodo tortor aliquet facilisis. Pellentesque sed accumsan nibh. Sed convallis gravida magna, et finibus tortor rutrum a.


text:
package org.apache.catalina.core;

import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.DefaultContext;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Service;
import org.apache.catalina.util.ServerInfo;

/**
 * Standard implementation of the Engine interface.  Each
 * child container must be a Host implementation to process the specific
 * fully qualified host name of that virtual host.
 *
 * @author Craig R. McClanahan
 * @version $Revision: 1.15 $ $Date: 2002/05/02 22:14:45 $
 */

public class StandardEngine
    extends ContainerBase
    implements Engine {

    // ----------------------------------------------------------- Constructors

    /**
     * Create a new StandardEngine component with the default basic Valve.
     */
    public StandardEngine() {

        super();
        pipeline.setBasic(new StandardEngineValve());

    }

    // ----------------------------------------------------- Instance Variables

    /**
     * Host name to use when no server host, or an unknown host,
     * is specified in the request.
     */
    private String defaultHost = null;

    /**
     * The descriptive information string for this implementation.
     */
    private static final String info =
        "org.apache.catalina.core.StandardEngine/1.0";

    /**
     * The Java class name of the default Mapper class for this Container.
     */
    private String mapperClass =
        "org.apache.catalina.core.StandardEngineMapper";

    /**
     * The Service that owns this Engine, if any.
     */
    private Service service = null;

    /**
     * DefaultContext config
     */
    private DefaultContext defaultContext;

    /**
     * The JVM Route ID for this Tomcat instance. All Route ID's must be unique
     * across the cluster.
     */
    private String jvmRouteId;

    // ------------------------------------------------------------- Properties

    /**
     * Return the default host.
     */
    public String getDefaultHost() {

        return (defaultHost);

    }

    /**
     * Set the default host.
     *
     * @param host The new default host
     */
    public void setDefaultHost(String host) {

        String oldDefaultHost = this.defaultHost;
        if (host == null) {
            this.defaultHost = null;
        } else {
            this.defaultHost = host.toLowerCase();
        }
        support.firePropertyChange("defaultHost", oldDefaultHost,
                                   this.defaultHost);

    }

    /**
     * Set the cluster-wide unique identifier for this Engine.
     * This value is only useful in a load-balancing scenario.
     *

     * This property should not be changed once it is set.
     */
    public void setJvmRoute(String routeId) {
        this.log("setJvmRoute=" + routeId);
        jvmRouteId = routeId;
    }

    /**
     * Retrieve the cluster-wide unique identifier for this Engine.
     * This value is only useful in a load-balancing scenario.
     */
    public String getJvmRoute() {
        return jvmRouteId;
    }

    /**
     * Set the DefaultContext
     * for new web applications.
     *
     * @param defaultContext The new DefaultContext
     */
    public void addDefaultContext(DefaultContext defaultContext) {

        DefaultContext oldDefaultContext = this.defaultContext;
        this.defaultContext = defaultContext;
        support.firePropertyChange("defaultContext",
                                   oldDefaultContext, this.defaultContext);

    }

    /**
     * Retrieve the DefaultContext for new web applications.
     */
    public DefaultContext getDefaultContext() {
        return (this.defaultContext);
    }

    /**
     * Return the default Mapper class name.
     */
    public String getMapperClass() {

        return (this.mapperClass);

    }

    /**
     * Set the default Mapper class name.
     *
     * @param mapperClass The new default Mapper class name
     */
    public void setMapperClass(String mapperClass) {

        String oldMapperClass = this.mapperClass;
        this.mapperClass = mapperClass;
        support.firePropertyChange("mapperClass",
                                   oldMapperClass, this.mapperClass);

    }

    /**
     * Return the Service with which we are associated (if any).
     */
    public Service getService() {

        return (this.service);

    }

    /**
     * Set the Service with which we are associated (if any).
     *
     * @param service The service that owns this Engine
     */
    public void setService(Service service) {

        this.service = service;

    }

    // --------------------------------------------------------- Public Methods

    /**
     * Import the DefaultContext config into a web application context.
     *
     * @param context web application context to import default context
     */
    public void importDefaultContext(Context context) {

        if ( this.defaultContext != null )
            this.defaultContext.importDefaultContext(context);

    }

    /**
     * Add a child Container, only if the proposed child is an implementation
     * of Host.
     *
     * @param child Child container to be added
     */
    public void addChild(Container child) {

        if (!(child instanceof Host))
            throw new IllegalArgumentException
                (sm.getString("standardEngine.notHost"));
        super.addChild(child);

    }

    /**
     * Return descriptive information about this Container implementation and
     * the corresponding version number, in the format
     * <description>/<version>.
     */
    public String getInfo() {

        return (info);

    }

    /**
     * Disallow any attempt to set a parent for this Container, since an
     * Engine is supposed to be at the top of the Container hierarchy.
     *
     * @param container Proposed parent Container
     */
    public void setParent(Container container) {

        throw new IllegalArgumentException
            (sm.getString("standardEngine.notParent"));

    }

    /**
     * Start this Engine component.
     *
     * @exception LifecycleException if a startup error occurs
     */
    public void start() throws LifecycleException {

        // Log our server identification information
        System.out.println(ServerInfo.getServerInfo());

        // Standard container startup
        super.start();

    }

    /**
     * Return a String representation of this component.
     */
    public String toString() {

        StringBuffer sb = new StringBuffer("StandardEngine[");
        sb.append(getName());
        sb.append("]");
        return (sb.toString());

    }

    // ------------------------------------------------------ Protected Methods

    /**
     * Add a default Mapper implementation if none have been configured
     * explicitly.
     *
     * @param mapperClass The default mapper class name to add
     */
    protected void addDefaultMapper(String mapperClass) {

        super.addDefaultMapper(this.mapperClass);

    }

}


text:
package org.corpus_tools.annis.gui.admin.reflinks;

import com.google.common.base.Strings;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.FutureCallback;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.corpus_tools.annis.gui.Helper;
import org.corpus_tools.annis.gui.components.ExceptionDialog;

final class MigrationCallback implements FutureCallback<Integer> {

  private final MigrationPanel migrationPanel;
  private final Multimap<QueryStatus, URLShortenerDefinition> failedQueries;

  MigrationCallback(MigrationPanel migrationPanel,
      Multimap<QueryStatus, URLShortenerDefinition> failedQueries) {
    this.migrationPanel = migrationPanel;
    this.failedQueries = failedQueries;
  }

  @Override
  public void onSuccess(Integer successfulQueries) {
    this.migrationPanel.progress.setCaption("");

    // output summary and detailed list of failed queries
    final Collection<URLShortenerDefinition> unknownCorpusQueries =
        failedQueries.get(QueryStatus.UNKNOWN_CORPUS);

    StringBuilder detailedStatus = new StringBuilder();

    if (!unknownCorpusQueries.isEmpty()) {
      final Map<String, Integer> unknownCorpusCount = new TreeMap<>();
      for (final URLShortenerDefinition q : unknownCorpusQueries) {
        for (final String c : q.getUnknownCorpora()) {
          final int oldCount = unknownCorpusCount.getOrDefault(c, 0);
          unknownCorpusCount.put(c, oldCount + 1);
        }
      }
      final String unknownCorpusCaption = "Unknown corpus (" + unknownCorpusCount.size()
          + " unknown corpora and " + unknownCorpusQueries.size() + " queries)";
      detailedStatus.append(unknownCorpusCaption);
      detailedStatus.append("\n");
      detailedStatus.append(Strings.repeat("=", unknownCorpusCaption.length()));
      detailedStatus.append("\n");

      for (final Map.Entry<String, Integer> e : unknownCorpusCount.entrySet()) {
        detailedStatus.append("Corpus \"" + e.getKey() + "\": " + e.getValue() + " queries");
        detailedStatus.append("\n");
      }
      detailedStatus.append("\n");
    }

    printProblematicQueries("UUID already exists", failedQueries.get(QueryStatus.UUID_EXISTS),
        detailedStatus);
    printProblematicQueries("Count different", failedQueries.get(QueryStatus.COUNT_DIFFERS),
        detailedStatus);
    printProblematicQueries("Match list different", failedQueries.get(QueryStatus.MATCHES_DIFFER),
        detailedStatus);
    printProblematicQueries("Timeout", failedQueries.get(QueryStatus.TIMEOUT), detailedStatus);
    printProblematicQueries("Other server error", failedQueries.get(QueryStatus.SERVER_ERROR),
        detailedStatus);
    printProblematicQueries("Empty corpus list", failedQueries.get(QueryStatus.EMPTY_CORPUS_LIST),
        detailedStatus);
    printProblematicQueries("FAILED", failedQueries.get(QueryStatus.FAILED), detailedStatus);

    final String summaryString = "+ Successful: " + successfulQueries + " from "
        + (successfulQueries + failedQueries.size()) + " +";
    detailedStatus.append(Strings.repeat("+", summaryString.length()));
    detailedStatus.append("\n");
    detailedStatus.append(summaryString);
    detailedStatus.append("\n");
    detailedStatus.append(Strings.repeat("+", summaryString.length()));
    detailedStatus.append("\n");

    this.migrationPanel.setMessageAndScrollToEnd(detailedStatus.toString());
    this.migrationPanel.migrateButton.setEnabled(true);

    sendMail();
  }

  private void sendMail() {
    String mailAddress = this.migrationPanel.emailText.getValue();
    if (mailAddress != null && !mailAddress.isEmpty()) {
      try {
        // Send the whole content of the message text area as mail
        MultiPartEmail mail = Helper.createEMailFromConfiguration(migrationPanel.ui.getConfig());
        mail.addTo(mailAddress);
        mail.setSubject("ANNIS reference link migration finished");
        String message = this.migrationPanel.getMessages();
        if (message == null || message.isEmpty()) {
          message = "No further information provided";
        }
        mail.setMsg(message);
        mail.send();
      } catch (EmailException | UnknownHostException ex) {
        ExceptionDialog.show(ex, this.migrationPanel.ui);
      }
    }
  }

  @Override
  public void onFailure(Throwable t) {
    ExceptionDialog.show(t, this.migrationPanel.ui);
    this.migrationPanel.migrateButton.setEnabled(true);

    sendMail();
  }

  private void printProblematicQueries(final String statusCaption,
      final Collection<URLShortenerDefinition> queries, StringBuilder sb) {
    if (queries != null && !queries.isEmpty()) {
      final String captionWithCount = statusCaption + " (sum: " + queries.size() + ")";
      sb.append(captionWithCount);
      sb.append("\n");
      sb.append(Strings.repeat("=", captionWithCount.length()));
      sb.append("\n\n");

      for (final URLShortenerDefinition q : queries) {
        if (q.getQuery() != null && q.getQuery().getCorpora() != null) {
          sb.append(MigrationPanel.CORPUS_PREFIX + q.getQuery().getCorpora() + "\"");
          sb.append("\n");
        }
        sb.append(MigrationPanel.UUID_PREFIX + q.getUuid() + "\"");
        sb.append("\n");
        if (q.getQuery() != null && q.getQuery().getQuery() != null) {
          sb.append(MigrationPanel.QUERY_PREFIX);
          sb.append("\n");
          sb.append(q.getQuery().getQuery().trim());
          sb.append("\n");
        }
        if (q.getErrorMsg() != null) {
          sb.append("Error: " + q.getErrorMsg());
          sb.append("\n");
        }

        sb.append("-------");
        sb.append("\n");
      }
      sb.append("\n");
    }
  }

}


text:
listPopRange() with non-existent index

--DESCRIPTION--
This testcase will test for listPopRange() with non-existent index.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("ListPopRange", "error_003");
--EXPECTREGEX--
(ERR_REQUEST_INVALID|OK)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;

namespace Roslyn.VisualStudio.IntegrationTests.Basic
{
    [Collection(nameof(SharedIntegrationHostFixture))]
    public class BasicEncapsulateField : AbstractEditorTest
    {
        public BasicEncapsulateField(VisualStudioInstanceFactory instanceFactory, ITestOutputHelper testOutputHelper)
            : base(instanceFactory, testOutputHelper, nameof(BasicEncapsulateField))
        {
        }

        protected override string LanguageName => LanguageNames.VisualBasic;

        private const string TestSource = @"
Module Module1
        Public $$name As Integer? = 0
    Sub Main()
        name = 90
    End Sub
End Module";

        [WpfFact]
        [Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughCommand()
        {
            SetUpEditor(TestSource);

            var encapsulateField = VisualStudio.EncapsulateField;
            var dialog = VisualStudio.PreviewChangesDialog;
            encapsulateField.Invoke();
            dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout);
            dialog.ClickCancel(encapsulateField.DialogName);
            dialog.VerifyClosed(encapsulateField.DialogName);
            encapsulateField.Invoke();
            dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout);
            dialog.ClickApplyAndWaitForFeature(encapsulateField.DialogName, FeatureAttribute.EncapsulateField);
            VisualStudio.Editor.Verify.TextContains(@"    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughLightbulbIncludingReferences()
        {
            SetUpEditor(TestSource);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (and use property)", applyFix: true, blockUntilComplete: true);
            VisualStudio.Editor.Verify.TextContains(@"
Module Module1
    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property

    Sub Main()
        Name = 90
    End Sub
End Module");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughLightbulbDefinitionsOnly()
        {
            SetUpEditor(TestSource);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (but still use field)", applyFix: true, blockUntilComplete: true);
            VisualStudio.Editor.Verify.TextContains(@"
Module Module1
    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property

    Sub Main()
        name = 90
    End Sub
End Module");
        }
    }
}


text:
require 'rails_helper'

describe Agent do
  # pending "add some examples to (or delete) #{__FILE__}"
  fixtures :all

  it "should set a default required_role to Guest" do
    agent = FactoryBot.create(:agent)
    expect(agent.required_role).to eq Role.find_by(name: 'Guest')
  end

  it "should set birth_date" do
    agent = FactoryBot.create(:agent, birth_date: '2000')
    expect(agent.date_of_birth).to eq Time.zone.parse('2000-01-01')
  end

  it "should set death_date" do
    agent = FactoryBot.create(:agent, death_date: '2000')
    expect(agent.date_of_death).to eq Time.zone.parse('2000-01-01')
  end

  it "should not set death_date earlier than birth_date" do
    agent = FactoryBot.create(:agent, birth_date: '2010', death_date: '2000')
    expect(agent).not_to be_valid
  end

  it "should be creator" do
    create = FactoryBot.create(:create)
    expect(create.agent.creator?(create.work)).to be_truthy
  end

  it "should not be creator" do
    produce = FactoryBot.create(:produce)
    expect(produce.agent.creator?(produce.manifestation)).to be_falsy
  end

  it "should be publisher" do
    produce = FactoryBot.create(:produce)
    expect(produce.agent.publisher?(produce.manifestation)).to be_truthy
  end

  it "should not be publisher" do
    create = FactoryBot.create(:create)
    expect(create.agent.publisher?(create.work)).to be_falsy
  end

  describe ".import_agents" do
    it "should import agents" do
      agent_list = [{full_name: "Agent 1"}, {full_name: "Agent 2"}]
      agents = Agent.import_agents(agent_list)
      expect(agents).to be_truthy
      expect(agents.first).to be_truthy
      expect(agents.first.full_name).to eq "Agent 1"
      expect(agents.last).to be_truthy
      expect(agents.last.full_name).to eq "Agent 2"
    end
    it "should import place" do
      agent_list = [{full_name: "Agent 1", place: "place"}]
      agents = Agent.import_agents(agent_list)
      expect(agents.first).to be_truthy
      expect(agents.first.place).to eq "place"
    end
    it "should unique the same agent" do
      agent_list = [{full_name: "Agent 1", place: "place"}, {full_name: "Agent 1"}]
      agents = Agent.import_agents(agent_list)
      expect(agents.size).to be 1
    end
    it "should distinguish the agents even with the same full_name" do
      agent_list = [{full_name: "Agent 1", place: "place 1"}, {full_name: "Agent 1", place: "place 2"}]
      agents = Agent.import_agents(agent_list)
      expect(agents.size).to be 2
    end
  end
end

# == Schema Information
#
# Table name: agents
#
#  id                                  :bigint           not null, primary key
#  last_name                           :string
#  middle_name                         :string
#  first_name                          :string
#  last_name_transcription             :string
#  middle_name_transcription           :string
#  first_name_transcription            :string
#  corporate_name                      :string
#  corporate_name_transcription        :string
#  full_name                           :string
#  full_name_transcription             :text
#  full_name_alternative               :text
#  created_at                          :datetime         not null
#  updated_at                          :datetime         not null
#  zip_code_1                          :string
#  zip_code_2                          :string
#  address_1                           :text
#  address_2                           :text
#  address_1_note                      :text
#  address_2_note                      :text
#  telephone_number_1                  :string
#  telephone_number_2                  :string
#  fax_number_1                        :string
#  fax_number_2                        :string
#  other_designation                   :text
#  place                               :text
#  postal_code                         :string
#  street                              :text
#  locality                            :text
#  region                              :text
#  date_of_birth                       :datetime
#  date_of_death                       :datetime
#  language_id                         :integer          default(1), not null
#  country_id                          :integer          default(1), not null
#  agent_type_id                       :integer          default(1), not null
#  lock_version                        :integer          default(0), not null
#  note                                :text
#  required_role_id                    :integer          default(1), not null
#  required_score                      :integer          default(0), not null
#  email                               :text
#  url                                 :text
#  full_name_alternative_transcription :text
#  birth_date                          :string
#  death_date                          :string
#  agent_identifier                    :string
#  profile_id                          :integer
#


text:
'use strict';

module.exports = {
    set: function (v) {
        this.setProperty('empty-cells', v);
    },
    get: function () {
        return this.getPropertyValue('empty-cells');
    },
    enumerable: true
};


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\models\Country;
use dosamigos\datepicker\DatePicker;
use yii\helpers\Url;
use kartik\password\PasswordInput;
use kartik\file\FileInput;
use backend\models\Category;

/* @var $this yii\web\View */
/* @var $model backend\models\Member */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'gender')->radioList(['Male'=>'Male','Female'=>'Female']); ?>
    <?= $form->field($model, 'dob')->widget(
    DatePicker::className(), [
        'inline' => false,
        // 'template' => '
{input}
',
        'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
        ]
    ]);?>
    <?= $form->field($model, 'phone')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'address')->textarea(['rows' => 6]) ?>
    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
    <?php echo $form->field($model, 'file_image')->widget(FileInput::classname(), [
        'options' => ['accept' => 'image/*'],
        'pluginOptions' => [
            'initialPreview'=>(!empty($model->avatar) ? Html::img(Yii::$app->request->hostInfo.Yii::$app->request->baseUrl."/..".$model->avatar,['width'=>'250px']) : false),
            'showUpload' => false,
        ]
    ]); ?>
    <?php
    $countries=Country::find()->all();
    $listData=ArrayHelper::map($countries,'country_id','name');
    ?>
    <?= $form->field($model, 'country')->dropDownList($listData, ['prompt'=>'Select...']);?>

    <?= $form->field($model, 'city')->dropDownList([], ['prompt'=>'Select...']); ?>
    <?= $form->field($model, 'password')->widget(PasswordInput::classname(), [
        'pluginOptions' => [
            'showMeter' => true,
            'toggleMask' => true
        ]
    ]); ?>
    <?= $form->field($model, 'password_repeat')->passwordInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'status')->dropDownList([0=>'Blocked',1=>'Pending',2=>'Active'], ['prompt'=>'Select...']); ?>
    <?php
    $category=Category::find()->all();
    $listData=ArrayHelper::map($category,'id_category','category');
    ?>
    <?= $form->field($model, 'id_category')->radioList($listData);?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

<?php
$null='';
use yii\web\View;
$this->registerJs("
$(document).ready(function() {
    var country = $('#member-country').val();
    if (country!='') {
       $.ajax({
        url: '".Yii::$app->urlManager->createAbsoluteUrl('member/getcity')."',
        type: 'post',
        data: 'country=' + country,
        dataType: 'json',
        success: function(json) {
            html = '<option value=".$null.">Select...</option>';
            if (json && json!= '') {
                for (i = 0; i < json.length; i++) {
                    html += '<option value=' + json[i]['zone_id'];
                    if (json[i]['zone_id'] == '".$model->city."') {
                        html += ' selected=selected';
                    }
                    html += '>' + json[i]['name'] + '</option>';
                }
            }
            $('select#member-city').html(html);
        },
    });
    }
});
$('#member-country').on('change', function() {
    var country = $('#member-country').val();
    $.ajax({
        url: '".Yii::$app->urlManager->createAbsoluteUrl('member/getcity')."',
        type: 'post',
        data: 'country=' + country,
        dataType: 'json',
        success: function(json) {
            html = '<option value=".$null.">Select...</option>';
            if (json && json!= '') {
                for (i = 0; i < json.length; i++) {
                    html += '<option value=' + json[i]['zone_id'] + '>' + json[i]['name'] + '</option>';
                }
            }
            $('select#member-city').html(html);
        },
    });
});", View::POS_END);
?>


text:
<?php

namespace Symfony\Component\DomCrawler;

/**
 * Link represents an HTML link (an HTML a tag).
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @api
 */
class Link
{
    /**
     * @var \DOMNode A \DOMNode instance
     */
    protected $node;
    /**
     * @var string The method to use for the link
     */
    protected $method;
    /**
     * @var string The URI of the page where the link is embedded (or the base href)
     */
    protected $currentUri;

    /**
     * Constructor.
     *
     * @param \DOMNode $node       A \DOMNode instance
     * @param string   $currentUri The URI of the page where the link is embedded (or the base href)
     * @param string   $method     The method to use for the link (get by default)
     *
     * @throws \InvalidArgumentException if the node is not a link
     *
     * @api
     */
    public function __construct(\DOMNode $node, $currentUri, $method = 'GET')
    {
        if (!in_array(strtolower(substr($currentUri, 0, 4)), array('http', 'file'))) {
            throw new \InvalidArgumentException(sprintf('Current URI must be an absolute URL ("%s").', $currentUri));
        }

        $this->setNode($node);
        $this->method = $method ? strtoupper($method) : null;
        $this->currentUri = $currentUri;
    }

    /**
     * Gets the node associated with this link.
     *
     * @return \DOMNode A \DOMNode instance
     */
    public function getNode()
    {
        return $this->node;
    }

    /**
     * Gets the method associated with this link.
     *
     * @return string The method
     *
     * @api
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * Gets the URI associated with this link.
     *
     * @return string The URI
     *
     * @api
     */
    public function getUri()
    {
        $uri = trim($this->getRawUri());

        // absolute URL?
        if (null !== parse_url($uri, PHP_URL_SCHEME)) {
            return $uri;
        }

        // empty URI
        if (!$uri) {
            return $this->currentUri;
        }

        // only an anchor
        if ('#' === $uri[0]) {
            $baseUri = $this->currentUri;
            if (false !== $pos = strpos($baseUri, '#')) {
                $baseUri = substr($baseUri, 0, $pos);
            }

            return $baseUri.$uri;
        }

        // only a query string
        if ('?' === $uri[0]) {
            $baseUri = $this->currentUri;

            // remove the query string from the current uri
            if (false !== $pos = strpos($baseUri, '?')) {
                $baseUri = substr($baseUri, 0, $pos);
            }

            return $baseUri.$uri;
        }

        // absolute path
        if ('/' === $uri[0]) {
            return preg_replace('#^(.*?//[^/]+)(?:\/.*)?$#', '$1', $this->currentUri).$uri;
        }

        // relative path
        return substr($this->currentUri, 0, strrpos($this->currentUri, '/') + 1).$uri;
    }

    /**
     * Returns raw uri data.
     *
     * @return string
     */
    protected function getRawUri()
    {
        return $this->node->getAttribute('href');
    }

    /**
     * Sets current \DOMNode instance.
     *
     * @param \DOMNode $node A \DOMNode instance
     *
     * @throws \LogicException If given node is not an anchor
     */
    protected function setNode(\DOMNode $node)
    {
        if ('a' != $node->nodeName) {
            throw new \LogicException(sprintf('Unable to click on a "%s" tag.', $node->nodeName));
        }

        $this->node = $node;
    }
}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased] - YYYY-MM-DD
#### Added
#### Changed
#### Deprecated
#### Removed
#### Fixed
#### Security

## [2.2.0] - 2016-02-05
#### Added
- Passing request `url` details to the layout and page props.

## [2.1.0] - 2016-02-05
#### Changed
- Referencing [Babel](https://babeljs.io/) dependencies via `js-babel-ui` and `js-babel-dev` modules.
- Linting updated to use [AirBnB style guide](https://github.com/airbnb/javascript).

## [2.0.0] - 2015-12-29
#### Added
- `webpackLoaders` parameter allowing custom loaders to be passed into the middleware.

#### Removed
- Lodash references (from webpack settings as well). Now using Ramda.

## [1.2.2] - 2015-12-24
#### Changed
- Updated ES6 compiler to use Babel version 6 (from Babel version 5).

## [1.2.0] - 2015-11-26
#### Added
- Lint command within the `prepublish` script.

#### Changed
- Increase required node version to `^5.0.0`

#### Removed
- Init script that copied react into the root `node_modules`.  No longer needed given the way Node 5 manages modules.


text:
namespace str{

class split
{
    std::string const seperator;

    void _split(std::vector<std::string>& v,std::string const& s) const
    {
        auto const spos = s.find(seperator);
        v.push_back(s.substr(0,spos));
        if(spos != std::string::npos){
            _split(v,s.substr(spos+seperator.size()));
        }
    }

public:
    split(std::string const& seperator):
        seperator(seperator)
    {}

    std::vector<std::string> operator () (std::string const& s) const
    {
        std::vector<std::string> v;
        _split(v,s);
        return v;
    }
};

}

#endif