text:
/*
File: qpcr_pools.js
URL: /static/js/qpcr_pools.js
Powers /qpcr_pools - template is run_dir/design/qpcr_pools.html
*/

$(document).ready(function() {
    // Load the data
    load_table();
});
// Initialize sorting and searching javascript plugin

function load_table() {
  var colspan = $('#pools_table > thead > tr:first > th').length + 1; // adding the first column
  $("#pools_table_body").html('
 Loading..
');
  return $.getJSON('/api/v1/qpcr_pools', function(data) {
    $("#pools_table_body").empty();
    $.each(data, function(flow, containers) {
      if(!($.isEmptyObject(containers))){
        $.each(containers, function(container, pools){
          var avg_wait_calc = 0;
          var tbl_row = $('
');
          tbl_row.append($('').html(flow));
          tbl_row.append($('').html(function() {
              var to_return = '';
              to_return = to_return + container + ' '+pools['samples'].length+'';
              to_return = to_return + '
 \

';
              to_return = to_return + '

Sample	Well	Waiting (in days)

';
              $.each(pools['samples'], function(pool, sample){
                var wait = getDaysAndDateLabel(sample['queue_time'], 'date')[0];
                to_return = to_return +
                '
'+
                  ''+sample['name']+'	'+
                  ''+sample['well']+'	'+
                  ''+wait+'	'+
                '
';
                //use avg_wait_calc as a counter
                avg_wait_calc = avg_wait_calc + wait;
                });
                to_return = to_return +'
';
              return to_return;
          }));
          tbl_row.append($('').html(function(){
            var to_return = '';
            $.each( pools['projects'], function(pid, pname){
              to_return = to_return + '
'+pname+' ('+pid+')
'
            });
            return to_return;
          }));
          tbl_row.append($('').html(function(){
            var to_return = '';
            $.each( pools['library_types'], function(i, library_type){
              to_return = to_return + '
'+ library_type +'
'
            });
            return to_return;
          }));
          tbl_row.append($('').html(function(){
            var to_return = '';
            $.each( pools['sequencing_platforms'], function(i, seq_platform){
              to_return = to_return + '
'+ seq_platform +'
'
            });
            return to_return;
          }));
          tbl_row.append($('').html(function(){
            var to_return = '';
            $.each( pools['flowcells'], function(i, flowcell){
              to_return = to_return + '
'+ flowcell +'
'
            });
            return to_return;
          }));
          tbl_row.append($('').html(function(){
            var to_return = '';
            $.each( pools['proj_queue_dates'], function(i, queued_date){
              to_return = to_return + '
'+ queued_date +'
'
            });
            return to_return;
          }));
          //get average wait time for all samples in a pool.
          avg_wait_calc = avg_wait_calc/pools['samples'].length;
          var daysAndLabel = getDaysAndDateLabel(avg_wait_calc, 'label');
          tbl_row.append($('').html(''+(avg_wait_calc).toFixed(1)+''));
          $("#pools_table_body").append(tbl_row);
        })
      }
    })
    init_listjs();
  })
}

function init_listjs() {
    // Setup - add a text input to each footer cell
    $('#pools_table tfoot th').each( function () {
      var title = $('#pools_table thead th').eq( $(this).index() ).text();
      $(this).html( '<input size=10 type="text" placeholder="Search '+title+'" />' );
    } );

    var table = $('#pools_table').DataTable({
      "columnDefs": [
          { "visible": false, "targets": 0 }
      ],
      "paging":false,
      "info":false,
      "order": [],
      "drawCallback": function ( settings ) {
        var api = this.api();
        var rows = api.rows( {page:'current'} ).nodes();
        var last=null;
        api.column(0, {page:'current'} ).data().each( function ( group, i ) {
          if ( last !== group ) {
            $(rows).eq( i ).before(
                '
 thead > tr:first > th').length + 1+'">'+group+'
'
            );
            last = group;
          }
        });
      }
    });

    //Add the bootstrap classes to the search thingy
    $('div.dataTables_filter input').addClass('form-control search search-query');
    $('#pools_table_filter').addClass('form-inline float-right');
    $("#pools_table_filter").appendTo("h1");
    $('#pools_table_filter label input').appendTo($('#pools_table_filter'));
    $('#pools_table_filter label').remove();
    $("#pools_table_filter input").attr("placeholder", "Search..");
    // Apply the search
    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            that
            .search( this.value )
            .draw();
        } );
    } );
    $('.expand-proj').on('click', function () {
      if($(this).parent().find('table').css('visibility')=='collapse'){
        $(this).find('.fa').toggleClass('fa-plus-square fa-minus-square');
        $(this).parent().find('table').css('visibility', 'visible');
      }
      else {
        $(this).find('.fa').toggleClass('fa-minus-square fa-plus-square');
        $(this).parent().find('table').css('visibility', 'collapse');
      }
    });
    $('.expand-all').on('click', function () {
      var reqText = {'Expand All': ['Collapse All', 'visible', 'fa-plus-square', 'fa-minus-square'],
                      'Collapse All': ['Expand All', 'collapse', 'fa-minus-square', 'fa-plus-square']};
      $('.expand-all').find('.fa').removeClass(reqText[$('.expand-all').text()][2]);
      $('#pools_table').find('tr').find('.fa').removeClass(reqText[$('.expand-all').text()][2]);
      $('.expand-all').find('.fa').addClass(reqText[$('.expand-all').text()][3]);
      $('#pools_table').find('tr').find('.fa').addClass(reqText[$('.expand-all').text()][3]);
      $('#pools_table').find('tr').find('table').css('visibility', reqText[$('.expand-all').text()][1]);
      $('.expand-all').contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith(reqText[$('.expand-all').text()][0]);
    });
}

$('body').on('click', '.group', function(event) {
  $($("#pools_table").DataTable().column(0).header()).trigger("click")
});

function getDaysAndDateLabel(date, option){
  var number_of_days = 0;
  var label = '';
  if( option=='date' || option=='both' ){
    //calculate number of days from given date to current date
    number_of_days = Math.floor(Math.abs(new Date() - new Date(date))/(1000*86400));
  }
  if (option=='label' || option=='both') {
    if (option=='label'){
      number_of_days = date;
    }
    if (number_of_days < 7){
      label =  'success';
    }
    else if (number_of_days >= 7 && number_of_days < 14) {
      label = 'warning';
    }
    else {
      label = 'danger';
    }
  }
   return [number_of_days, label];
}

// Copy project samples table to clipboard
var clipboard = new Clipboard('#pools_copy_table');
clipboard.on('success', function(e) {
  e.clearSelection();
  $('#pools_copy_table_btn').addClass('active').html(' Copied!');
  setTimeout(function(){
    $('#pools_copy_table_btn').removeClass('active').html(' Copy table');
  }, 2000);
});

$('#pools_copy_table_btn').on('click', function () {
  $('.expand-all').click();
  $('#pools_copy_table').click();
  $('.expand-all').click();
})


text:
#include <aws/email/model/InvalidSnsTopicException.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace SES
{
namespace Model
{

InvalidSnsTopicException::InvalidSnsTopicException() :
    m_topicHasBeenSet(false)
{
}

InvalidSnsTopicException::InvalidSnsTopicException(const XmlNode& xmlNode) :
    m_topicHasBeenSet(false)
{
  *this = xmlNode;
}

InvalidSnsTopicException& InvalidSnsTopicException::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode topicNode = resultNode.FirstChild("Topic");
    if(!topicNode.IsNull())
    {
      m_topic = Aws::Utils::Xml::DecodeEscapedXmlText(topicNode.GetText());
      m_topicHasBeenSet = true;
    }
  }

  return *this;
}

void InvalidSnsTopicException::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_topicHasBeenSet)
  {
      oStream << location << index << locationValue << ".Topic=" << StringUtils::URLEncode(m_topic.c_str()) << "&";
  }

}

void InvalidSnsTopicException::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_topicHasBeenSet)
  {
      oStream << location << ".Topic=" << StringUtils::URLEncode(m_topic.c_str()) << "&";
  }
}

} // namespace Model
} // namespace SES
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
namespace arm{

//-----------------------------------------------------------------------------
// Function to set damping constant
//-----------------------------------------------------------------------------
double set_damping(int material){

   return 0.1;

}

}


text:
<?php

namespace Mizmoz\Router\Tests\Parser;

use Mizmoz\Router\Parser\Plain;
use Mizmoz\Router\Parser\Result;
use Mizmoz\Router\Tests\TestCase;

class PlainTest extends TestCase
{
    public function testSimpleMatch()
    {
        $result = (new Plain('/'))->match('/');
        $this->assertEquals(Result::MATCH_FULL, $result->match());
    }

    public function testPartialMatch()
    {
        $result = (new Plain('/'))->match('/app');
        $this->assertEquals(Result::MATCH_PARTIAL, $result->match());
        $this->assertEquals('/app', $result->getUri());
    }

    public function testLongPartialMatch()
    {
        $result = (new Plain('/app'))->match('/app/users');
        $this->assertEquals(Result::MATCH_PARTIAL, $result->match());
        $this->assertEquals('/users', $result->getUri());
    }

    public function testNotPartialMatch()
    {
        $result = (new Plain('/app'))->match('/application');
        $this->assertEquals(Result::MATCH_NONE, $result->match());
    }

    public function testMatchWithVariable()
    {
        $result = (new Plain('/user/:userId'))->match('/user/123');
        $this->assertEquals(Result::MATCH_FULL, $result->match());
        $this->assertEquals([
            'userId' => '123',
        ], $result->getVariables());
    }

    public function testMatchWithMultipleVariables()
    {
        $result = (new Plain('/user/:userId/:action'))->match('/user/123/edit');
        $this->assertEquals(Result::MATCH_FULL, $result->match());
        $this->assertEquals([
            'userId' => '123',
            'action' => 'edit',
        ], $result->getVariables());
    }

    public function testMatchWithMultipleVariablesPartialMatch()
    {
        $result = (new Plain('/user/:userId'))->match('/user/123/edit');
        $this->assertEquals(Result::MATCH_PARTIAL, $result->match());
        $this->assertEquals([
            'userId' => '123',
        ], $result->getVariables());
    }

    public function testMatchWildcard()
    {
        $result = (new Plain('/*'))->match('/app');
        $this->assertEquals(Result::MATCH_FULL, $result->match());
    }

    public function testNoMatchWildcard()
    {
        $result = (new Plain('/app/*'))->match('/application/cheese');
        $this->assertEquals(Result::MATCH_NONE, $result->match());
    }
}


text:
<?php

namespace Gitcolab\Bundle\AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Gitcolab\Bundle\AppBundle\DependencyInjection\Compiler\OverrideServiceCompilerPass;
use Gitcolab\Bundle\AppBundle\DependencyInjection\Compiler\GitcolabListenersPass;

class GitcolabAppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        $mappings = array(
            realpath(__DIR__ . '/Resources/config/doctrine/model') => 'Gitcolab\Bundle\AppBundle\Model',
        );

        $ormCompilerClass = 'Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass';

        if (class_exists($ormCompilerClass)) {
            $container->addCompilerPass(
                DoctrineOrmMappingsPass::createXmlMappingDriver(
                    $mappings,
                    array('gitcolab_app.model_manager_name'),
                    'gitcolab_app.backend_type_orm'
                ));
        }
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <sundials/sundials_math.h>

#define ZERO RCONST(0.0)
#define ONE  RCONST(1.0)

realtype SUNRpowerI(realtype base, int exponent)
{
  int i, expt;
  realtype prod;

  prod = ONE;
  expt = abs(exponent);
  for(i = 1; i <= expt; i++) prod *= base;
  if (exponent < 0) prod = ONE/prod;
  return(prod);
}

realtype SUNRpowerR(realtype base, realtype exponent)
{
  if (base <= ZERO) return(ZERO);

#if defined(SUNDIALS_USE_GENERIC_MATH)
  return((realtype) pow((double) base, (double) exponent));
#elif defined(SUNDIALS_DOUBLE_PRECISION)
  return(pow(base, exponent));
#elif defined(SUNDIALS_SINGLE_PRECISION)
  return(powf(base, exponent));
#elif defined(SUNDIALS_EXTENDED_PRECISION)
  return(powl(base, exponent));
#endif
}


text:
/**
Written by: Smyth Chang
Description: The CWindow class creates a window for use.
*/

#pragma once
#include <Windows.h>

#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define WINDOW_TITLE L"Engine test"

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wparam, LPARAM lparam);

class CWindow
{
private:
	WNDCLASSEX wndClass;

public:
	CWindow();
	~CWindow();

	void init(HWND &hWnd, HINSTANCE &hInstance, bool windowed);
};


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{$smarty.const.Site_Name}</title>
<link href="css/public.css" rel="stylesheet" type="text/css" />

{include file="header.html"}

{include file="menu.html"}

			{if $BTP[$get.open].advanced}
高级查询
{/if}
			{if $BTP[$get.open].add}
添加产品
{/if}
			{if $BTP[$get.open].show}
产品管理
{/if}

			<form action="{write_url url=$thisurl go='append'}" method="post" enctype="multipart/form-data">

{if $get.action != 'edit'}添加产品{else}编辑产品{/if}

						编号

						{if $get.action == 'add'}
							<input type="text" name="ProID" value="{$edit.ProID}" style="width:30%" />
							<input type="checkbox" name="to_NO" id="to_NO" value="auto" onclick="sto_NO(this)" />系统生成
							<input type="button" class="Find" value="检测" onclick="check_NO(this)" />
							注:编号具有唯一性,不能重复
						{else}{$edit.ProID}{/if}

						原编号
						<input type="text" name="previousNO" value="{$edit.previousNO}" style="width:250px" />

						状态

							<select name="status">
								<option value="0">请选择产品状态</option>
								{foreach item=ts key=sy from=$status}<option value="{$sy}" {selected val=$edit.status str=$sy}>{$ts}</option>{/foreach}
							</select>

						形状

							<select name="shape">
								<option value="0">请选择产品形状</option>
								{foreach item=ts key=sy from=$shape}<option value="{$sy}" {selected val=$edit.shape str=$sy}>{$ts}</option>{/foreach}
							</select>

						重量
						<input type="text" name="weight" id="weight" value="{$edit.weight|default:0}" style="width:80px;text-align:center" onfocus="sprintf('%.2f' , this , true)" onchange="get_bid('INTbid');get_agio('agio')" /> ct

						颜色

							<select name="color" id="color" onchange="get_bid('INTbid')">
								<option value="0">请选择产品颜色</option>
								{foreach item=ts from=$color}<option value="{$ts}" {selected val=$edit.color str=$ts}>{$ts}</option>{/foreach}
							</select>

						净度

							<select name="clarity" id="clarity" onchange="get_bid('INTbid')">
								<option value="0">请选择产品净度</option>
								{foreach item=ts from=$clarity}<option value="{$ts}" {selected val=$edit.clarity str=$ts}>{$ts}</option>{/foreach}
							</select>

						切工

							<select name="cut">
								<option value="0">请选择产品切工</option>
								{foreach item=ts from=$cut}<option value="{$ts}" {selected val=$edit.cut str=$ts}>{$ts}</option>{/foreach}
							</select>

						抛光

							<select name="buffing">
								<option value="0">请选择产品抛光</option>
								{foreach item=ts from=$cut}<option value="{$ts}" {selected val=$edit.buffing str=$ts}>{$ts}</option>{/foreach}
							</select>

						对称

							<select name="symmetry">
								<option value="0">请选择产品对称</option>
								{foreach item=ts from=$cut}<option value="{$ts}" {selected val=$edit.symmetry str=$ts}>{$ts}</option>{/foreach}
							</select>

						荧光强度

							<select name="Fent_Isity">
								<option value="0">请选择产品荧光强度</option>
								{foreach item=ts from=$Fent_Isity}<option value="{$ts}" {selected val=$edit.Fent_Isity str=$ts}>{$ts}</option>{/foreach}
							</select>

						荧光颜色

							<select name="Fent_color">
								<option value="0">请选择产品荧光颜色</option>
								{foreach item=ts from=$Fent_color}<option value="{$ts}" {selected val=$edit.Fent_color str=$ts}>{$ts}</option>{/foreach}
							</select>

						国家

							<select name="country">
								<option value="0">请选择国家</option>
								{foreach item=ts key=sy from=$country}<option value="{$sy}" {selected val=$edit.country str=$sy}>{$ts}</option>{/foreach}
							</select>

						证书类型

							<select name="diploma" onchange="to_check_Dip()">
								<option value="0">请选择产品证书类型</option>
								{foreach item=ts from=$diploma}<option value="{$ts}" {selected val=$edit.diploma str=$ts}>{$ts}</option>{/foreach}
							</select>

						证书编号

							<input type="text" name="diplomaNO" onchange="to_check_Dip()" value="{$edit.diplomaNO}" style="width:250px" />
							自动填表

						证书图像

							<input type="file" name="diplomaPhoto" size="40" style="width:300px;height:23px" />
							{if $edit.diplomaPhoto}不选择文件表示不改变原来的文件{/if}

注:当前支持的文件大小为5M,文件类型 图片:jpg , gif , bmp , png

						产品来源

							<select name="proSource" onchange="show_proSource(this , 'tab_show' , 'seller');">
								<option value="0">请选择产品来源</option>
								{foreach item=ts key=sy from=$proSource}<option value="{$sy}" {selected val=$edit.proSource str=$sy}>{$ts}</option>{/foreach}
							</select>

						商家ID
						<input type="text" name="sellerID" value="{$edit.sellerID}" style="width:250px" />

						库存地点

							<input type="text" name="stockAddress_String" value="{$edit.stockAddress}" style="width:60%;display:{if $edit.proSource && $edit.proSource != 'self'}block{else}none{/if}" />

							<select name="stockAddress_Select" style="display:{if $edit.proSource && $edit.proSource == 'self'}block{else}none{/if}">
								<option value="0">请选择库存地点</option>
								{foreach item=ts from=$stockAddress}<option value="{$ts.address}" {selected val=$edit.stockAddress str=$ts.address}>{$ts.address}</option>{/foreach}
							</select>

						测量值
						<input type="text" name="scalar_value" value="{$edit.scalar_value}" style="width:150px;" />

						全身比
						<input type="text" name="body_ratio" value="{$edit.body_ratio}" style="width:80px;text-align:center" onfocus="sprintf('%.2f' , this , true)" /> %

						台宽比
						<input type="text" name="table_width" value="{$edit.table_width}" style="width:80px;text-align:center" onfocus="sprintf('%.2f' , this , true)" /> %

						进货价
						<input type="text" name="infml" id="infml" value="{$edit.infml|default:0}" style="width:80px;text-align:center" onfocus="sprintf('%.2f' , this );" onpropertychange="get_agio('agio')" onchange="get_agio('agio')" /> 元

						数量
						<input type="text" name="amount" value="{$edit.amount|default:1}" style="width:80px;text-align:center" onfocus="sprintf('%d' , this)" />

						国际报价
						人民币 {$edit.INTbid|default:0} / ct<input id="INTbid_value" type="hidden" value="{$edit.INTbid|default:0}" />

						退点
						{$edit.agio|default:0} %

						基准退点
						<input type="text" name="baseAgio" value="{$edit.baseAgio|default:0}" style="width:80px;text-align:center" onfocus="sprintf('%.2f' , this , true)" /> %

						促销

							<input name="is_promotion" type="radio" value="Y" {checked val=$edit.is_promotion str='Y'} onclick="click_promotion(this)" /> 是
							<input name="is_promotion" type="radio" value="N" {if $get.action == 'add'}checked="checked"{else}{checked val=$edit.is_promotion str='N'}{/if} onclick="click_promotion(this)" /> 否

									开始时间 <input name='promotion_start' type="text" class="FM_date" onclick="Calendar(this)" value="{$edit.promotion_start|date_format:'%Y-%m-%d'}" readonly />
									删除

									结束时间 <input name='promotion_stop' type="text" class="FM_date" onclick="Calendar(this)" value="{$edit.promotion_stop|date_format:'%Y-%m-%d'}" readonly />
									删除

促销点 <input type="text" name="promotion_dot" value="{$edit.promotion_dot}" style="width:40px;text-align:center; margin:0 0 0 1em" maxlength="5" onfocus="sprintf('%.2f' , this , true)" /> %

						外部备注
						<textarea name="userRemark" style="width:95%;height:120px">{br_to_null str=$edit.userRemark}</textarea>

						内部备注
						<textarea name="backRemark" style="width:95%;height:120px">{br_to_null str=$edit.backRemark}</textarea>

<input type="submit" value=" 提 交 " /> <input type="reset" value=" 重 填 " />

			</form>


text:
.. include:: /global_defs.hrst

Code Templates
==============

Code templates are available in the completion proposals in code assist. They provide shortcuts for boilerplate code like main method definition and asInstanceOf invocation.

.. image:: images/feature-template-01.png
   :width: 100%
   :target: ../_images/feature-template-01.png

The list of available templates can be viewed and modified in the ``Scala → Templates`` preference page.


text:
import ShuffleDb from './db';

export const GET_SHUFFLES = 'GET_SHUFFLES';
export function getShuffles() {
    const db = new ShuffleDb();
    const shuffles = db.getShuffles();
    return { type: GET_SHUFFLES, payload: shuffles };
}

export const CREATE_SHUFFLE = 'CREATE_SHUFFLE';
export function createShuffle(props) {
    const db = new ShuffleDb();
    const shuffle = db.createShuffle(props.name, props.date, props.costPerTicket, props.numberOfTickets);
    return { type: CREATE_SHUFFLE, payload: shuffle };
}

export const DELETE_SHUFFLE = 'DELETE_SHUFFLE';
export function deleteShuffle(id) {
    const db = new ShuffleDb();
    db.deleteShuffle(id);
    return { type: DELETE_SHUFFLE, payload: id };
}

export const LOAD_DRAW = 'LOAD_DRAW';
export function loadDraw(id) {
    const db = new ShuffleDb();
    const shuffle = db.getShuffle(id);
    return { type: LOAD_DRAW, payload: shuffle };
}

export const CLEAR_DRAW = 'CLEAR_DRAW';
export function clearDraw() { return { type: CLEAR_DRAW }; }

export const START_DRAW = 'START_DRAW';
export function startDraw() { return { type: START_DRAW }; }

export const STOP_DRAW = 'STOP_DRAW';
export function stopDraw() { return { type: STOP_DRAW }; }

export const COMPLETE_DRAW = 'COMPLETE_DRAW';
export function completeDraw() { return { type: COMPLETE_DRAW }; }

export const DRAW_TICKET = 'DRAW_TICKET';
export function drawTicket(id, drawn) {
    const db = new ShuffleDb();
    db.drawTicket(id, drawn);
    return { type: DRAW_TICKET, payload: { id, drawn } };
}


text:
namespace TeaDriven.Graphology.Visualization
{
    public interface IGetMemberTypesString
    {
        string For(GraphNode graphNode);
    }
}


text:
package flag

import (
	"errors"
	"fmt"
	"strconv"
)

var ErrHelp = errors.New("flag: help requested")

type boolValue bool

func newBoolValue(val bool, p *bool) *boolValue {
	*p = val
	return (*boolValue)(p)
}

func (b *boolValue) Set(s string) error {
	v, err := strconv.ParseBool(s)
	*b = boolValue(v)
	return err
}

func (b *boolValue) Get() interface{} { return bool(*b) }

func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }

func (b *boolValue) IsBoolFlag() bool { return true }

type boolFlag interface {
	Value
	IsBoolFlag() bool
}


text:
import java.util.*;

public class Connector
{
    public static final int SEAT_JOLTAGE = 0;
    public static final int JOLTAGE_RANGE = 3;

    public Connector (boolean debug)
    {
        _differenceOne = null;
        _differenceTwo = null;
        _differenceThree = null;
        _debug = debug;
    }

    public Vector<JoltageAdapter> getDifferenceOne ()
    {
        return _differenceOne;
    }

    public Vector<JoltageAdapter> getDifferenceTwo ()
    {
        return _differenceTwo;
    }

    public Vector<JoltageAdapter> getDifferenceThree ()
    {
        return _differenceThree;
    }

    public long combinations (Vector<JoltageAdapter> adapters)
    {
        HashMap<Integer, Long> count = new HashMap<Integer, Long>();
        int index = 0;

        return check(adapters, count, index, adapters.elementAt(adapters.size() -1).outputJoltage());
    }

    public Vector<JoltageAdapter> connect (Vector<JoltageAdapter> adapters)
    {
        Vector<JoltageAdapter> toReturn = new Vector<JoltageAdapter>();
        int joltage = 0;

        _differenceOne = new Vector<JoltageAdapter>();
        _differenceTwo = new Vector<JoltageAdapter>();
        _differenceThree = new Vector<JoltageAdapter>();

        while (adapters.size() > 0)
        {
            boolean found = false;
            JoltageAdapter adapter = null;

            if (_debug)
                System.out.println("Seaching for adapter joltage: "+joltage);

            for (int i = 0; (i < adapters.size()) && !found; i++)
            {
                int current = adapters.elementAt(i).outputJoltage();

                if (_debug)
                    System.out.println("Checking adapter: "+current);

                if (current == joltage)
                {
                    adapter = adapters.elementAt(i);
                    found = true;
                }

                if ((current > joltage) && (current <= joltage + JOLTAGE_RANGE))
                {
                    if (_debug)
                        System.out.println("Adapter "+current+" within range. Have "+adapter);

                    if (adapter == null)
                        adapter = adapters.elementAt(i);
                    else
                    {
                        if (current <= adapter.outputJoltage())
                            adapter = adapters.elementAt(i);
                    }

                    if (_debug)
                        System.out.println("Adapter: "+adapter);
                }
            }

            if (_debug)
                System.out.println("Difference "+(adapter.outputJoltage() - joltage));

            switch (adapter.outputJoltage() - joltage)
            {
                case 1:
                {
                    _differenceOne.add(adapter);
                }
                break;
                case 2:
                {
                    _differenceTwo.add(adapter);
                }
                break;
                case 3:
                {
                    _differenceThree.add(adapter);
                }
                break;
                default:
                {
                    // dp nothing
                }
                break;
            }

            joltage = adapter.outputJoltage();

            toReturn.add(adapter);
            adapters.remove(adapter);
        }

        if (_debug)
        {
            System.out.println("Difference One: "+_differenceOne.size());
            System.out.println("Difference Two: "+_differenceTwo.size());
            System.out.println("Difference Three: "+_differenceThree.size());
        }

        return toReturn;
    }

    private long check (Vector<JoltageAdapter> adapters, Map<Integer, Long> count, int current, int target)
    {
        if (current + 3 == target)
            return 1;
        else
        {
            if (count.containsKey(current))
                return count.get(current);
        }

        long value = 0;

        if (adapters.contains(new JoltageAdapter(current + 1, _debug)))
            value += check(adapters, count, current + 1, target);

        if (adapters.contains(new JoltageAdapter(current + 2, _debug)))
            value += check(adapters, count, current + 2, target);

        if (adapters.contains(new JoltageAdapter(current + 3, _debug)))
            value += check(adapters, count, current + 3, target);

        count.put(current, value);

        return value;
    }

    private Vector<JoltageAdapter> _differenceOne;
    private Vector<JoltageAdapter> _differenceTwo;
    private Vector<JoltageAdapter> _differenceThree;
    private boolean _debug;
}


text: <assertion-summary></assertion-summary>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class com.sleepycat.je.EnvironmentConfig (Oracle - Berkeley DB Java Edition API)
</TITLE>

<META NAME="date" CONTENT="2010-01-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../style.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB Java Edition
 version 4.0.92

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.sleepycat.je.EnvironmentConfig

Packages that use EnvironmentConfig

com.sleepycat.je
Foundation for creating environments, databases and transactions; provides
cursor based data access.

com.sleepycat.je.jca.ra
Support for the Java Connector Architecture, which provides a standard
for connecting the J2EE platform to legacy enterprise information
systems (EIS), such as ERP systems, database systems, and legacy
applications not written in Java.

com.sleepycat.je.jmx
Implementations of JMX MBeans for JE.

com.sleepycat.je.rep

Berkeley DB Java Edition High Availability (JE HA) enables replication of JE
environments.

Uses of EnvironmentConfig in com.sleepycat.je

Methods in com.sleepycat.je that return EnvironmentConfig

 EnvironmentConfig
EnvironmentConfig.clone()

          Returns a copy of this configuration object.

 EnvironmentConfig
Environment.getConfig()

          Returns this object's configuration.

 EnvironmentConfig
EnvironmentConfig.setAllowCreate(boolean allowCreate)

          If true, creates the database environment if it doesn't already exist.

 EnvironmentConfig
EnvironmentConfig.setConfigParam(String paramName,
               String value)

 EnvironmentConfig
EnvironmentConfig.setLocking(boolean locking)

          Configures the database environment for no locking.

 EnvironmentConfig
EnvironmentConfig.setLockTimeout(long timeout,
               TimeUnit unit)

          Configures the lock timeout.

 EnvironmentConfig
EnvironmentConfig.setNodeName(String nodeName)

          Sets the user defined nodeName for the Environment.

 EnvironmentConfig
EnvironmentConfig.setReadOnly(boolean readOnly)

          Configures the database environment to be read only, and any attempt to
 modify a database will fail.

 EnvironmentConfig
EnvironmentConfig.setSharedCache(boolean sharedCache)

          If true, the shared cache is used by this environment.

 EnvironmentConfig
EnvironmentConfig.setTransactional(boolean transactional)

          Configures the database environment for transactions.

 EnvironmentConfig
EnvironmentConfig.setTxnSerializableIsolation(boolean txnSerializableIsolation)

          Configures all transactions for this environment to have Serializable
 (Degree 3) isolation.

 EnvironmentConfig
EnvironmentConfig.setTxnTimeout(long timeout,
              TimeUnit unit)

          Configures the transaction timeout.

Constructors in com.sleepycat.je with parameters of type EnvironmentConfig

Environment(File envHome,
            EnvironmentConfig configuration)

          Creates a database environment handle.

XAEnvironment(File envHome,
              EnvironmentConfig configuration)

          Create a database environment handle.

Uses of EnvironmentConfig in com.sleepycat.je.jca.ra

Methods in com.sleepycat.je.jca.ra with parameters of type EnvironmentConfig

 JEConnection
JEConnectionFactory.getConnection(String jeRootDir,
              EnvironmentConfig envConfig)

 JEConnection
JEConnectionFactory.getConnection(String jeRootDir,
              EnvironmentConfig envConfig,
              TransactionConfig transConfig)

Uses of EnvironmentConfig in com.sleepycat.je.jmx

Methods in com.sleepycat.je.jmx that return EnvironmentConfig

 EnvironmentConfig
JEMBeanHelper.getEnvironmentOpenConfig()

          Deprecated. If the helper was instantiated with canConfigure==true, it shows
 environment configuration attributes.

Uses of EnvironmentConfig in com.sleepycat.je.rep

Constructors in com.sleepycat.je.rep with parameters of type EnvironmentConfig

ReplicatedEnvironment(File envHome,
                      ReplicationConfig repConfig,
                      EnvironmentConfig envConfig)

          A convenience constructor that defaults the replica consistency policy
 and the initial election policy to be used.

ReplicatedEnvironment(File envHome,
                      ReplicationConfig repConfig,
                      EnvironmentConfig envConfig,
                      ReplicaConsistencyPolicy consistencyPolicy,
                      QuorumPolicy initialElectionPolicy)

          Creates a replicated environment handle and starts participating in the
 replication group as either a Master or a Replica.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB Java Edition
 version 4.0.92

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright (c) 2004-2010 Oracle.  All rights reserved.


text:
#ifndef AtomicStringHash_h
#define AtomicStringHash_h

#include "wtf/HashTraits.h"
#include "wtf/text/AtomicString.h"

namespace WTF {

struct AtomicStringHash {
    static unsigned hash(const AtomicString& key)
    {
        return key.impl()->existingHash();
    }

    static bool equal(const AtomicString& a, const AtomicString& b)
    {
        return a == b;
    }

    static const bool safeToCompareToEmptyOrDeleted = false;
};

// AtomicStringHash is the default hash for AtomicString
template<> struct HashTraits<AtomicString> : SimpleClassHashTraits<AtomicString> {
    // Unlike other types, we can return a const reference for AtomicString's
    // empty value (nullAtom).
    typedef const AtomicString& PeekOutType;

    static const AtomicString& emptyValue() { return nullAtom; }
    static PeekOutType peek(const AtomicString& value) { return value; }

    static const bool hasIsEmptyValueFunction = true;
    static bool isEmptyValue(const AtomicString& value) { return value.isNull(); }
};

} // namespace WTF

using WTF::AtomicStringHash;

#endif


text:
var characterSelect = (function() {

  function _switchCharacter(characterInput) {
    var newIndex = parseInt(characterInput.dataset.characterSelectIndex, 10);
    sheet.switcher(newIndex);
    menu.close();
    snack.render({
      message: helper.truncate(_get_name(sheet.get()), 50, true) + " now in the game."
    });
  };

  function _bind_characterOption(characterLink) {
    var input = characterLink.querySelector(".js-character-select-list-item-input");
    input.addEventListener("change", function() {
      _switchCharacter(input);
      close();
      shade.destroy();
      page.update();
      nav.scrollToTop();
    }, false);
  };

  function _bind_characterSelectToggle() {
    var characterSelectToggle = helper.e(".js-character-select-toggle");
    characterSelectToggle.addEventListener("click", function(event) {
      menu.close();
      toggle();
      page.update();
    }, false);
    characterSelectToggle.addEventListener("keydown", function(event) {
      // enter
      if (event.keyCode == 13) {
        toggle();
        page.update();
      };
    }, false);
  };

  function _bind_characterSelectControls() {
    var characterSelectAdd = helper.e(".js-character-select-add");
    var characterSelectRemove = helper.e(".js-character-select-remove");
    var characterSelectUpdate = helper.e(".js-character-select-update");
    var characterSelectImport = helper.e(".js-character-select-import");
    var characterSelectExport = helper.e(".js-character-select-export");
    var headerControlExport = helper.e(".js-header-control-export");

    characterSelectAdd.addEventListener("click", function(event) {
      menu.close();
      shade.destroy();
      close();
      sheet.add();
      page.update();
    }, false);

    characterSelectRemove.addEventListener("click", function(event) {
      close();
      sheet.remove();
      page.update();
    }, false);

    characterSelectImport.addEventListener("click", function(event) {
      close();
      sheet.import();
      page.update();
    }, false);

    characterSelectUpdate.addEventListener("click", function(event) {
      close();
      sheet.replace();
      page.update();
    }, false);

    characterSelectExport.addEventListener("click", function(event) {
      close();
      sheet.export();
      page.update();
    }, false);

    headerControlExport.addEventListener("click", function(event) {
      close();
      sheet.export();
      page.update();
    }, false);
  };

  function bind() {
    _bind_characterSelectToggle();
    _bind_characterSelectControls();
  };

  function toggle() {
    modal.destroy();
    prompt.destroy();
    menu.close();
    var body = helper.e("body");
    var characterSelect = helper.e(".js-character-select");
    var state = (body.dataset.characterSelectOpen == "true");
    if (state) {
      close();
      shade.destroy();
    } else {
      open();
      shade.render({
        action: function() {
          close();
          page.update();
        }
      });
    };
  };

  function open() {
    var body = helper.e("body");
    var characterSelect = helper.e(".js-character-select");
    var characterSelectToggle = helper.e(".js-character-select-toggle");
    body.dataset.characterSelectOpen = true;
    helper.addClass(characterSelect, "is-open");
    helper.addClass(characterSelectToggle, "is-active");
  };

  function close() {
    var body = helper.e("body");
    var characterSelect = helper.e(".js-character-select");
    var characterSelectToggle = helper.e(".js-character-select-toggle");
    body.dataset.characterSelectOpen = false;
    helper.removeClass(characterSelect, "is-open");
    helper.removeClass(characterSelectToggle, "is-active");
  };

  function update() {
    clear();
    render();
  };

  function clear() {
    var characterSelectList = helper.e(".js-character-select-list");
    while (characterSelectList.lastChild) {
      characterSelectList.removeChild(characterSelectList.lastChild);
    };
  };

  function _render_allCharacterItems() {
    var all_character = sheet.get({
      all: true
    });
    var characterSelectList = helper.e(".js-character-select-list");
    all_character.forEach(function(arrayItem, index) {
      characterSelectList.appendChild(_createCharacterItem(arrayItem, index));
    });
    var all_characterIndexInput = helper.eA(".js-character-select-list-item-input");
    all_characterIndexInput[sheet.index.get()].checked = true;
  };

  function _render_currentCharacter() {
    var characterSelectName = helper.e(".js-character-select-name");
    var characterSelectClassLevel = helper.e(".js-character-select-class-level");
    characterSelectName.textContent = _get_name(sheet.get());
    characterSelectClassLevel.textContent = helper.getObject({
      object: sheet.get(),
      path: "basics.classes.string"
    });
  };

  function _get_name(characterObject) {
    var characterName = characterObject.basics.character.name;
    if (typeof characterName == "undefined" || characterName == "" || characterName == " ") {
      characterName = "New character";
    };
    return characterName;
  };

  function _createCharacterItem(characterObject, characterIndex) {
    var characterName = _get_name(characterObject);
    var uniqueId = helper.randomString(10);
    var navCharacter = document.createElement("li");
    navCharacter.setAttribute("class", "m-character-select-list-item js-character-select-list-item-" + characterIndex);

    var input = document.createElement("input");
    input.setAttribute("id", characterName.replace(/\s+/g, "-").toLowerCase() + "-" + uniqueId);
    input.setAttribute("name", "js-all-characters");
    input.setAttribute("class", "js-character-select-list-item-input");
    input.setAttribute("type", "radio");
    input.setAttribute("tabindex", 1);
    input.setAttribute("data-character-select-index", characterIndex);

    var label = document.createElement("label");
    label.setAttribute("for", characterName.replace(/\s+/g, "-").toLowerCase() + "-" + uniqueId);
    label.setAttribute("class", "u-full-width js-character-select-list-item-label");

    var detailsSpan = document.createElement("span");
    detailsSpan.setAttribute("class", "m-character-select-list-item-details");

    var nameSpan = document.createElement("span");
    nameSpan.setAttribute("class", "m-character-select-list-item-name");
    nameSpan.textContent = characterName;

    var classLevelSpan = document.createElement("span");
    classLevelSpan.setAttribute("class", "m-character-select-list-item-class-level");
    classLevelSpan.textContent = helper.getObject({
      object: sheet.get({
        index: characterIndex
      }),
      path: "basics.classes.string"
    });

    if (characterObject.awesomeSheet.demo) {
      var demoSpan = document.createElement("span");
      demoSpan.setAttribute("class", "m-character-select-list-item-demo");
      demoSpan.textContent = "Demo";
      detailsSpan.appendChild(demoSpan);
    };

    // build module
    detailsSpan.appendChild(nameSpan);
    detailsSpan.appendChild(classLevelSpan);
    label.appendChild(detailsSpan);
    navCharacter.appendChild(input);
    navCharacter.appendChild(label);

    // bind
    _bind_characterOption(navCharacter);
    return navCharacter;
  };

  function render() {
    _render_allCharacterItems();
    _render_currentCharacter();
  };

  // exposed methods
  return {
    toggle: toggle,
    open: open,
    close: close,
    bind: bind,
    update: update,
    clear: clear,
    render: render
  };

})();


text:
#include <aws/servicecatalog/model/DeleteTagOptionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ServiceCatalog::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteTagOptionRequest::DeleteTagOptionRequest() :
    m_idHasBeenSet(false)
{
}

Aws::String DeleteTagOptionRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_idHasBeenSet)
  {
   payload.WithString("Id", m_id);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteTagOptionRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWS242ServiceCatalogService.DeleteTagOption"));
  return headers;

}


text:
class DBConnection
  def self.db
    @db ||= ActiveRecord::Base.establish_connection(
      configuration.merge(database: 'ar_sql_analyzer_test')
    )
  end

  def self.connection
    db.connection
  end

  def self.configuration
    {
      adapter: 'mysql2',
      host: 'localhost',
      encoding: 'utf8',
      usernamme: ENV["TRAVIS"] ? "travis" : "root"
    }
  end

  def self.setup_db
    conn = ActiveRecord::Base.establish_connection(configuration)
    conn.connection.execute <<-SQL
      CREATE DATABASE IF NOT EXISTS ar_sql_analyzer_test
    SQL
  end

  def self.reset
    connection.execute <<-SQL
      DROP TABLE IF EXISTS matching_table
    SQL

    connection.execute <<-SQL
      CREATE TABLE `matching_table` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `test_string` varchar(255) DEFAULT NULL,
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    SQL

    connection.execute <<-SQL
      DROP TABLE IF EXISTS second_matching_table
    SQL

    connection.execute <<-SQL
      CREATE TABLE `second_matching_table` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `test_string` varchar(255) DEFAULT NULL,
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    SQL

    connection.execute <<-SQL
      DROP TABLE IF EXISTS nonmatching_table
    SQL

    connection.execute <<-SQL
      CREATE TABLE `nonmatching_table` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `test_string` varchar(255) DEFAULT NULL,
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    SQL
  end
end


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Serializer;

use ApiPlatform\Serializer\ResourceList;
use PHPUnit\Framework\TestCase;

class ResourceListTest extends TestCase
{
    private ResourceList $resourceList;

    protected function setUp(): void
    {
        $this->resourceList = new ResourceList();
    }

    public function testImplementsArrayObject(): void
    {
        $this->assertInstanceOf(\ArrayObject::class, $this->resourceList);
    }
}


text:
package circqueue

import (
	"github.com/pkg/errors"
)

// Queue is a circular queue of fixed length
// s is the oldest element in the queue or -1 if there are no elements
// t is the newest element in the queue or -1 if there are no elements
// a is a slice of fixed length that will hold the elements of the queue
// but those elements can only be read considering s and t
// Internal implementation: we will always have t greater or equal to s,
// considering they are on a circle with the pozitive sens
// from west ( 0 ) to est ( capacity ).
// s can never pass by t ( when they are equal on pop, they will be resetted )
// t is always at least s, and t cannot become equal to s on push, as that will mean full queue
// Can we make it variable size, meaning that when we make a push on full queue, to increase the queue ?
// Can we also decrease the size, if we find we have too many uoccupied places ?
type Queue struct {
	s, t int
	a    []int
}

func New(cap int) *Queue {
	return &Queue{
		s: -1,
		t: -1,
		a: make([]int, cap),
	}
}

func (q *Queue) Pop() (int, error) {
	if q.s == -1 {
		return 0, errors.New("no more elements")
	}
	el := q.a[q.s]
	if q.s == q.t {
		// no more elements, reset
		q.s, q.t = -1, -1
	} else {
		// we set the oldest element to be the next one,
		// which exists because there is at least one more element
		q.s = (q.s + 1) % cap(q.a)
	}
	return el, nil
}

func (q *Queue) Push(el int) error {
	// if there are no elements
	if q.t == -1 {
		q.a[0] = el
		q.s, q.t = 0, 0
		return nil
	}
	// we set the next element,
	// unless the next element is the oldest element
	// which would mean that the queue is full
	newIndex := (q.t + 1) % cap(q.a)
	if newIndex == q.s {
		return errors.New("we are full")
	}
	q.a[newIndex] = el
	q.t = newIndex
	return nil

}


text:
package org.craft.spoonge.modifiers;

import org.craft.client.render.fonts.*;
import org.craft.modding.modifiers.*;
import org.spongepowered.api.text.format.*;
import org.spongepowered.api.text.format.TextStyle.Base;

@BytecodeModifier(value = "org.spongepowered.api.text.format.TextStyles", replaceStaticBlock = true)
public class SpoongeTextStyles
{

    @Shadow
    public SpoongeTextStyles()
    {
        ;
    }

    @Shadow
    public static final TextStyle.Base OBFUSCATED    = new Base("obfuscated", TextFormatting.OBFUSCATED.toString().charAt(1));

    @Shadow
    public static final TextStyle.Base BOLD          = new Base("bold", TextFormatting.BOLD.toString().charAt(1));

    @Shadow
    public static final TextStyle.Base STRIKETHROUGH = new Base("strikethrough", 's');                                        // TODO: Add corresponding TextFormatting

    @Shadow
    public static final TextStyle.Base UNDERLINE     = new Base("underline", TextFormatting.UNDERLINED.toString().charAt(1));

    @Shadow
    public static final TextStyle.Base ITALIC        = new Base("italic", TextFormatting.ITALIC.toString().charAt(1));

    /**
     * Resets all currently applied text styles to their default values.
     */
    @Shadow
    public static final TextStyle.Base RESET         = new Base("reset", TextFormatting.RESET.toString().charAt(1));
}


text:
from math import floor
from world import World
import queue
import socketserver
import datetime
import random
import re
import requests
import sqlite3
import sys
import threading
import time
import traceback

DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 4080

DB_PATH = 'craft.db'
LOG_PATH = 'log.txt'

CHUNK_SIZE = 32
BUFFER_SIZE = 4096
COMMIT_INTERVAL = 5

AUTH_REQUIRED = True
AUTH_URL = 'https://craft.michaelfogleman.com/api/1/access'

DAY_LENGTH = 600
SPAWN_POINT = (0, 0, 0, 0, 0)
RATE_LIMIT = False
RECORD_HISTORY = False
INDESTRUCTIBLE_ITEMS = set([16])
ALLOWED_ITEMS = set([
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    17, 18, 19, 20, 21, 22, 23,
    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63])

AUTHENTICATE = 'A'
BLOCK = 'B'
CHUNK = 'C'
DISCONNECT = 'D'
KEY = 'K'
LIGHT = 'L'
NICK = 'N'
POSITION = 'P'
REDRAW = 'R'
SIGN = 'S'
TALK = 'T'
TIME = 'E'
VERSION = 'V'
YOU = 'U'

try:
    from config import *
except ImportError:
    pass

def log(*args):
    now = datetime.datetime.utcnow()
    line = ' '.join(map(str, (now,) + args))
    print(line)
    with open(LOG_PATH, 'a') as fp:
        fp.write('%s\n' % line)

def chunked(x):
    return int(floor(round(x) / CHUNK_SIZE))

def packet(*args):
    return '%s\n' % ','.join(map(str, args))

class RateLimiter(object):
    def __init__(self, rate, per):
        self.rate = float(rate)
        self.per = float(per)
        self.allowance = self.rate
        self.last_check = time.time()
    def tick(self):
        if not RATE_LIMIT:
            return False
        now = time.time()
        elapsed = now - self.last_check
        self.last_check = now
        self.allowance += elapsed * (self.rate / self.per)
        if self.allowance > self.rate:
            self.allowance = self.rate
        if self.allowance < 1:
            return True # too fast
        else:
            self.allowance -= 1
            return False # okay

class Server(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True
    daemon_threads = True

class Handler(socketserver.BaseRequestHandler):
    def setup(self):
        self.position_limiter = RateLimiter(100, 5)
        self.limiter = RateLimiter(1000, 10)
        self.version = None
        self.client_id = None
        self.user_id = None
        self.nick = None
        self.queue = queue.Queue()
        self.running = True
        self.start()
    def handle(self):
        model = self.server.model
        model.enqueue(model.on_connect, self)
        try:
            buf = []
            while True:
                data = self.request.recv(BUFFER_SIZE)
                if not data:
                    break
                buf.extend(data.decode().replace('\r\n', '\n'))
                while '\n' in buf:
                    index = buf.index('\n')
                    line = ''.join(buf[:index])
                    buf = buf[index + 1:]
                    if not line:
                        continue
                    if line[0] == POSITION:
                        if self.position_limiter.tick():
                            log('RATE', self.client_id)
                            self.stop()
                            return
                    else:
                        if self.limiter.tick():
                            log('RATE', self.client_id)
                            self.stop()
                            return
                    model.enqueue(model.on_data, self, line)
        finally:
            model.enqueue(model.on_disconnect, self)
    def finish(self):
        self.running = False
    def stop(self):
        self.request.close()
    def start(self):
        thread = threading.Thread(target=self.run)
        thread.setDaemon(True)
        thread.start()
    def run(self):
        while self.running:
            try:
                buf = []
                try:
                    buf.append(self.queue.get(timeout=5))
                    try:
                        while True:
                            buf.append(self.queue.get(False))
                    except queue.Empty:
                        pass
                except queue.Empty:
                    continue
                data = ''.join(buf)
                self.request.sendall(data.encode())
            except Exception:
                self.request.close()
                raise
    def send_raw(self, data):
        if data:
            self.queue.put(data)
    def send(self, *args):
        self.send_raw(packet(*args))

class Model(object):
    def __init__(self, seed):
        self.world = World(seed)
        self.clients = []
        self.queue = queue.Queue()
        self.commands = {
            AUTHENTICATE: self.on_authenticate,
            CHUNK: self.on_chunk,
            BLOCK: self.on_block,
            LIGHT: self.on_light,
            POSITION: self.on_position,
            TALK: self.on_talk,
            SIGN: self.on_sign,
            VERSION: self.on_version,
        }
        self.patterns = [
            (re.compile(r'^/nick(?:\s+([^,\s]+))?$'), self.on_nick),
            (re.compile(r'^/spawn$'), self.on_spawn),
            (re.compile(r'^/goto(?:\s+(\S+))?$'), self.on_goto),
            (re.compile(r'^/pq\s+(-?[0-9]+)\s*,?\s*(-?[0-9]+)$'), self.on_pq),
            (re.compile(r'^/help(?:\s+(\S+))?$'), self.on_help),
            (re.compile(r'^/list$'), self.on_list),
        ]
    def start(self):
        thread = threading.Thread(target=self.run)
        thread.setDaemon(True)
        thread.start()
    def run(self):
        self.connection = sqlite3.connect(DB_PATH)
        self.create_tables()
        self.commit()
        while True:
            try:
                if time.time() - self.last_commit > COMMIT_INTERVAL:
                    self.commit()
                self.dequeue()
            except Exception:
                traceback.print_exc()
    def enqueue(self, func, *args, **kwargs):
        self.queue.put((func, args, kwargs))
    def dequeue(self):
        try:
            func, args, kwargs = self.queue.get(timeout=5)
            func(*args, **kwargs)
        except queue.Empty:
            pass
    def execute(self, *args, **kwargs):
        return self.connection.execute(*args, **kwargs)
    def commit(self):
        self.last_commit = time.time()
        self.connection.commit()
    def create_tables(self):
        queries = [
            'create table if not exists block ('
            '    p int not null,'
            '    q int not null,'
            '    x int not null,'
            '    y int not null,'
            '    z int not null,'
            '    w int not null'
            ');',
            'create unique index if not exists block_pqxyz_idx on '
            '    block (p, q, x, y, z);',
            'create table if not exists light ('
            '    p int not null,'
            '    q int not null,'
            '    x int not null,'
            '    y int not null,'
            '    z int not null,'
            '    w int not null'
            ');',
            'create unique index if not exists light_pqxyz_idx on '
            '    light (p, q, x, y, z);',
            'create table if not exists sign ('
            '    p int not null,'
            '    q int not null,'
            '    x int not null,'
            '    y int not null,'
            '    z int not null,'
            '    face int not null,'
            '    text text not null'
            ');',
            'create index if not exists sign_pq_idx on sign (p, q);',
            'create unique index if not exists sign_xyzface_idx on '
            '    sign (x, y, z, face);',
            'create table if not exists block_history ('
            '   timestamp real not null,'
            '   user_id int not null,'
            '   x int not null,'
            '   y int not null,'
            '   z int not null,'
            '   w int not null'
            ');',
        ]
        for query in queries:
            self.execute(query)
    def get_default_block(self, x, y, z):
        p, q = chunked(x), chunked(z)
        chunk = self.world.get_chunk(p, q)
        return chunk.get((x, y, z), 0)
    def get_block(self, x, y, z):
        query = (
            'select w from block where '
            'p = :p and q = :q and x = :x and y = :y and z = :z;'
        )
        p, q = chunked(x), chunked(z)
        rows = list(self.execute(query, dict(p=p, q=q, x=x, y=y, z=z)))
        if rows:
            return rows[0][0]
        return self.get_default_block(x, y, z)
    def next_client_id(self):
        result = 1
        client_ids = set(x.client_id for x in self.clients)
        while result in client_ids:
            result += 1
        return result
    def on_connect(self, client):
        client.client_id = self.next_client_id()
        client.nick = 'guest%d' % client.client_id
        log('CONN', client.client_id, *client.client_address)
        client.position = SPAWN_POINT
        self.clients.append(client)
        client.send(YOU, client.client_id, *client.position)
        client.send(TIME, time.time(), DAY_LENGTH)
        client.send(TALK, 'Welcome to Craft!')
        client.send(TALK, 'Type "/help" for a list of commands.')
        self.send_position(client)
        self.send_positions(client)
        self.send_nick(client)
        self.send_nicks(client)
    def on_data(self, client, data):
        #log('RECV', client.client_id, data)
        args = data.split(',')
        command, args = args[0], args[1:]
        if command in self.commands:
            func = self.commands[command]
            func(client, *args)
    def on_disconnect(self, client):
        log('DISC', client.client_id, *client.client_address)
        self.clients.remove(client)
        self.send_disconnect(client)
        self.send_talk('%s has disconnected from the server.' % client.nick)
    def on_version(self, client, version):
        if client.version is not None:
            return
        version = int(version)
        if version != 1:
            client.stop()
            return
        client.version = version
        # TODO: client.start() here
    def on_authenticate(self, client, username, access_token):
        user_id = None
        if username and access_token:
            payload = {
                'username': username,
                'access_token': access_token,
            }
            response = requests.post(AUTH_URL, data=payload)
            if response.status_code == 200 and response.text.isdigit():
                user_id = int(response.text)
        client.user_id = user_id
        if user_id is None:
            client.nick = 'guest%d' % client.client_id
            client.send(TALK, 'Visit craft.michaelfogleman.com to register!')
        else:
            client.nick = username
        self.send_nick(client)
        # TODO: has left message if was already authenticated
        self.send_talk('%s has joined the game.' % client.nick)
    def on_chunk(self, client, p, q, key=0):
        packets = []
        p, q, key = list(map(int, (p, q, key)))
        query = (
            'select rowid, x, y, z, w from block where '
            'p = :p and q = :q and rowid > :key;'
        )
        rows = self.execute(query, dict(p=p, q=q, key=key))
        max_rowid = 0
        blocks = 0
        for rowid, x, y, z, w in rows:
            blocks += 1
            packets.append(packet(BLOCK, p, q, x, y, z, w))
            max_rowid = max(max_rowid, rowid)
        query = (
            'select x, y, z, w from light where '
            'p = :p and q = :q;'
        )
        rows = self.execute(query, dict(p=p, q=q))
        lights = 0
        for x, y, z, w in rows:
            lights += 1
            packets.append(packet(LIGHT, p, q, x, y, z, w))
        query = (
            'select x, y, z, face, text from sign where '
            'p = :p and q = :q;'
        )
        rows = self.execute(query, dict(p=p, q=q))
        signs = 0
        for x, y, z, face, text in rows:
            signs += 1
            packets.append(packet(SIGN, p, q, x, y, z, face, text))
        if blocks:
            packets.append(packet(KEY, p, q, max_rowid))
        if blocks or lights or signs:
            packets.append(packet(REDRAW, p, q))
        packets.append(packet(CHUNK, p, q))
        client.send_raw(''.join(packets))
    def on_block(self, client, x, y, z, w):
        x, y, z, w = list(map(int, (x, y, z, w)))
        p, q = chunked(x), chunked(z)
        previous = self.get_block(x, y, z)
        message = None
        if AUTH_REQUIRED and client.user_id is None:
            message = 'Only logged in users are allowed to build.'
        elif y <= 0 or y > 255:
            message = 'Invalid block coordinates.'
        elif w not in ALLOWED_ITEMS:
            message = 'That item is not allowed.'
        elif w and previous:
            message = 'Cannot create blocks in a non-empty space.'
        elif not w and not previous:
            message = 'That space is already empty.'
        elif previous in INDESTRUCTIBLE_ITEMS:
            message = 'Cannot destroy that type of block.'
        if message is not None:
            client.send(BLOCK, p, q, x, y, z, previous)
            client.send(REDRAW, p, q)
            client.send(TALK, message)
            return
        query = (
            'insert into block_history (timestamp, user_id, x, y, z, w) '
            'values (:timestamp, :user_id, :x, :y, :z, :w);'
        )
        if RECORD_HISTORY:
            self.execute(query, dict(timestamp=time.time(),
                user_id=client.user_id, x=x, y=y, z=z, w=w))
        query = (
            'insert or replace into block (p, q, x, y, z, w) '
            'values (:p, :q, :x, :y, :z, :w);'
        )
        self.execute(query, dict(p=p, q=q, x=x, y=y, z=z, w=w))
        self.send_block(client, p, q, x, y, z, w)
        for dx in range(-1, 2):
            for dz in range(-1, 2):
                if dx == 0 and dz == 0:
                    continue
                if dx and chunked(x + dx) == p:
                    continue
                if dz and chunked(z + dz) == q:
                    continue
                np, nq = p + dx, q + dz
                self.execute(query, dict(p=np, q=nq, x=x, y=y, z=z, w=-w))
                self.send_block(client, np, nq, x, y, z, -w)
        if w == 0:
            query = (
                'delete from sign where '
                'x = :x and y = :y and z = :z;'
            )
            self.execute(query, dict(x=x, y=y, z=z))
            query = (
                'update light set w = 0 where '
                'x = :x and y = :y and z = :z;'
            )
            self.execute(query, dict(x=x, y=y, z=z))
    def on_light(self, client, x, y, z, w):
        x, y, z, w = list(map(int, (x, y, z, w)))
        p, q = chunked(x), chunked(z)
        block = self.get_block(x, y, z)
        message = None
        if AUTH_REQUIRED and client.user_id is None:
            message = 'Only logged in users are allowed to build.'
        elif block == 0:
            message = 'Lights must be placed on a block.'
        elif w < 0 or w > 15:
            message = 'Invalid light value.'
        if message is not None:
            # TODO: client.send(LIGHT, p, q, x, y, z, previous)
            client.send(REDRAW, p, q)
            client.send(TALK, message)
            return
        query = (
            'insert or replace into light (p, q, x, y, z, w) '
            'values (:p, :q, :x, :y, :z, :w);'
        )
        self.execute(query, dict(p=p, q=q, x=x, y=y, z=z, w=w))
        self.send_light(client, p, q, x, y, z, w)
    def on_sign(self, client, x, y, z, face, *args):
        if AUTH_REQUIRED and client.user_id is None:
            client.send(TALK, 'Only logged in users are allowed to build.')
            return
        text = ','.join(args)
        x, y, z, face = list(map(int, (x, y, z, face)))
        if y <= 0 or y > 255:
            return
        if face < 0 or face > 7:
            return
        if len(text) > 48:
            return
        p, q = chunked(x), chunked(z)
        if text:
            query = (
                'insert or replace into sign (p, q, x, y, z, face, text) '
                'values (:p, :q, :x, :y, :z, :face, :text);'
            )
            self.execute(query,
                dict(p=p, q=q, x=x, y=y, z=z, face=face, text=text))
        else:
            query = (
                'delete from sign where '
                'x = :x and y = :y and z = :z and face = :face;'
            )
            self.execute(query, dict(x=x, y=y, z=z, face=face))
        self.send_sign(client, p, q, x, y, z, face, text)
    def on_position(self, client, x, y, z, rx, ry):
        x, y, z, rx, ry = list(map(float, (x, y, z, rx, ry)))
        client.position = (x, y, z, rx, ry)
        self.send_position(client)
    def on_talk(self, client, *args):
        text = ','.join(args)
        if text.startswith('/'):
            for pattern, func in self.patterns:
                match = pattern.match(text)
                if match:
                    func(client, *match.groups())
                    break
            else:
                client.send(TALK, 'Unrecognized command: "%s"' % text)
        elif text.startswith('@'):
            nick = text[1:].split(' ', 1)[0]
            for other in self.clients:
                if other.nick == nick:
                    client.send(TALK, '%s> %s' % (client.nick, text))
                    other.send(TALK, '%s> %s' % (client.nick, text))
                    break
            else:
                client.send(TALK, 'Unrecognized nick: "%s"' % nick)
        else:
            self.send_talk('%s> %s' % (client.nick, text))
    def on_nick(self, client, nick=None):
        if AUTH_REQUIRED:
            client.send(TALK, 'You cannot change your nick on this server.')
            return
        if nick is None:
            client.send(TALK, 'Your nickname is %s' % client.nick)
        else:
            self.send_talk('%s is now known as %s' % (client.nick, nick))
            client.nick = nick
            self.send_nick(client)
    def on_spawn(self, client):
        client.position = SPAWN_POINT
        client.send(YOU, client.client_id, *client.position)
        self.send_position(client)
    def on_goto(self, client, nick=None):
        if nick is None:
            clients = [x for x in self.clients if x != client]
            other = random.choice(clients) if clients else None
        else:
            nicks = dict((client.nick, client) for client in self.clients)
            other = nicks.get(nick)
        if other:
            client.position = other.position
            client.send(YOU, client.client_id, *client.position)
            self.send_position(client)
    def on_pq(self, client, p, q):
        p, q = list(map(int, (p, q)))
        if abs(p) > 1000 or abs(q) > 1000:
            return
        client.position = (p * CHUNK_SIZE, 0, q * CHUNK_SIZE, 0, 0)
        client.send(YOU, client.client_id, *client.position)
        self.send_position(client)
    def on_help(self, client, topic=None):
        if topic is None:
            client.send(TALK, 'Type "t" to chat. Type "/" to type commands:')
            client.send(TALK, '/goto [NAME], /help [TOPIC], /list, /login NAME, /logout, /nick')
            client.send(TALK, '/offline [FILE], /online HOST [PORT], /pq P Q, /spawn, /view N')
            return
        topic = topic.lower().strip()
        if topic == 'goto':
            client.send(TALK, 'Help: /goto [NAME]')
            client.send(TALK, 'Teleport to another user.')
            client.send(TALK, 'If NAME is unspecified, a random user is chosen.')
        elif topic == 'list':
            client.send(TALK, 'Help: /list')
            client.send(TALK, 'Display a list of connected users.')
        elif topic == 'login':
            client.send(TALK, 'Help: /login NAME')
            client.send(TALK, 'Switch to another registered username.')
            client.send(TALK, 'The login server will be re-contacted. The username is case-sensitive.')
        elif topic == 'logout':
            client.send(TALK, 'Help: /logout')
            client.send(TALK, 'Unauthenticate and become a guest user.')
            client.send(TALK, 'Automatic logins will not occur again until the /login command is re-issued.')
        elif topic == 'offline':
            client.send(TALK, 'Help: /offline [FILE]')
            client.send(TALK, 'Switch to offline mode.')
            client.send(TALK, 'FILE specifies the save file to use and defaults to "craft".')
        elif topic == 'online':
            client.send(TALK, 'Help: /online HOST [PORT]')
            client.send(TALK, 'Connect to the specified server.')
        elif topic == 'nick':
            client.send(TALK, 'Help: /nick [NICK]')
            client.send(TALK, 'Get or set your nickname.')
        elif topic == 'pq':
            client.send(TALK, 'Help: /pq P Q')
            client.send(TALK, 'Teleport to the specified chunk.')
        elif topic == 'spawn':
            client.send(TALK, 'Help: /spawn')
            client.send(TALK, 'Teleport back to the spawn point.')
        elif topic == 'view':
            client.send(TALK, 'Help: /view N')
            client.send(TALK, 'Set viewing distance, 1 - 24.')
    def on_list(self, client):
        client.send(TALK,
            'Players: %s' % ', '.join(x.nick for x in self.clients))
    def send_positions(self, client):
        for other in self.clients:
            if other == client:
                continue
            client.send(POSITION, other.client_id, *other.position)
    def send_position(self, client):
        for other in self.clients:
            if other == client:
                continue
            other.send(POSITION, client.client_id, *client.position)
    def send_nicks(self, client):
        for other in self.clients:
            if other == client:
                continue
            client.send(NICK, other.client_id, other.nick)
    def send_nick(self, client):
        for other in self.clients:
            other.send(NICK, client.client_id, client.nick)
    def send_disconnect(self, client):
        for other in self.clients:
            if other == client:
                continue
            other.send(DISCONNECT, client.client_id)
    def send_block(self, client, p, q, x, y, z, w):
        for other in self.clients:
            if other == client:
                continue
            other.send(BLOCK, p, q, x, y, z, w)
            other.send(REDRAW, p, q)
    def send_light(self, client, p, q, x, y, z, w):
        for other in self.clients:
            if other == client:
                continue
            other.send(LIGHT, p, q, x, y, z, w)
            other.send(REDRAW, p, q)
    def send_sign(self, client, p, q, x, y, z, face, text):
        for other in self.clients:
            if other == client:
                continue
            other.send(SIGN, p, q, x, y, z, face, text)
    def send_talk(self, text):
        log(text)
        for client in self.clients:
            client.send(TALK, text)

def cleanup():
    world = World(None)
    conn = sqlite3.connect(DB_PATH)
    query = 'select x, y, z from block order by rowid desc limit 1;'
    last = list(conn.execute(query))[0]
    query = 'select distinct p, q from block;'
    chunks = list(conn.execute(query))
    count = 0
    total = 0
    delete_query = 'delete from block where x = %d and y = %d and z = %d;'
    print('begin;')
    for p, q in chunks:
        chunk = world.create_chunk(p, q)
        query = 'select x, y, z, w from block where p = :p and q = :q;'
        rows = conn.execute(query, {'p': p, 'q': q})
        for x, y, z, w in rows:
            if chunked(x) != p or chunked(z) != q:
                continue
            total += 1
            if (x, y, z) == last:
                continue
            original = chunk.get((x, y, z), 0)
            if w == original or original in INDESTRUCTIBLE_ITEMS:
                count += 1
                print(delete_query % (x, y, z))
    conn.close()
    print('commit;')
    print('%d of %d blocks will be cleaned up' % (count, total), file=sys.stderr)

def main():
    if len(sys.argv) == 2 and sys.argv[1] == 'cleanup':
        cleanup()
        return
    host, port = DEFAULT_HOST, DEFAULT_PORT
    if len(sys.argv) > 1:
        host = sys.argv[1]
    if len(sys.argv) > 2:
        port = int(sys.argv[2])
    log('SERV', host, port)
    model = Model(None)
    model.start()
    server = Server((host, port), Handler)
    server.model = model
    server.serve_forever()

if __name__ == '__main__':
    main()


text:
using TimeSeries
using Reactive

nma = 50
ohlc_BA = TimeSeries.readtimearray("../../data/OHLC_BA.csv")

s_ohlc = Reactive.Input(ohlc_BA.values[1,:])
s_oc = lift(s -> (s[1], s[4]), s_ohlc, typ=(Float64, Float64))

vsig = [s_close.value - s_open.value]
function vsigupd!(vsig::Vector{Float64}, nma::Int64, nmax::Int64)
    for i in 2:nmax
        push!(s_ohlc, ohlc_BA.values[i,:])
        push!(vsig, s_oc.value[2] - s_oc.value[1])
    end
end

println("OHLC updates with 2-in-1-tuple lift-signal:")
println("reactive signal updates timing")
expr_run = parse("@time vsigupd!(vsig, nma, length(ohlc_BA))")
for i = 1:5
    eval(expr_run)
end

### results
# elapsed time: 0.21731065 seconds (23552912 bytes allocated, 17.07% gc time)
### more lift-signals really add time

Profile.clear()  # in case we have any previous profiling data
@profile vsigupd!(vsig, nma, length(ohlc_BA))
Profile.print()


text:
<?php declare(strict_types=1);

use DCarbone\PHPFHIR\Utilities\CopyrightUtils;

/** @var \DCarbone\PHPFHIR\Config\VersionConfig $config */

$rootNS = $config->getNamespace(false);

ob_start();
echo "<?php\n\n";

if ('' !== $rootNS) :
    echo "namespace {$rootNS};\n\n";
endif;

echo CopyrightUtils::getFullPHPFHIRCopyrightComment();

echo "\n\n";
?>
/**
 * Trait <?php echo PHPFHIR_TRAIT_VALIDATION_ASSERTIONS; if ('' !== $rootNS) : ?>

 * @package \<?php echo $rootNS; ?>
<?php endif; ?>

 */
trait <?php echo PHPFHIR_TRAIT_VALIDATION_ASSERTIONS; ?>

{
    /**
     * Asserts that a given collection field is of a specific minimum length
     * @param string $typeName
     * @param string $fieldName
     * @param int $expected
     * @param null|array $value)
     * @return null|string
     */
    protected function _assertMinOccurs(string $typeName, string $fieldName, int $expected, ?array $value): ?string
    {
        if (0 >= $expected) {
            return null;
        }
        if (!is_array($value) || [] === $value) {
            return sprintf('Field "%s" on type "%s" must have at least %d elements, but it is empty', $fieldName, $typeName, $expected);
        }
        if ($expected > ($cnt = count($value))) {
            return sprintf('Field "%s" on type "%s" must have at least %d elements, %d seen.', $fieldName, $typeName, $expected, $cnt);
        }
        return null;
    }

    /**
     * Asserts that a given collection field has no more than the specified number of elements
     * @param string $typeName
     * @param string $fieldName
     * @param int $expected
     * @param null|array $value
     * @return null|string
     */
    protected function _assertMaxOccurs(string $typeName, string $fieldName, int $expected, ?array $value): ?string
    {
        if (PHPFHIRConstants::UNLIMITED === $expected || null === $value || !is_array($value) || [] === $value || $expected >= ($cnt = count($value))) {
            return null;
        }
        return sprintf('Field "%s" on type "%s" must have no more than %d elements, %d seen', $fieldName, $typeName, $expected, $cnt);
    }

    /**
     * Asserts that a given string value is at least x characters long
     * @param string $typeName
     * @param string $fieldName
     * @param int $expected
     * @param null|string $value
     * @return null|string
     */
    protected function _assertMinLength(string $typeName, string $fieldName, int $expected, ?string $value): ?string
    {
        if (0 >= $expected) {
            return null;
        }
        if (!is_string($value) || '' === $value) {
            return sprintf('Field "%s" on type "%s" must be at least %d characters long, but it is empty', $fieldName, $typeName, $expected);
        }
        $cnt = strlen($value);
        if ($expected <= $cnt) {
            return null;
        }
        return sprintf('Field "%s" on type "%s" must be at least %d characters long, %d seen.', $fieldName, $typeName, $expected, $cnt);
    }

    /**
     * Asserts that a given string value is no more than x characters long
     * @param string $typeName
     * @param string $fieldName
     * @param int $expected
     * @param null|string $value
     * @return null|string
     */
    protected function _assertMaxLength(string $typeName, string $fieldName, int $expected, ?string $value): ?string
    {
        if (PHPFHIRConstants::UNLIMITED === $expected || !is_string($value) || '' === $value) {
            return null;
        }
        $cnt = strlen($value);
        if ($expected >= $cnt) {
            return null;
        }
        return sprintf('Field "%s" on type "%s" must be no more than %d characters long, %d seen', $fieldName, $typeName, $expected, $cnt);
    }

    /**
     * Asserts that a given value is within the expected list of values
     * @param string $typeName
     * @param string $fieldName
     * @param array $expected
     * @param mixed $value
     * @return null|string
     */
    protected function _assertValueInEnum(string $typeName, string $fieldName, array $expected, $value): ?string
    {
        if ([] === $expected || in_array($value, $expected, true)) {
            return null;
        }
        return sprintf(
            'Field "%s" on type "%s" value "%s" not in allowed list: [%s]',
            $fieldName,
            $typeName,
            var_export($value, true),
            implode(
                ', ',
                array_map(
                    function($v) { return var_export($v, true); },
                    $expected
                )
            )
        );
    }

    /**
     * Asserts that a given string value matches the specified pattern
     * @param string $typeName
     * @param string $fieldName
     * @param string $pattern
     * @param null|string $value
     * @return null|string
     */
    protected function _assertPatternMatch(string $typeName, string $fieldName, string $pattern, ?string $value): ?string
    {
        if (!is_string($pattern) || '' === $pattern || (bool)preg_match($pattern, $value)) {
            return null;
        }
        return sprintf('Field "%s" on type "%s" value of "%s" does not match pattern: %s', $fieldName, $typeName, $value, $pattern);
    }

    /**
     * @param string $typeName
     * @param string $fieldName
     * @param string $ruleName
     * @param mixed $constraint
     * @param mixed $value
     * @return null|string
     */
    protected function _performValidation(string $typeName, string $fieldName, string $ruleName, $constraint, $value): ?string
    {
        switch($ruleName) {
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_ENUM_NAME; ?>:
                return $this->_assertValueInEnum($typeName, $fieldName, $constraint, $value);
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_MIN_LENGTH_NAME; ?>:
                return $this->_assertMinLength($typeName, $fieldName, $constraint, $value);
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_MAX_LENGTH_NAME; ?>:
                return $this->_assertMaxLength($typeName, $fieldName, $constraint, $value);
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_MIN_OCCURS_NAME; ?>:
                return $this->_assertMinOccurs($typeName, $fieldName, $constraint, $value);
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_MAX_OCCURS_NAME; ?>:
                return $this->_assertMaxOccurs($typeName, $fieldName, $constraint, $value);
            case PHPFHIRConstants::<?php echo PHPFHIR_VALIDATION_PATTERN_NAME; ?>:
                return $this->_assertPatternMatch($typeName, $fieldName, $constraint, $value);

            default:
                return sprintf('Type "%s" specifies unknown validation for field "%s": Name "%s"; Constraint "%s"', $typeName, $fieldName, $ruleName, var_export($constraint, true));
        }
    }
}
<?php
return ob_get_clean();


text:
'use strict';

moduloZona.controller('ZonaNewController', ['$scope', '$routeParams', '$location', 'serverService', 'zonaService', 'sharedSpaceService', '$filter', '$uibModal',
    function ($scope, $routeParams, $location, serverService, zonaService, sharedSpaceService, $filter, $uibModal) {
        $scope.fields = zonaService.getFields();
        $scope.obtitle = zonaService.getObTitle();
        $scope.icon = zonaService.getIcon();
        $scope.ob = zonaService.getTitle();
        $scope.title = "Creando un nuevo " + $scope.obtitle;
        $scope.op = "plist";
        $scope.status = null;
        $scope.debugging = serverService.debugging();
        $scope.bean = {};
        $scope.bean.id = 0;

        $scope.save = function () {
            var jsonToSend = {json: JSON.stringify(serverService.array_identificarArray($scope.bean))};
            serverService.promise_setOne($scope.ob, jsonToSend).then(function (response) {
                if (response.status == 200) {
                    if (response.data.status == 200) {
                        $scope.response = response;
                        $scope.status = "El registro " + $scope.obtitle + " se ha creado con id = " + response.data.message;
                        $scope.bean.id = response.data.message;
                    } else {
                        $scope.status = "Error en la recepción de datos del servidor";
                    }
                } else {
                    $scope.status = "Error en la recepción de datos del servidor";
                }
            }).catch(function (data) {
                $scope.status = "Error en la recepción de datos del servidor";
            });
            ;
        };
        $scope.back = function () {
            window.history.back();
        };
        $scope.close = function () {
            $location.path('/home');
        };
        $scope.plist = function () {
            $location.path('/' + $scope.ob + '/plist');
        };

    }]);


text:
#ifndef BERRYDEBUGUTIL_H_
#define BERRYDEBUGUTIL_H_

#include <QHash>
#include <QSet>
#include <QList>

#include <org_blueberry_core_runtime_Export.h>

class QDir;

namespace berry {

class Object;
class DebugBreakpointManager;
struct IDebugObjectListener;
template <class T> class SmartPointer;

class org_blueberry_core_runtime_EXPORT DebugUtil
{

public:

  static DebugBreakpointManager* GetBreakpointManager();

  static void TraceObject(const Object*);
  static void TraceObject(unsigned int traceId);
  static void TraceClass(const QString& className);

  static void StopTracing(unsigned int traceId);
  static void StopTracing(const Object* obj);
  static void StopTracing(const QString& className);

  static bool IsTraced(const Object* object);
  static bool IsTraced(unsigned int traceId);
  static bool IsTraced(const QString& className);

  static QSet<unsigned int> GetTracedObjects();

  static const Object* GetObject(unsigned int traceId);

  static QList<unsigned int> GetSmartPointerIDs(const Object* objectPointer, const QList<unsigned int>& excludeList = QList<unsigned int>());
  static QList<const Object*> GetRegisteredObjects();

  static void PrintSmartPointerIDs(const Object* objectPointer, const QList<unsigned int>& excludeList = QList<unsigned int>());

  static void ResetObjectSummary();
  static bool PrintObjectSummary(bool details = false);
  static bool PrintObjectSummary(const QString& className, bool details = false);

  static void AddObjectListener(IDebugObjectListener* listener);
  static void RemoveObjectListener(IDebugObjectListener* listener);

  static void SaveState(const QDir& path);
  static void RestoreState(const QDir& path);

  // ******* for internal use only *************
  static unsigned int& GetSmartPointerCounter();
  static void RegisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer, bool recordStack = false);
  static void UnregisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer);
  static void RegisterObject(const Object* objectPointer);
  static void UnregisterObject(const Object* objectPointer);
  // *******************************************

private:

  static const QString DEBUG_UTIL_XML;

  static const QString DEBUGUTIL_TAG;
  static const QString TRACEOBJECT_TAG;
  static const QString TRACECLASS_TAG;

  static const QString ID_ATTR;
  static const QString NAME_ATTR;

  static bool GetPersistencePath(QDir& path);

  static QHash<quint32, QList<unsigned int> > m_TraceIdToSmartPointerMap;
  typedef QHash<quint32, const Object* > TraceIdToObjectType;
  static TraceIdToObjectType m_TraceIdToObjectMap;
  static QSet<unsigned int> m_TracedObjects;
  static QSet<QString> m_TracedClasses;
};

}

#endif /* BERRYDEBUGUTIL_H_ */


text:
package org.elasticsearch.index.mapper;

import org.elasticsearch.Version;
import org.elasticsearch.common.geo.SpatialStrategy;
import org.elasticsearch.index.mapper.LegacyGeoShapeFieldMapper.GeoShapeFieldType;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class LegacyGeoShapeFieldTypeTests extends FieldTypeTestCase {

    /**
     * Test for {@link LegacyGeoShapeFieldMapper.GeoShapeFieldType#setStrategy(SpatialStrategy)} that checks
     * that {@link LegacyGeoShapeFieldMapper.GeoShapeFieldType#pointsOnly()} gets set as a side effect when using SpatialStrategy.TERM
     */
    public void testSetStrategyName() {
        GeoShapeFieldType fieldType = new GeoShapeFieldType("field");
        assertFalse(fieldType.pointsOnly());
        fieldType.setStrategy(SpatialStrategy.RECURSIVE);
        assertFalse(fieldType.pointsOnly());
        fieldType.setStrategy(SpatialStrategy.TERM);
        assertTrue(fieldType.pointsOnly());
    }

    public void testFetchSourceValue() throws IOException {

        MappedFieldType mapper = new LegacyGeoShapeFieldMapper.Builder("field", Version.CURRENT, false, true)
            .build(new ContentPath()).fieldType();

        Map<String, Object> jsonLineString = Map.of("type", "LineString", "coordinates",
            List.of(List.of(42.0, 27.1), List.of(30.0, 50.0)));
        Map<String, Object> jsonPoint = Map.of("type", "Point", "coordinates", List.of(14.0, 15.0));
        String wktLineString = "LINESTRING (42.0 27.1, 30.0 50.0)";
        String wktPoint = "POINT (14.0 15.0)";

        // Test a single shape in geojson format.
        Object sourceValue = jsonLineString;
        assertEquals(List.of(jsonLineString), fetchSourceValue(mapper, sourceValue, null));
        assertEquals(List.of(wktLineString), fetchSourceValue(mapper, sourceValue, "wkt"));

        // Test a list of shapes in geojson format.
        sourceValue = List.of(jsonLineString, jsonPoint);
        assertEquals(List.of(jsonLineString, jsonPoint), fetchSourceValue(mapper, sourceValue, null));
        assertEquals(List.of(wktLineString, wktPoint), fetchSourceValue(mapper, sourceValue, "wkt"));

        // Test a single shape in wkt format.
        sourceValue = wktLineString;
        assertEquals(List.of(jsonLineString), fetchSourceValue(mapper, sourceValue, null));
        assertEquals(List.of(wktLineString), fetchSourceValue(mapper, sourceValue, "wkt"));

        // Test a list of shapes in wkt format.
        sourceValue = List.of(wktLineString, wktPoint);
        assertEquals(List.of(jsonLineString, jsonPoint), fetchSourceValue(mapper, sourceValue, null));
        assertEquals(List.of(wktLineString, wktPoint), fetchSourceValue(mapper, sourceValue, "wkt"));
    }
}


text:
Alternate signature
--FILE--
<?php
strtr("abc","def","ghi");
strtr("abc",["def"=>"ghi"]);
strtr(["def"=>"ghi"]);
--EXPECTF--
%s:4 ParamError call with 1 arg(s) to strtr() which requires 3 arg(s)
%s:4 TypeError arg#1(str) is string[] but strtr() takes string


text:
//
//  SOSegmentControl.h
//  SOKit
//
//  Created by soso on 13-2-21.
//  Copyright (c) 2013-2015 soso. All rights reserved.
//

#import "SOBaseScrollView.h"
#import "SOSegmentButton.h"
#import "SOGlobal.h"

/**
 *  @brief  默认标题个数
 */
#define DEFAULT_TITLE_COUNT 5

/**
 *  @brief  分段选项动画周期
 */
extern NSTimeInterval const SOSegmentAnimationDuration;

@class SOSegmentControl;
/**
 *  @brief  回调协议
 */
@protocol SOSegmentControlDelegate <NSObject>

/**
 *  @brief  回调选中的button和对应的索引
 *
 *  @return 无返回值
 */
- (void)segmentControl:(SOSegmentControl *)segmentControl didSelectButton:(SOSegmentButton *)button atIndex:(NSInteger)index;
@end

/**
 *  @brief  分段选项视图
 */
@interface SOSegmentControl : SOBaseScrollView
/**
 *  @brief  选中的索引
 */
@property (nonatomic, readonly) NSInteger selectedIndex;

/**
 *  @brief  能展示的item个数,items超过这个数字就会解锁自动滚动,contentCount大于items个数时会自动修正为[items count]
 */
@property (nonatomic, assign) CGFloat contentCount;

/**
 *  @brief  响应回调的对象
 */
@property (nonatomic, PROPERTYWEAK) id<SOSegmentControlDelegate> segmentDelegate;

/**
 *  @brief  下方进度条的高
 */
@property (assign, nonatomic) CGFloat currentOffsetViewHeight;

/**
 *  @brief  是否一直显示下方进度条
 */
@property (assign, nonatomic) BOOL showCurrentOffsetViewAlways;

/**
 *  @brief  get方法
 *
 *  @return 返回当前item数组
 */
- (NSArray *)items;

/**
 *  @brief  get方法
 *
 *  @return 返回索引为index的button
 */
- (SOSegmentButton *)buttonAtIndex:(NSInteger)index;

/**
 *  @brief  get方法
 *
 *  @return 显示进度的视图
 */
- (UIView *)showCurrentOffsetView;

/**
 *  @brief  set方法,设置当前item数组
 *
 *  @return 无返回值
 */
- (void)setItems:(NSArray *)items;

/**
 *  @brief  set方法,设置当前选中的索引
 *
 *  @return 无返回值
 */
- (void)setSelectedItemIndex:(NSInteger)index animated:(BOOL)animated;

/**
 *  @brief  set方法,设置当前进度
 *
 *  @return 无返回值
 */
- (void)setCurrentOffset:(CGPoint)offset animated:(BOOL)animated;

@end