text:
package org.onetwo.ext.poi.excel.etemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.onetwo.ext.poi.excel.etemplate.ETSheetContext.ETRowContext;
import org.onetwo.ext.poi.excel.etemplate.directive.ETRowDirective;
import org.onetwo.ext.poi.excel.etemplate.directive.ForeachRowDirective;
import org.onetwo.ext.poi.excel.exception.ExcelException;
import org.onetwo.ext.poi.excel.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class ExcelTemplateEngineer {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private Map<String, ETRowDirective> rowDirectives = Maps.newHashMap();

	public ExcelTemplateEngineer() {
		super();
		addDirective(new ForeachRowDirective());
	}

	final void addDirective(ETRowDirective directive){
		addDirective(directive, false);
	}
	final void addDirective(ETRowDirective directive, boolean override){
		if(rowDirectives.containsKey(directive.getName())){
			if(override){
				rowDirectives.put(directive.getName(), directive);
			}else{
				throw new RuntimeException("directive already exists: " + directive.getName());
			}
		}else{
			rowDirectives.put(directive.getName(), directive);
		}
	}

	public Object getCellValue(Cell cell){
		return ExcelUtils.getCellValue(cell);
	}

	public int parseRow(ETSheetContext sheetContext, Row row){
		for(ETRowDirective d : rowDirectives.values()){
			ETRowContext rowContext = sheetContext.new ETRowContext(row);
			if(d.isMatch(rowContext) ){
				logger.info("match directive[{}], executing...", d.getName());
				try {
					if(d.excecute(rowContext))
						return rowContext.getLastRownumbAfterExecuteTag();
				} catch (Exception e) {
					throw new RuntimeException("execute directive["+d.getName()+"] error:"+e.getMessage(), e);
				}
			}
		}
		ExcelUtils.parseCommonRow(row, sheetContext.getValueProvider());
		return row.getRowNum();
	}

	/*protected int parse(final Row row, final ExcelTemplateValueProvider provider){
		RowForeachDirectiveModel forModel = rowForeachDirective.matchStart(row);
		if(forModel!=null){
			Row nextRow = row.getSheet().getRow(row.getRowNum()+1);
			if(rowForeachDirective.matchEnd(forModel, nextRow)){
				nextRow = row.getSheet().getRow(forModel.getEndRow().getRowNum()+1);
				rowForeachDirective.excecute(this, forModel, provider);

				int rownumb = nextRow.getRowNum()-1;
				return rownumb;
			}
			throw new BaseException("not match end tag for : " + forModel.getDirectiveStart());
		}else{
			int cellNumbs = row.getPhysicalNumberOfCells();
			for (int cellIndex = 0; cellIndex < cellNumbs; cellIndex++) {
				Cell cell = row.getCell(cellIndex);
				Object cellValue = getCellValue(cell);
				if(cellValue==null)
					continue;

				Object newCellValue = provider.parseCellValue(cell, provider);
				ExcelUtils.setCellValue(cell, newCellValue);
			}
		}
		return row.getRowNum();
	}*/

	protected void parseSheet(ETSheetContext sheetContext){
		Sheet sheet = sheetContext.getSheet();
		final ExcelTemplateValueProvider provider = sheetContext.getValueProvider();
//		int rowNumbs = sheet.getPhysicalNumberOfRows();
		List<CellRangeAddress> cellRangeList = Lists.newArrayList();
		for(int i=0; i< sheet.getNumMergedRegions(); i++){
			CellRangeAddress cellRange = sheet.getMergedRegion(i);
			cellRangeList.add(cellRange);
//			logger.info("find mergedRegion, first row:{}, last row:{} " + cellRange.getFirstRow(), cellRange.getLastRow());
		}
		provider.setCellRangeList(cellRangeList);

		for (int rowIndex = 0; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
			Row row = sheet.getRow(rowIndex);
			if(row==null)
				continue;
			rowIndex = parseRow(sheetContext, row);
		}

		/*for(int i=0; i< sheet.getNumMergedRegions(); i++){
			CellRangeAddress cellRange = sheet.getMergedRegion(i);
			logger.info("==find mergedRegion, first row:{}, last row:{} " + cellRange.getFirstRow(), cellRange.getLastRow());
		}*/
	}

	public void generate(File templateFile, String generatedPath, final ETemplateContext context){
		try {
			ExcelUtils.makeDirs(generatedPath, true);
			generate(templateFile, new FileOutputStream(generatedPath), context);
		} catch (FileNotFoundException e) {
			throw new ExcelException("write workbook to ["+generatedPath+"] error: " + e.getMessage());
		}
	}

	public void generate(File templateFile, OutputStream out, final ETemplateContext context){
//		File destFile = FileUtils.copyFile(templatePath, generatedPath);
//		System.out.println("dest: " + destFile);

		Workbook wb = readExcelTemplate(templateFile);
		int sheetNumbs = wb.getNumberOfSheets();

		ExcelTemplateValueProvider provider = new ExcelTemplateValueProvider(context);
		for (int index = 0; index < sheetNumbs; index++) {
			Sheet sheet = wb.getSheetAt(index);
			ETSheetContext directiveContext = new ETSheetContext(this, provider, context);
			directiveContext.setSheet(sheet);
			parseSheet(directiveContext);
		}
		try {
			wb.write(out);
		} catch (Exception e) {
			throw new ExcelException("write workbook error: " + e.getMessage());
		}
	}

	public Workbook readExcelTemplate(File destFile){
		InputStream in;
		try {
			in = new FileInputStream(destFile);
		} catch (FileNotFoundException e) {
			throw new ExcelException("create file inpustream error: " + e.getMessage(), e);
		}
		Workbook wb = ExcelUtils.createWorkbook(in);
		return wb;
	}

}


text:
from typing import TYPE_CHECKING
from typing import Any
from typing import List

if TYPE_CHECKING:
    from typing_extensions import Protocol
    from typing_extensions import runtime_checkable
else:
    try:
        from typing import Protocol
        from typing import runtime_checkable
    except ImportError:
        from typing_extensions import Protocol
        from typing_extensions import runtime_checkable

@runtime_checkable
class SuportsGetAll(Protocol):
    def getall(self, name: str) -> List[Any]:
        ...

@runtime_checkable
class SuportsGetList(Protocol):
    def getlist(self, name: str) -> List[Any]:
        ...

redpajama_set_name: RedPajamaGithub


text:
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */

/*************************************************************************
 * Copyright (c) 2011 AT&T Intellectual Property
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: See CVS logs. Details at http://www.graphviz.org/
 *************************************************************************/

#include "config.h"

#include "gvplugin_device.h"

#include "gvplugin_quartz.h"

#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1040 && defined(HAVE_PANGOCAIRO)

const void *memory_data_consumer_get_byte_pointer(void *info)
{
	return info;
}

CGDataProviderDirectCallbacks memory_data_provider_callbacks = {
	0,
	memory_data_consumer_get_byte_pointer,
	NULL,
	NULL,
	NULL
};

static void quartz_format(GVJ_t *job)
{
	/* image destination -> data consumer -> job's gvdevice */
	/* data provider <- job's imagedata */
	CGDataConsumerRef data_consumer = CGDataConsumerCreate(job, &device_data_consumer_callbacks);
	CGImageDestinationRef image_destination = CGImageDestinationCreateWithDataConsumer(data_consumer, format_to_uti(job->device.id), 1, NULL);
	CGDataProviderRef data_provider = CGDataProviderCreateDirect(job->imagedata, BYTES_PER_PIXEL * job->width * job->height, &memory_data_provider_callbacks);

	/* add the bitmap image to the destination and save it */
	CGColorSpaceRef color_space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
	CGImageRef image = CGImageCreate (
		job->width,							/* width in pixels */
		job->height,						/* height in pixels */
		BITS_PER_COMPONENT,					/* bits per component */
		BYTES_PER_PIXEL * 8,				/* bits per pixel */
		BYTES_PER_PIXEL * job->width,		/* bytes per row: exactly width # of pixels */
		color_space,						/* color space: sRGB */
		kCGImageAlphaPremultipliedFirst|kCGBitmapByteOrder32Little,	/* bitmap info: corresponds to CAIRO_FORMAT_ARGB32 */
		data_provider,						/* data provider: from imagedata */
		NULL,								/* decode: don't remap colors */
		FALSE,								/* don't interpolate */
		kCGRenderingIntentDefault			/* rendering intent (what to do with out-of-gamut colors): default */
	);
	CGImageDestinationAddImage(image_destination, image, NULL);
	CGImageDestinationFinalize(image_destination);

	/* clean up */
	CGImageRelease(image);
	CGColorSpaceRelease(color_space);
	CGDataProviderRelease(data_provider);
	if (image_destination)
		CFRelease(image_destination);
	CGDataConsumerRelease(data_consumer);
}

static gvdevice_engine_t quartz_engine = {
    NULL,		/* quartz_initialize */
    quartz_format,
    NULL,		/* quartz_finalize */
};

static gvdevice_features_t device_features_quartz = {
	GVDEVICE_BINARY_FORMAT
          | GVDEVICE_DOES_TRUECOLOR,/* flags */
	{0.,0.},                    /* default margin - points */
	{0.,0.},                    /* default page width, height - points */
	{96.,96.},                  /* dpi */
};

gvplugin_installed_t gvdevice_quartz_types_for_cairo[] = {
	{FORMAT_BMP, "bmp:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_GIF, "gif:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_EXR, "exr:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_ICNS, "icns:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_ICO, "ico:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_JPEG, "jpe:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_JPEG, "jpeg:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_JPEG, "jpg:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_JPEG2000, "jp2:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_PICT, "pct:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_PICT, "pict:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_PNG, "png:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_PSD, "psd:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_SGI, "sgi:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_TIFF, "tif:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_TIFF, "tiff:cairo", 7, &quartz_engine, &device_features_quartz},
	{FORMAT_TGA, "tga:cairo", 7, &quartz_engine, &device_features_quartz},
	{0, NULL, 0, NULL, NULL}
};

#endif


text:
package dollar.api;

public class VarFlags {
    private final boolean declaration;
    private final boolean fixed;
    private final boolean isVolatile;
    private final boolean numeric;
    private final boolean pure;
    private final boolean readonly;

    /**
     * @param readonly    true if the variable cannot be changed
     * @param isVolatile  true if the variable can be accessed by multiple threads
     * @param fixed       true if the variable is a fixed/static value
     * @param pure        true if the variable contains a pure value (i.e. a pure function/expession)
     * @param numeric     true if the variable should be a number (i.e. $1, $2)
     * @param declaration true if this is the first use (declaration)
     */
    public VarFlags(boolean readonly, boolean isVolatile, boolean fixed, boolean pure, boolean numeric, boolean declaration) {
        this.readonly = readonly;
        this.isVolatile = isVolatile;
        this.fixed = fixed;
        this.pure = pure;
        this.numeric = numeric;
        this.declaration = declaration;
    }

    /**
     * @param readonly    true if the variable cannot be changed
     * @param isVolatile  true if the variable can be accessed by multiple threads
     * @param declaration true if this is the first use (declaration)
     */
    public VarFlags(boolean readonly, boolean isVolatile, boolean declaration, boolean pure) {

        this.readonly = readonly;
        this.isVolatile = isVolatile;
        this.declaration = declaration;
        fixed = false;
        this.pure = pure;
        numeric = false;
    }

    public boolean isDeclaration() {
        return declaration;
    }

    public boolean isFixed() {
        return fixed;
    }

    public boolean isNumeric() {
        return numeric;
    }

    public boolean isPure() {
        return pure;
    }

    public boolean isReadonly() {
        return readonly;
    }

    public boolean isVolatile() {
        return isVolatile;
    }
}


text:
/* Custom CSS Document*/
@import url(http://fonts.googleapis.com/css?family=Open+Sans:300);
body{
	background:#010101;
}

.price_table_container{
	text-align:center;
	color:#666;
	margin-top:35px;
	font-family: 'Open Sans', sans-serif;
}

.price_table_heading{
	font-size:36px;
	padding:10px;
	background:#EEE;
}

.price_table_row {
    padding:15px;
	background: #FFF;
}

.cost{
	padding:30px;
	font-size:30px;
}
.cost span{
	font-size:15px;
}

.price_table_row:nth-of-type(even) {
    background: #F8F8F8;
}
.btn{
	border-radius:0px;
}

.recommended{
/*USER DEFINED COLOUR*/
background:#FF3A3A;
color:#FFF;
/*USER DEFINED COLOUR*/
padding:3px 0 3px 0;
margin-top:10px;
text-align:center;
margin-bottom:-35px;
font-family: 'Open Sans', sans-serif;
}

.spacer{width:100%;height:50px;}

/*Already Defined Colours*/
/*Background*/
.primary-bg{background:#337AB7;color:#FFF;}
.success-bg{background:#5CB85C;color:#FFF;}
.info-bg{background:#5BC0DE;color:#FFF;}
.warning-bg{background:#F0AD4E;color:#FFF;}
.danger-bg{background:#D9534F;color:#FFF;}
.dark-bg{background:#444;color:#FFF;}
.royal-bg{background:#8E74E2;color:#FFF;}
.static-bg{background:#2BB0A6;color:#FFF;}

/*Only Text Colours*/
.primary-text{background:#FFF;color:#337AB7;}
.success-text{background:#FFF;color:#5CB85C;}
.info-text{background:#FFF;color:#5BC0DE;}
.warning-text{background:#FFF;color:#F0AD4E;}
.danger-text{background:#FFF;color:#D9534F;}
.dark-text{background:#FFF;color:#444;}
.royal-text{background:#FFF;color:#8E74E2;}
.static-text{background:#FFF;color:#2BB0A6;}

/*Additional Button styles*/

/*BTN-DARK*/
.btn-dark {
  color: #fff;
  background-color: #444;
  border-color: #444;
}
.btn-dark:hover,
.btn-dark:focus,
.btn-dark.focus,
.btn-dark:active,
.btn-dark.active,
.open > .dropdown-toggle.btn-dark {
  color: #fff;
  background-color: #222;
  border-color: #222;
}
.btn-dark:active,
.btn-dark.active,
.open > .dropdown-toggle.btn-dark {
  background-image: none;
}

/*BTN-ROYAL---------*/
.btn-royal {
  color: #fff;
  background-color: #8E74E2;
  border-color: #8E74E2;
}
.btn-royal:hover,
.btn-royal:focus,
.btn-royal.focus,
.btn-royal:active,
.btn-royal.active,
.open > .dropdown-toggle.btn-royal {
  color: #fff;
  background-color: #7451E8;
  border-color: #7451E8;
}
.btn-royal:active,
.btn-royal.active,
.open > .dropdown-toggle.btn-royal {
  background-image: none;
}

/*BTN-STATIC---------*/
.btn-static {
  color: #fff;
  background-color: #2BB0A6;
  border-color: #2BB0A6;
}
.btn-static:hover,
.btn-static:focus,
.btn-static.focus,
.btn-static:active,
.btn-static.active,
.open > .dropdown-toggle.btn-static {
  color: #fff;
  background-color: #07A094;
  border-color: #07A094;
}
.btn-static:active,
.btn-static.active,
.open > .dropdown-toggle.btn-static {
  background-image: none;
}


text:
<?php

namespace Minsal\shcpBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShcpParTrabajoParto
 *
 * @ORM\Table(name="shcp_par_trabajo_parto", indexes={@ORM\Index(name="IDX_4D44E3A2D766E548", columns={"id_admision_parto"})})
 * @ORM\Entity
 */
class ShcpParTrabajoParto
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="shcp_par_trabajo_parto_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_partograma", type="string", nullable=true)
     */
    private $trabPartograma;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="trab_hora", type="time", nullable=true)
     */
    private $trabHora;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_posicion", type="string", nullable=true)
     */
    private $trabPosicion;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_pa_sistole", type="string", nullable=true)
     */
    private $trabPaSistole;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_pa_diastole", type="string", nullable=true)
     */
    private $trabPaDiastole;

    /**
     * @var integer
     *
     * @ORM\Column(name="trab_pulso", type="integer", nullable=true)
     */
    private $trabPulso;

    /**
     * @var integer
     *
     * @ORM\Column(name="trab_contrac", type="integer", nullable=true)
     */
    private $trabContrac;

    /**
     * @var integer
     *
     * @ORM\Column(name="trab_dilatacion", type="integer", nullable=true)
     */
    private $trabDilatacion;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_altura_present", type="string", nullable=true)
     */
    private $trabAlturaPresent;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_variedad_posic", type="string", nullable=true)
     */
    private $trabVariedadPosic;

    /**
     * @var string
     *
     * @ORM\Column(name="trab_meconio", type="string", nullable=true)
     */
    private $trabMeconio;

    /**
     * @var integer
     *
     * @ORM\Column(name="trab_fcf_dips", type="integer", nullable=true)
     */
    private $trabFcfDips;

    /**
     * @var \ShcpParAdmision
     *
     * @ORM\ManyToOne(targetEntity="ShcpParAdmision")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_admision_parto", referencedColumnName="id")
     * })
     */
    private $idAdmisionParto;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set trabPartograma
     *
     * @param string $trabPartograma
     * @return ShcpParTrabajoParto
     */
    public function setTrabPartograma($trabPartograma)
    {
        $this->trabPartograma = $trabPartograma;

        return $this;
    }

    /**
     * Get trabPartograma
     *
     * @return string
     */
    public function getTrabPartograma()
    {
        return $this->trabPartograma;
    }

    /**
     * Set trabHora
     *
     * @param \DateTime $trabHora
     * @return ShcpParTrabajoParto
     */
    public function setTrabHora($trabHora)
    {
        $this->trabHora = $trabHora;

        return $this;
    }

    /**
     * Get trabHora
     *
     * @return \DateTime
     */
    public function getTrabHora()
    {
        return $this->trabHora;
    }

    /**
     * Set trabPosicion
     *
     * @param string $trabPosicion
     * @return ShcpParTrabajoParto
     */
    public function setTrabPosicion($trabPosicion)
    {
        $this->trabPosicion = $trabPosicion;

        return $this;
    }

    /**
     * Get trabPosicion
     *
     * @return string
     */
    public function getTrabPosicion()
    {
        return $this->trabPosicion;
    }

    /**
     * Set trabPaSistole
     *
     * @param string $trabPaSistole
     * @return ShcpParTrabajoParto
     */
    public function setTrabPaSistole($trabPaSistole)
    {
        $this->trabPaSistole = $trabPaSistole;

        return $this;
    }

    /**
     * Get trabPaSistole
     *
     * @return string
     */
    public function getTrabPaSistole()
    {
        return $this->trabPaSistole;
    }

    /**
     * Set trabPaDiastole
     *
     * @param string $trabPaDiastole
     * @return ShcpParTrabajoParto
     */
    public function setTrabPaDiastole($trabPaDiastole)
    {
        $this->trabPaDiastole = $trabPaDiastole;

        return $this;
    }

    /**
     * Get trabPaDiastole
     *
     * @return string
     */
    public function getTrabPaDiastole()
    {
        return $this->trabPaDiastole;
    }

    /**
     * Set trabPulso
     *
     * @param integer $trabPulso
     * @return ShcpParTrabajoParto
     */
    public function setTrabPulso($trabPulso)
    {
        $this->trabPulso = $trabPulso;

        return $this;
    }

    /**
     * Get trabPulso
     *
     * @return integer
     */
    public function getTrabPulso()
    {
        return $this->trabPulso;
    }

    /**
     * Set trabContrac
     *
     * @param integer $trabContrac
     * @return ShcpParTrabajoParto
     */
    public function setTrabContrac($trabContrac)
    {
        $this->trabContrac = $trabContrac;

        return $this;
    }

    /**
     * Get trabContrac
     *
     * @return integer
     */
    public function getTrabContrac()
    {
        return $this->trabContrac;
    }

    /**
     * Set trabDilatacion
     *
     * @param integer $trabDilatacion
     * @return ShcpParTrabajoParto
     */
    public function setTrabDilatacion($trabDilatacion)
    {
        $this->trabDilatacion = $trabDilatacion;

        return $this;
    }

    /**
     * Get trabDilatacion
     *
     * @return integer
     */
    public function getTrabDilatacion()
    {
        return $this->trabDilatacion;
    }

    /**
     * Set trabAlturaPresent
     *
     * @param string $trabAlturaPresent
     * @return ShcpParTrabajoParto
     */
    public function setTrabAlturaPresent($trabAlturaPresent)
    {
        $this->trabAlturaPresent = $trabAlturaPresent;

        return $this;
    }

    /**
     * Get trabAlturaPresent
     *
     * @return string
     */
    public function getTrabAlturaPresent()
    {
        return $this->trabAlturaPresent;
    }

    /**
     * Set trabVariedadPosic
     *
     * @param string $trabVariedadPosic
     * @return ShcpParTrabajoParto
     */
    public function setTrabVariedadPosic($trabVariedadPosic)
    {
        $this->trabVariedadPosic = $trabVariedadPosic;

        return $this;
    }

    /**
     * Get trabVariedadPosic
     *
     * @return string
     */
    public function getTrabVariedadPosic()
    {
        return $this->trabVariedadPosic;
    }

    /**
     * Set trabMeconio
     *
     * @param string $trabMeconio
     * @return ShcpParTrabajoParto
     */
    public function setTrabMeconio($trabMeconio)
    {
        $this->trabMeconio = $trabMeconio;

        return $this;
    }

    /**
     * Get trabMeconio
     *
     * @return string
     */
    public function getTrabMeconio()
    {
        return $this->trabMeconio;
    }

    /**
     * Set trabFcfDips
     *
     * @param integer $trabFcfDips
     * @return ShcpParTrabajoParto
     */
    public function setTrabFcfDips($trabFcfDips)
    {
        $this->trabFcfDips = $trabFcfDips;

        return $this;
    }

    /**
     * Get trabFcfDips
     *
     * @return integer
     */
    public function getTrabFcfDips()
    {
        return $this->trabFcfDips;
    }

    /**
     * Set idAdmisionParto
     *
     * @param \Minsal\shcpBundle\Entity\ShcpParAdmision $idAdmisionParto
     * @return ShcpParTrabajoParto
     */
    public function setIdAdmisionParto(\Minsal\shcpBundle\Entity\ShcpParAdmision $idAdmisionParto = null)
    {
        $this->idAdmisionParto = $idAdmisionParto;

        return $this;
    }

    /**
     * Get idAdmisionParto
     *
     * @return \Minsal\shcpBundle\Entity\ShcpParAdmision
     */
    public function getIdAdmisionParto()
    {
        return $this->idAdmisionParto;
    }
}


text:
class Project::SettingsController < ApplicationController
  before_action :set_project_setting, only: [:show]
  before_action :load_measured_points, only: [:index]

  # GET /project/settings, momentarily root
  def index
    @project_settings = Project::Setting.all
    @testpoints = PowderData::EmulatedPoints.last
  end

  # GET /project/settings/{id}
  def show
    @manager = Project::Manager.setup(@project_setting)
    @testpoints = PowderData::EmulatedPoints.last
    @function = @project_setting.estimation_function.serialize.as_json
  end

  def remotecall
    @setting = Project::Setting.find(params[:id])
    render json: @setting
  end

  # currently the method to get the data into fronted via ajax
  # should be exchanged actually for something more appropriate
  # TODO: change name of call, add new route, delete old one (probably)
  # TODO: calculation of quality metrics has to be changed (shouldn't happen in controller)
  def remotepost
    parameters = project_setting_params
    inputvals = parameters
    id = params[:id].to_i
    manager = Project::Manager.setup(id)
    run = manager.run(inputvals)
    manager.run_list.add(run)
    run.calculate_quality_metric
    #render json: run.get_emulated_points.to_json
    render json: run
  end

  def alternative_estfunc
    #parameters = project_setting_params
    result_vector = params[:parameters]
    p "RESULT VECTOR"
    p result_vector
    rv = result_vector.map do |r|
      r = r.to_f
    end
    id = params[:id].to_i
    manager = Project::Manager.setup(id)
    func = manager.estimation_function
    newfunc = func.create_alternative(rv)
    render json: newfunc
  end

  def get_runs
    manager = Project::Manager.setup(params[:id].to_i)
    runs = manager.run_list.runs
    render json: runs, root: "runs"
  end

  def get_initial_runs
    manager = Project::Manager.setup(params[:id].to_i)
    runs = manager.estimation_function.run_list.runs
    render json: runs, root: "initial_runs"
  end

  private

  def set_project_setting
    @project_setting = Project::Setting.find(params[:id])
  end

  def load_measured_points
    @project_setting = Project::Setting.last
  end

  def project_setting_params
    params.require(:parameters).permit!
    #params[:project_setting]
  end

  def result_vector_params
    params.require(:result_vector).permit!
  end
end


text:
from setuptools import setup, find_packages

from prakasha import meta
from prakasha.util import dist

setup(
    name=meta.display_name,
    version=meta.version,
    description=meta.description,
    author=meta.author,
    author_email=meta.author_email,
    url=meta.url,
    license=meta.license,
    install_requires=meta.requires,
    long_description=dist.catReST(
        "docs/PRELUDE.rst",
        "README.rst",
        "docs/DEPENDENCIES.rst",
        "docs/INSTALL.rst",
        "docs/USAGE.rst",
        "TODO",
        "docs/HISTORY.rst",
        stop_on_errors=False,
        out=True),
    packages=find_packages() + ["twisted.plugins"],
    package_data={
        "twisted": ['plugins/prakasha.py']
        },
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python",
        ],
    )


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Microsoft.SourceBrowser.SourceIndexServer.Models
{
    public class ResultsHtmlGenerator
    {
        private readonly Query query;
        private readonly StringBuilder sb = new StringBuilder();

        public ResultsHtmlGenerator(Query query)
        {
            this.query = query;
        }

        public string Generate(Stopwatch sw = null, Index index = null, string usageStats = null)
        {
            sb.Clear();

            if (query.HasDiagnostics)
            {
                sb.AppendLine(Markup.Note(query.Diagnostics));
                AppendAffiliateLinks(query);
                return sb.ToString();
            }

            if (!query.HasResults)
            {
                var symbolSearchTerm = query.GetSearchTermForSymbolSearch();
                if (!string.IsNullOrEmpty(symbolSearchTerm) && symbolSearchTerm.Length < 3)
                {
                    sb.AppendLine(Markup.Note("Please specify at least 3 characters for the symbol name, otherwise too many results would be returned"));
                }
                else
                {
                    sb.AppendLine(Markup.Note("No results found"));
                }

                AppendAffiliateLinks(query);
                return sb.ToString();
            }

            WriteSymbolResults(index);
            WriteAssemblyResults(index);
            WriteProjectResults(index);
            WriteGuidResults(index);
            WriteMSBuildPropertiesResults(index);
            WriteMSBuildItemsResults(index);
            WriteMSBuildTargetsResults(index);
            WriteMSBuildTasksResults(index);

            if (sw != null)
            {
                string message = "Generated in " + sw.ElapsedMilliseconds + " ms.";
                if (usageStats != null)
                {
                    message += "
" + usageStats;
                }

                message = Markup.Note(message);
                sb.AppendLine(message);
            }

            return sb.ToString();
        }

        private void WriteMSBuildPropertiesResults(Index index)
        {
            if (query.ResultMSBuildProperties == null || !query.ResultMSBuildProperties.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "MSBuild Properties");
            string count = query.ResultMSBuildProperties.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string header = "MSBuild properties that match '" + query.OriginalString + "' (" + count + ")";
            WriteLine("
{0}
", header);
            WriteLine("
");
            WriteLine("
", "MSBuild Properties");

            foreach (var text in query.ResultMSBuildProperties)
            {
                var url = text;
                WriteLine(
                    "

{2}
",
                    Constants.MSBuildPropertiesAssembly,
                    Constants.ReferencesFileName,
                    text);
                WriteLine("
");
            }

            WriteLine("

");
        }

        private void WriteMSBuildItemsResults(Index index)
        {
            if (query.ResultMSBuildItems == null || !query.ResultMSBuildItems.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "MSBuild Items");
            string count = query.ResultMSBuildItems.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string header = "MSBuild items that match '" + query.OriginalString + "' (" + count + ")";
            WriteLine("
{0}
", header);
            WriteLine("
");
            WriteLine("
", "MSBuild Items");

            foreach (var text in query.ResultMSBuildItems)
            {
                var url = text;
                WriteLine(
                    "

{2}
",
                    Constants.MSBuildItemsAssembly,
                    Constants.ReferencesFileName,
                    text);
                WriteLine("
");
            }

            WriteLine("

");
        }

        private void WriteMSBuildTargetsResults(Index index)
        {
            if (query.ResultMSBuildTargets == null || !query.ResultMSBuildTargets.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "MSBuild Targets");
            string count = query.ResultMSBuildTargets.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string header = "MSBuild targets that match '" + query.OriginalString + "' (" + count + ")";
            WriteLine("
{0}
", header);
            WriteLine("
");
            WriteLine("
", "MSBuild Targets");

            foreach (var text in query.ResultMSBuildTargets)
            {
                var url = text;
                WriteLine(
                    "

{2}
",
                    Constants.MSBuildTargetsAssembly,
                    Constants.ReferencesFileName,
                    text);
                WriteLine("
");
            }

            WriteLine("

");
        }

        private void WriteMSBuildTasksResults(Index index)
        {
            if (query.ResultMSBuildTasks == null || !query.ResultMSBuildTasks.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "MSBuild Tasks");
            string count = query.ResultMSBuildTasks.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string header = "MSBuild tasks that match '" + query.OriginalString + "' (" + count + ")";
            WriteLine("
{0}
", header);
            WriteLine("
");
            WriteLine("
", "MSBuild Tasks");

            foreach (var text in query.ResultMSBuildTasks)
            {
                var url = text;
                WriteLine(
                    "

{2}
",
                    Constants.MSBuildTasksAssembly,
                    Constants.ReferencesFileName,
                    text);
                WriteLine("
");
            }

            WriteLine("

");
        }

        private void AppendAffiliateLinks(Query query)
        {
            WriteLine(Markup.P("Try also searching on:"));
            var term = query.OriginalString;
            term = Markup.UrlEncodeAndHtmlEscape(term);
            WriteLine("
");
            AppendAffiliateLink("http://www.bing.com/search?q=" + term);
            AppendAffiliateLink("http://social.msdn.microsoft.com/Search/en-US?query=" + term);
            AppendAffiliateLink("http://stackoverflow.com/search?q=" + term);
            WriteLine("
");
        }

        private void AppendAffiliateLink(string url)
        {
            WriteLine(Markup.Li(Markup.A(url)));
        }

        private void WriteSymbolResults(Index index)
        {
            if (query.ResultSymbols == null || !query.ResultSymbols.Any())
            {
                return;
            }

            GenerateResultCount();

            var groups = query.ResultSymbols
                .GroupBy(s => s.AssemblyName)
                .Select(g => new
                {
                    AssemblyName = g.Key,
                    Results = g,
                    AssemblyWeight = GetAssemblyWeight(g),
                    NumberOfReferences = GetNumberOfReferences(g.Key, index)
                })
                .OrderBy(g => g.AssemblyWeight)
                .ThenByDescending(g => g.NumberOfReferences);
            foreach (var symbolsInAssembly in groups)
            {
                WriteAssembly(symbolsInAssembly.Results);
            }
        }

        private int GetNumberOfReferences(string assemblyName, Index index)
        {
            return index.GetReferencingAssembliesCount(assemblyName);
        }

        private static int GetAssemblyWeight(IEnumerable<DeclaredSymbolInfo> resultsInAssembly)
        {
            return resultsInAssembly.Min(d => d.Weight);
        }

        private void WriteAssemblyResults(Index index = null)
        {
            if (query.ResultAssemblies == null || !query.ResultAssemblies.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "Assemblies");
            string count = query.ResultAssemblies.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string assemblySearchTerm = query.GetSearchTermForAssemblySearch() ?? "";
            if (!string.IsNullOrEmpty(assemblySearchTerm))
            {
                assemblySearchTerm = "that start with '" + assemblySearchTerm + "' ";
            }

            string assemblyHeader = "Assemblies " + assemblySearchTerm + "(" + count + ")";
            WriteLine("
{0}
", assemblyHeader);
            //WriteLine(sb, "
{0}
", Markup.HtmlEscape(symbolsInAssembly.First().ProjectFilePath));
            WriteLine("
");
            WriteLine("
", "Assemblies");

            foreach (var assembly in query.ResultAssemblies)
            {
                var url = assembly;
                WriteLine("

{0}
", url.AssemblyName);
                var projectKey = url.ProjectKey;
                if (projectKey >= 0)
                {
                    WriteLine("
{0}

", index.projects[projectKey]);
                }
                else
                {
                    WriteLine("
");
                }
            }

            WriteLine("

");
        }

        private void WriteProjectResults(Index index = null)
        {
            if (query.ResultProjects == null || !query.ResultProjects.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "Projects");
            string count = query.ResultProjects.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string assemblyHeader = "Projects in '" + query.GetSearchTermForProjectSearch() + "' (" + count + ")";
            WriteLine("
{0}
", assemblyHeader);
            //WriteLine(sb, "
{0}
", Markup.HtmlEscape(symbolsInAssembly.First().ProjectFilePath));
            WriteLine("
");
            WriteLine("
", "Projects");

            foreach (var project in query.ResultProjects)
            {
                var url = project;
                Write(
                    "

{1}
",
                    url.AssemblyName,
                    index.projects[url.ProjectKey]);
                WriteLine("
{0}

", Markup.HtmlEscape(url.AssemblyName));
            }

            WriteLine("

");
        }

        private void WriteGuidResults(Index index)
        {
            if (query.ResultGuids == null || !query.ResultGuids.Any())
            {
                return;
            }

            WriteLine("
");
            WriteLine("
", "Guids");
            string count = query.ResultGuids.Count.ToString();
            if (count == Index.MaxRawResults.ToString())
            {
                count = "showing first " + Index.MaxRawResults.ToString();
            }

            string guidHeader = "Guids that match '" + query.OriginalString + "' (" + count + ")";
            WriteLine("
{0}
", guidHeader);
            WriteLine("
");
            WriteLine("
", "Guids");

            foreach (var guidText in query.ResultGuids)
            {
                var url = guidText;
                WriteLine(
                    "

{2}
",
                    Constants.GuidAssembly,
                    Constants.ReferencesFileName,
                    guidText);
                WriteLine("
");
            }

            WriteLine("

");
        }

        private void GenerateResultCount()
        {
            int count = query.ResultSymbols.Count();
            string message = count + string.Format(" result{0} found:", count == 1 ? "" : "s");
            if (count >= Index.MaxRawResults)
            {
                if (query.PotentialRawResults > count)
                {
                    count = query.PotentialRawResults;
                }

                message = "Displaying top " + Index.MaxRawResults + " results out of " + count + ":";
            }
            else if (count == 0)
            {
                message = "No results found.";
            }

            var url = string.Format("/#q={0}", Markup.UrlEncodeAndHtmlEscape(query.OriginalString));
            message = Markup.A(url, message, "_top");

            sb.AppendLine(Markup.Note(message));
        }

        private void WriteAssembly(IGrouping<string, DeclaredSymbolInfo> symbolsInAssembly)
        {
            WriteLine("
");
            WriteLine("
", symbolsInAssembly.Key);
            string assemblyHeader = symbolsInAssembly.Key;
            ////assemblyHeader = assemblyHeader + " (" + symbolsInAssembly.Count().ToString() + ")";
            WriteLine("
{0}
", assemblyHeader);
            WriteLine("
{0}
", Markup.HtmlEscape(symbolsInAssembly.First().ProjectFilePath));
            WriteLine("
");
            WriteLine("
", symbolsInAssembly.Key);

            foreach (var symbol in symbolsInAssembly)
            {
                Markup.WriteSymbol(symbol, sb);
            }

            WriteLine("

");
        }

        private void Write(string format, params object[] args)
        {
            sb.Append(string.Format(format, args));
        }

        private void WriteLine(string format, params object[] args)
        {
            var line = format;
            if (args.Length > 0)
            {
                line = string.Format(line, args);
            }

            sb.AppendLine(line);
        }
    }
}


text:
"""
    ${NAME}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys

log = logging.getLogger(__name__)

def getSrcFolder():
    """
    Find the 'src/' folder of a source checkout.

    ...should maybe assert that '.git' exists?
    :return: unicode
    """
    import mcedit2
    mod = os.path.realpath(mcedit2.__file__)  # src/mcedit2/__init__.py

    # On Windows, sys.argv[0] is always codepage-encoded, as is the __file__ attribute of any module.
    # in fact, the entire module import subsystem of python2.7 is either restricted to codepages
    # or to ASCII (haven't found out which) as `import` seems to break with non-ascii paths.

    # On OS X, it is always UTF-8 encoded and filenames are *always* UTF-8 encoded.

    # On Linux, it is locale-encoded and filenames are defined as bytestrings, so it is possible
    # to have a filename that cannot be interpreted as unicode. If the user writes a filename
    # that is not locale-encoded, he loses.

    mod = mod.decode(sys.getfilesystemencoding())

    # Assert the source checkout is not in a non-representable path...
    assert os.path.exists(mod), ("Source checkout path cannot be represented as unicode. "
                                 "Put the source checkout somewhere else.")
    return os.path.dirname((os.path.dirname(mod)))

def resourcePath(filename):
    """
    Return the absolute path of a filename included as a resource.

    "Resource" is not well-defined. When packaged with PyInstaller, the filename is found
    relative to the app's folder (_MEIPASS). When running from source, it is relative to the
    'src' folder. I'd imagine that when installed as a .whl (on linux) we need to use
    pkg_resources to get filenames.

    :param filename:
    :return:
    """
    filename = filename.replace('/', os.path.sep)
    basedir = getattr(sys, "_MEIPASS", None)  # if pyinstaller'd
    if basedir is None:
        # should work across platforms
        basedir = getSrcFolder()
    path = os.path.join(basedir, filename)
    if not os.path.exists(path):
        raise RuntimeError("Could not get resource path for %s\n(Tried %s which does not exist)" % (filename, path))

    return path


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
    internal interface IRazorSpanMappingService
    {
        Task<ImmutableArray<RazorMappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken);
    }
}


text:
#include <aws/elasticloadbalancingv2/model/DescribeRulesResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::ElasticLoadBalancingv2::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

DescribeRulesResult::DescribeRulesResult()
{
}

DescribeRulesResult::DescribeRulesResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

DescribeRulesResult& DescribeRulesResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (!rootNode.IsNull() && (rootNode.GetName() != "DescribeRulesResult"))
  {
    resultNode = rootNode.FirstChild("DescribeRulesResult");
  }

  if(!resultNode.IsNull())
  {
    XmlNode rulesNode = resultNode.FirstChild("Rules");
    if(!rulesNode.IsNull())
    {
      XmlNode rulesMember = rulesNode.FirstChild("member");
      while(!rulesMember.IsNull())
      {
        m_rules.push_back(rulesMember);
        rulesMember = rulesMember.NextNode("member");
      }

    }
    XmlNode nextMarkerNode = resultNode.FirstChild("NextMarker");
    if(!nextMarkerNode.IsNull())
    {
      m_nextMarker = Aws::Utils::Xml::DecodeEscapedXmlText(nextMarkerNode.GetText());
    }
  }

  if (!rootNode.IsNull()) {
    XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
    m_responseMetadata = responseMetadataNode;
    AWS_LOGSTREAM_DEBUG("Aws::ElasticLoadBalancingv2::Model::DescribeRulesResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
  }
  return *this;
}


text:
mod gamestate;
use gamestate::*;

extern crate rand;
extern crate piston_window;
extern crate image as im;

use piston_window::*;
use std::borrow::BorrowMut;
use im::Pixel;

fn main() {
    let mut game = GameState::new();

    let mut paused = true;
    let mut raining = true;
    let mut redraw_needed = true;

    let mut mouse_buttons_pressed = (false, false); //left, right

    let (width, height) = (WINDOW_WIDTH as u32, WINDOW_HEIGHT as u32);

    let mut window: PistonWindow =
        WindowSettings::new("Falling Sand", (width, height))
            .exit_on_esc(true)
            .build()
            .unwrap_or_else(|e| panic!("Failed to build PistonWindow: {}", e));

    let pixel = im::Rgba::from_channels(0, 0, 0, 255);
    let mut canvas = im::ImageBuffer::from_pixel(width, height, pixel);
    let blank = canvas.clone().into_raw();
    let tex_set = &TextureSettings::new();
    // https://github.com/PistonDevelopers/piston-examples/blob/master/src/paint.rs
    let mut texture = Texture::from_image(&mut *window.factory.borrow_mut(), &canvas, tex_set)
        .unwrap();

    // for e in window.clone().events().max_fps(120).ups(60) {
    while let Some(e) = window.next() {

        if let Some(Button::Keyboard(key)) = e.press_args() {
            match key {
                Key::Space => {
                    paused = !paused;
                    // window.borrow_mut().set_capture_cursor(!paused); //remove cursor when game is running
                }
                Key::D => {
                    println!("{:?}", game);
                }
                Key::R => raining = !raining,
                _ => {}
            }
        }

        if let Some(_) = e.update_args() {
            // Update game and image on every loop
            if !paused {
                if raining {
                    game.rain()
                }
                game.update();
                redraw_needed = true;
            } //if !paused {
        }

        if paused {
            if let Some(button) = e.press_args() {
                match button {
                    Button::Mouse(MouseButton::Left) => mouse_buttons_pressed.0 = true,
                    Button::Mouse(MouseButton::Right) => mouse_buttons_pressed.1 = true,
                    _ => {}
                }
            }
            if let Some(button) = e.release_args() {
                match button {
                    Button::Mouse(MouseButton::Left) => mouse_buttons_pressed.0 = false,
                    Button::Mouse(MouseButton::Right) => mouse_buttons_pressed.1 = false,
                    _ => {}
                }
            }
            if let Some(pos) = e.mouse_cursor_args() {
                redraw_needed = true;
                // get mouse coordinates and draw something if there is place
                let (mouse_x, mouse_y) = (pos[0] as i16, pos[1] as i16);

                match mouse_buttons_pressed {
                    (true, false) => {
                        game.paint_square_obstacles(mouse_x, mouse_y, 30, 30);
                    }
                    (false, true) => {
                        // remove everything from map and both lists
                        game.remove_square(mouse_x, mouse_y, 30, 30);
                    }
                    _ => {}
                }
            }
        } //if paused

        if redraw_needed {
            if let Some(_) = e.render_args() {
                canvas = im::ImageBuffer::from_vec(width, height, blank.clone()).unwrap();
                for particle in &game.particles {
                    canvas.put_pixel(
                        particle.x as u32,
                        particle.y as u32,
                        im::Rgba([238, 232, 170, 255]),
                    );
                }
                for obstacle in &game.obstacles {
                    canvas.put_pixel(
                        obstacle.x as u32,
                        obstacle.y as u32,
                        im::Rgba([128, 0, 0, 255]),
                    );
                }
                texture.update(&mut window.encoder, &canvas).unwrap();
                window.draw_2d(&e, |c, g| { image(&texture, c.transform, g); });
                redraw_needed = false;
            }
        };
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>allowsAttribute method - NodeValidator class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the allowsAttribute method from the NodeValidator class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

NodeValidator

allowsAttribute

allowsAttribute

polymer_app_layout_template

polymer_app_layout.behaviors

NodeValidator

allowsAttribute

method
 allowsAttribute

Source

polymer_app_layout_template

polymer_app_layout.behaviors

NodeValidator

Constructors

NodeValidator

throws

Methods

allowsAttribute

allowsElement

            bool
            allowsAttribute(

                Element element,
String attributeName,
String value

            )

Returns true if the attribute is allowed.

The attributeName parameter will always be in lowercase.

See allowsElement for format of tagName.

Source

/**
 * Returns true if the attribute is allowed.
 *
 * The attributeName parameter will always be in lowercase.
 *
 * See [allowsElement] for format of tagName.
 */
bool allowsAttribute(Element element, String attributeName, String value);

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
package admin

import (
	"github.com/qor/exchange"
	"github.com/qor/qor"
	"github.com/qor/qor-example/app/models"
	"github.com/qor/qor/resource"
	"github.com/qor/qor/utils"
	"github.com/qor/validations"
)

var ProductExchange *exchange.Resource

func init() {
	ProductExchange = exchange.NewResource(&models.Product{}, exchange.Config{PrimaryField: "Code"})
	ProductExchange.Meta(&exchange.Meta{Name: "Code"})
	ProductExchange.Meta(&exchange.Meta{Name: "Name"})
	ProductExchange.Meta(&exchange.Meta{Name: "Price"})

	ProductExchange.AddValidator(func(record interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
		if utils.ToInt(metaValues.Get("Price").Value) < 100 {
			return validations.NewError(record, "Price", "price can't less than 100")
		}
		return nil
	})
}


text:
For the [Global Azure Bootcamp 2017](https://global.azurebootcamp.net/) [Rubicon](http://rubicon.nl/) organized an event with [Cortana Intelligence Suite (CIS)](http://www.microsoft.com/en-us/cloud-platform/cortana-intelligence-suite) as theme. These HOLs are created and provided that day by [Jan Pieter Posthuma](https://linkedin.com/in/jpposthuma) of [DataScenarios [NL]](https://datascenarios.nl)

For this hands-on-lab bootcamp three parts of CIS are beeing used and connected:

1. [Azure Stream Analytics](https://azure.microsoft.com/en-us/services/stream-analytics/)
2. [Azure Data Lake](https://azure.microsoft.com/en-us/services/data-lake-store/)
3. [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning/)

### Prerequisites

See the [prerequisites](Prerequisites.md) document for the full list.

### Scenario
![](images/HOLDataScenario.png)
These HOL examples are part of a total data scenario. For this event, the sensor data and event hub (left part) part of the scenario is provided.

#### Lab 1 - Ingest
When connection data from the Event Hub to Azure Stream Analytics (ASA) it is possible to process that data stream directly and 'query' to either determine outliers of to reroute the data stream.

[More info](AzureStreamAnalytics/README.md)

#### Lab 2 - Store and prepare
The rerouted data from Azure Stream Analytics (ASA) can be stored at an Azure Data Lake Store (ADLS) directly in a folder.

After storing the raw data, it is possible to extract information from it by utilizing Azure Data Lake Analytics (ADLA). With U-SQL it is possible to read individual files (JSON) and extract information within one query.

[More info](AzureDataLake/README.md)

#### Lab 3 - Learning
The result of lab 2 will be used to start learning from the data. By using Azure Machine Learning (AzureML) it is possible to create a ML model that identifies incorrect events and even faulty sensors.

[More info](AzureMachineLearning/README.md)

#### Extra - Close the loop
It is possible to connect an AzureML model to an Azure Stream Analytics Job and use the outcome of that model to predict the incoming events.

[More info](CloseTheLoop/README.md)

---
[License](../LICENSE)


text:
package io.github.mzmine.gui.chartbasics.simplechart.renderers;

import io.github.mzmine.gui.chartbasics.simplechart.SimpleChartUtility;
import io.github.mzmine.gui.chartbasics.simplechart.datasets.ColoredXYZPieDataset;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jfree.chart.LegendItem;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRendererState;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetUtils;
import org.jfree.data.xy.XYDataset;

/**
 * Copied from {@link org.jfree.chart.renderer.xy.XYBlockRenderer}. Modified to use the data set
 * color and draw pie charts based on {@link io.github.mzmine.gui.chartbasics.simplechart.providers.PieXYZDataProvider}s.
 *
 * @author https://github.com/SteffenHeu
 */
public class ColoredXYZPieRenderer extends AbstractXYItemRenderer
    implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {

  private static final Logger logger = Logger.getLogger(ColoredXYZPieRenderer.class.getName());

  private ColoredXYZPieDataset<?> currentDataset = null;

  /**
   * Creates a new {@code ColoredXYZPieRenderer} instance with default attributes.
   */
  public ColoredXYZPieRenderer() {
    super();
    SimpleChartUtility.tryApplyDefaultChartThemeToRenderer(this);
    // default
  }

  /**
   * Returns the lower and upper bounds (range) of the x-values in the specified dataset.
   *
   * @param dataset the dataset ({@code null} permitted).
   * @return The range ({@code null} if the dataset is {@code null} or empty).
   * @see #findRangeBounds(XYDataset)
   */
  @Override
  public Range findDomainBounds(XYDataset dataset) {
    if (dataset == null) {
      return null;
    }
    Range r = DatasetUtils.findDomainBounds(dataset, false);
    if (r == null) {
      return null;
    }
    return new Range(r.getLowerBound(),
        r.getUpperBound());
  }

  /**
   * Returns the range of values the renderer requires to display all the items from the specified
   * dataset.
   *
   * @param dataset the dataset ({@code null} permitted).
   * @return The range ({@code null} if the dataset is {@code null} or empty).
   * @see #findDomainBounds(XYDataset)
   */
  @Override
  public Range findRangeBounds(XYDataset dataset) {
    if (dataset != null) {
      Range r = DatasetUtils.findRangeBounds(dataset, false);
      if (r == null) {
        return null;
      } else {
        return new Range(r.getLowerBound(), r.getUpperBound());
      }
    } else {
      return null;
    }
  }

  /**
   * Draws the block representing the specified item.
   *
   * @param g2             the graphics device.
   * @param state          the state.
   * @param dataArea       the data area.
   * @param info           the plot rendering info.
   * @param plot           the plot.
   * @param domainAxis     the x-axis.
   * @param rangeAxis      the y-axis.
   * @param dataset        the dataset.
   * @param series         the series index.
   * @param item           the item index.
   * @param crosshairState the crosshair state.
   * @param pass           the pass index.
   */
  @Override
  public void drawItem(Graphics2D g2, XYItemRendererState state,
      Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
      ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
      int series, int item, CrosshairState crosshairState, int pass) {

    if (!(dataset instanceof ColoredXYZPieDataset<?> pieDataset) || series > 0) {
      // we draw all series at once, because we need all values at once to draw the pie correctly.
      return;
    }

    currentDataset = pieDataset;

    final double x = dataset.getXValue(series, item);
    final double y = dataset.getYValue(series, item);
    final double z = pieDataset.getZValue(item);
    final double pieDiameter = pieDataset.getPieDiameter(item);

    double cx = domainAxis.valueToJava2D(x, dataArea,
        plot.getDomainAxisEdge()) - pieDiameter / 2;
    double cy = rangeAxis.valueToJava2D(y, dataArea,
        plot.getRangeAxisEdge()) - pieDiameter / 2;

    int startAngle = 0;
    for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {
      try {
        final double value = pieDataset.getZValue(seriesIndex, item);
        final int endAngle = (int) (value * 360 / z);

        g2.setPaint(pieDataset.getSliceColor(seriesIndex));
        g2.fill(new Arc2D.Double(cx, cy, pieDiameter,
            pieDataset.getPieDiameter(item), startAngle, endAngle, Arc2D.PIE));
        startAngle += endAngle;

      } catch (ClassCastException e) {
        e.printStackTrace();
        logger.log(Level.WARNING, e,
            () -> "The identifier delivered by the dataset could not be cast to the required generic type.");
        return;
      }
    }

    g2.setPaint(Color.BLACK);
    g2.draw(new Arc2D.Double(cx, cy, pieDiameter,
        pieDiameter, 0, 360, Arc2D.OPEN));

    final PlotOrientation orientation = plot.getOrientation();

    if (isItemLabelVisible(series, item)) {
      drawItemLabel(g2, orientation, dataset, series, item,
          cx, y + pieDiameter, y < 0.0);
    }

    int datasetIndex = plot.indexOf(dataset);
    double transX = domainAxis.valueToJava2D(x, dataArea,
        plot.getDomainAxisEdge());
    double transY = rangeAxis.valueToJava2D(y, dataArea,
        plot.getRangeAxisEdge());
    updateCrosshairValues(crosshairState, x, y, datasetIndex,
        transX, transY, orientation);

    EntityCollection entities = state.getEntityCollection();
    if (entities != null) {
      addEntity(entities, new Ellipse2D.Double(cx, cy, pieDiameter, pieDiameter), dataset, series, item,
          cx + pieDiameter / 2, cy + pieDiameter / 2);
    }

  }

  /**
   * Tests this {@code XYBlockRenderer} for equality with an arbitrary object.  This method returns
   * {@code true} if and only if:
   *

   *
{@code obj} is an instance of {@code XYBlockRenderer} (not
   *     {@code null});

   *
{@code obj} has the same field values as this
   *     {@code XYBlockRenderer};

   *

   *
   * @param obj the object ({@code null} permitted).
   * @return A boolean.
   */
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof ColoredXYZPieRenderer)) {
      return false;
    }
    return super.equals(obj);
  }

  /**
   * Returns a clone of this renderer.
   *
   * @return A clone of this renderer.
   * @throws CloneNotSupportedException if there is a problem creating the clone.
   */
  @Override
  public Object clone() throws CloneNotSupportedException {
    ColoredXYZPieRenderer clone = new ColoredXYZPieRenderer();
    return clone;
  }

  @Override
  public LegendItem getLegendItem(int datasetIndex, int series) {
    XYDataset dataset = getPlot().getDataset(datasetIndex);
    if ((dataset instanceof ColoredXYZPieDataset<?> ds)) {
      currentDataset = ds;
    }
    return super.getLegendItem(datasetIndex, series);
  }

  @Override
  public Paint lookupSeriesPaint(int series) {
    if (currentDataset != null) {
      return currentDataset.getSliceColor(series);
    }
    return super.lookupSeriesPaint(series);
  }
}


text:
class Game < ActiveRecord::Base
  belongs_to :round

  belongs_to :next_game, class: Game
  has_many :previous_games, class: Game, foreign_key: :next_game_id

  has_many :slots

  after_create :create_slots

  private

  def create_slots
    2.times do |_index|
      slots.create
    end
    end
end


text:
/**
 * Created by w.ding on 12/04/15.
 */
var React = require('react')
var ProductSummary = require('./ProductSummary')

var CheckoutDone = React.createClass({

    render: function() {
        var summaries = this.props.products.map(function(product) {
            return <ProductSummary key={ product.id } product={ product } />
        })

        return (

Your cats are on their way!

(just kidding)

But here are their favorite quotes on liberty:

              { summaries }

                        Tweet

                    <button type="button" className="btn btn-success" onClick={ this.handleDoneClick }>
                        Done
                    </button>

        )
    }
})

module.exports = CheckoutDone


text:
int main(){
	std::string right_password = "right_password";
	std::string wrong_password = "wrong_password";

	std::cout << "generate hash... " << std::flush;
	std::string hash = BCrypt::generateHash(right_password, 12);
	std::cout << "done." << std::endl;

	std::cout << "checking right password: " << std::flush
			  << BCrypt::validatePassword(right_password,hash) << std::endl;

	std::cout << "checking wrong password: " << std::flush
			  << BCrypt::validatePassword(wrong_password,hash) << std::endl;

	return 0;
}


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

namespace BtrieveWrapper.Orm
{
    public sealed class Transaction : IDisposable
    {

        bool _disposed = false, _committed = false;
        NativeOperator _operator;

        internal Transaction(NativeOperator nativeOperator , TransactionMode transactionMode, LockMode lockMode) {
            _operator = nativeOperator;
            this.TransactionMode = transactionMode;
            this.LockMode = lockMode;
            _operator.BeginTransaction(transactionMode, Utility.GetLockBias(lockMode));
        }

        public TransactionMode TransactionMode { get; private set; }
        public LockMode LockMode { get; private set; }

        public event EventHandler Committing = null;
        public event EventHandler Committed = null;
        public event EventHandler Rollbacking = null;
        public event EventHandler Rollbacked = null;
        public event EventHandler Disposing = null;

        public void Commit(bool detachAllRecordsAfterCommit = false) {
            if (_disposed) {
                throw new InvalidOperationException();
            }
            if (this.Committing != null) {
                this.Committing(this, null);
            }
            try {
                _operator.EndTransaction();
                _committed = true;
                if (this.Committed != null) {
                    this.Committed(this, null);
                }
            } finally {
                this.Dispose();
            }
        }

        void Dispose(bool disposing) {
            if (disposing) {
                if (!_disposed) {
                    if (!_committed && this.Rollbacking != null) {
                        this.Rollbacking(this, null);
                    }
                    try {
                        _operator.AbortTransaction();
                        if (!_committed && this.Rollbacked != null) {
                            this.Rollbacked(this, null);
                        }
                    } catch (OperationException e) {
                        if (e.StatusCode != 39) {
                            throw;
                        }
                    } finally {
                        _disposed = true;
                        if (this.Disposing != null) {
                            this.Disposing(this, null);
                        }
                    }
                }
            }
        }

        public void Dispose() {
            this.Dispose(true);
        }
    }
}


text:
namespace Thinktecture.IdentityServer.Core.ViewModels
{
    /// <summary>
    /// Models the data needed to render the logout prompt page.
    /// </summary>
    public class LogoutViewModel : CommonViewModel
    {
        /// <summary>
        /// The URL to POST to to trigger a logout.
        /// </summary>
        /// <value>
        /// The logout URL.
        /// </value>
        public string LogoutUrl { get; set; }

        /// <summary>
        /// The anti forgery values.
        /// </summary>
        /// <value>
        /// The anti forgery.
        /// </value>
        public AntiForgeryTokenViewModel AntiForgery { get; set; }

        /// <summary>
        /// The name of the client that requested the logout.
        /// </summary>
        /// <value>
        /// The name of the client.
        /// </value>
        public string ClientName { get; set; }
    }
}


text:
import List from './List';
import Loader from './Loader';
import ThirdLoader from './ThirdLoader'

export default {
    components: {
        listA: {
            creator: List,
            args: [document.getElementById('a'), {$ref: 'loader'}]
        },
        listB: {
            creator: List,
            args: [document.getElementById('b'), {$ref: 'thirdLoader'}]
        },
        loader: {
            creator: Loader,
            args: ['list.json']
        },
        thirdLoader: {
            creator: ThirdLoader
        }
    }
};


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>管理后台</title>
<link rel="stylesheet" href="{skin:css/admin.css}" />
{js:jquery}
{js:dialog}
{js:form}
{js:validate}
{js:artTemplate}

	<form name="balanceForm" callback="submitCallback();" action="#">

			<col width="120px" />
			<col />

				请选择:

					<select name="type" class="auto" pattern='required'>
						<option value="">请选择操作类型</option>
						<option value="recharge">充值账户余额</option>
						<option value="withdraw">账户余额提现</option>
					</select>

				请输入金额:
				<input name="balance" class="small" type="text" maxlength="8" pattern='float' alt='必须要填写金额数字' />

	</form>


text:
using testing::NiceMock;

namespace Envoy {
namespace Upstream {
namespace {

// Test Cluster Factory without custom configuration
class TestStaticClusterFactory : public Event::TestUsingSimulatedTime,
                                 public ClusterFactoryImplBase {

public:
  TestStaticClusterFactory() : ClusterFactoryImplBase("envoy.clusters.test_static") {}

  std::pair<ClusterImplBaseSharedPtr, ThreadAwareLoadBalancerPtr> createClusterImpl(
      Server::Configuration::ServerFactoryContext& server_context,
      const envoy::config::cluster::v3::Cluster& cluster, ClusterFactoryContext& context,
      Server::Configuration::TransportSocketFactoryContextImpl& socket_factory_context,
      Stats::ScopeSharedPtr&& stats_scope) override {
    return std::make_pair(std::make_shared<CustomStaticCluster>(
                              server_context, cluster, context.runtime(), socket_factory_context,
                              std::move(stats_scope), context.addedViaApi(), 1, "127.0.0.1", 80),
                          nullptr);
  }
};

class ClusterFactoryTestBase {
protected:
  ClusterFactoryTestBase() {
    outlier_event_logger_ = std::make_shared<Outlier::MockEventLogger>();
    dns_resolver_ = std::make_shared<Network::MockDnsResolver>();
  }

  NiceMock<Server::Configuration::MockServerFactoryContext> server_context_;
  Ssl::MockContextManager ssl_context_manager_;
  NiceMock<MockClusterManager> cm_;
  Stats::TestUtil::TestStore stats_;
  NiceMock<ProtobufMessage::MockValidationVisitor> validation_visitor_;
  Network::DnsResolverSharedPtr dns_resolver_;
  std::function<Network::DnsResolverSharedPtr()> dns_resolver_fn_ =
      [this]() -> Network::DnsResolverSharedPtr { return this->dns_resolver_; };
  AccessLog::MockAccessLogManager log_manager_;
  Outlier::EventLoggerSharedPtr outlier_event_logger_;
};

class TestStaticClusterImplTest : public testing::Test, public ClusterFactoryTestBase {};

TEST_F(TestStaticClusterImplTest, CreateWithoutConfig) {
  const std::string yaml = R"EOF(
      name: staticcluster
      connect_timeout: 0.25s
      lb_policy: ROUND_ROBIN
      load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 443
      cluster_type:
        name: envoy.clusters.test_static
    )EOF";

  TestStaticClusterFactory factory;
  Registry::InjectFactory<ClusterFactory> registered_factory(factory);

  const envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
  auto create_result = ClusterFactoryImplBase::create(
      server_context_, cluster_config, cm_, stats_, dns_resolver_fn_, ssl_context_manager_,
      std::move(outlier_event_logger_), false, validation_visitor_);
  auto cluster = create_result.first;
  cluster->initialize([] {});

  EXPECT_EQ(1UL, cluster->prioritySet().hostSetsPerPriority()[1]->healthyHosts().size());
  EXPECT_EQ("", cluster->prioritySet().hostSetsPerPriority()[1]->hosts()[0]->hostname());
  // the hosts field override by values hardcoded in the factory
  EXPECT_EQ("127.0.0.1", cluster->prioritySet()
                             .hostSetsPerPriority()[1]
                             ->hosts()[0]
                             ->address()
                             ->ip()
                             ->addressAsString());
  EXPECT_EQ(80,
            cluster->prioritySet().hostSetsPerPriority()[1]->hosts()[0]->address()->ip()->port());
  EXPECT_FALSE(cluster->info()->addedViaApi());
}

TEST_F(TestStaticClusterImplTest, CreateWithStructConfig) {
  const std::string yaml = R"EOF(
      name: staticcluster
      connect_timeout: 0.25s
      lb_policy: ROUND_ROBIN
      load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 443
      cluster_type:
          name: envoy.clusters.custom_static
          typed_config:
            "@type": type.googleapis.com/google.protobuf.Struct
            value:
              priority: 10
              address: 127.0.0.1
              port_value: 80
    )EOF";

  const envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
  auto create_result = ClusterFactoryImplBase::create(
      server_context_, cluster_config, cm_, stats_, dns_resolver_fn_, ssl_context_manager_,
      std::move(outlier_event_logger_), false, validation_visitor_);
  auto cluster = create_result.first;
  cluster->initialize([] {});

  EXPECT_EQ(1UL, cluster->prioritySet().hostSetsPerPriority()[10]->healthyHosts().size());
  EXPECT_EQ("", cluster->prioritySet().hostSetsPerPriority()[10]->hosts()[0]->hostname());
  EXPECT_EQ("127.0.0.1", cluster->prioritySet()
                             .hostSetsPerPriority()[10]
                             ->hosts()[0]
                             ->address()
                             ->ip()
                             ->addressAsString());
  EXPECT_EQ(80,
            cluster->prioritySet().hostSetsPerPriority()[10]->hosts()[0]->address()->ip()->port());
  EXPECT_FALSE(cluster->info()->addedViaApi());
}

TEST_F(TestStaticClusterImplTest, CreateWithTypedConfig) {
  const std::string yaml = R"EOF(
      name: staticcluster
      connect_timeout: 0.25s
      lb_policy: ROUND_ROBIN
      load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 443
      cluster_type:
          name: envoy.clusters.custom_static
          typed_config:
            "@type": type.googleapis.com/test.integration.clusters.CustomStaticConfig
            priority: 10
            address: 127.0.0.1
            port_value: 80
    )EOF";

  const envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
  auto create_result = ClusterFactoryImplBase::create(
      server_context_, cluster_config, cm_, stats_, dns_resolver_fn_, ssl_context_manager_,
      std::move(outlier_event_logger_), false, validation_visitor_);
  auto cluster = create_result.first;
  cluster->initialize([] {});

  EXPECT_EQ(1UL, cluster->prioritySet().hostSetsPerPriority()[10]->healthyHosts().size());
  EXPECT_EQ("", cluster->prioritySet().hostSetsPerPriority()[10]->hosts()[0]->hostname());
  EXPECT_EQ("127.0.0.1", cluster->prioritySet()
                             .hostSetsPerPriority()[10]
                             ->hosts()[0]
                             ->address()
                             ->ip()
                             ->addressAsString());
  EXPECT_EQ(80,
            cluster->prioritySet().hostSetsPerPriority()[10]->hosts()[0]->address()->ip()->port());
  EXPECT_FALSE(cluster->info()->addedViaApi());
}

TEST_F(TestStaticClusterImplTest, UnsupportedClusterType) {
  const std::string yaml = R"EOF(
    name: staticcluster
    connect_timeout: 0.25s
    lb_policy: ROUND_ROBIN
    load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 443
    cluster_type:
        name: envoy.clusters.bad_cluster_name
        typed_config:
          "@type": type.googleapis.com/test.integration.clusters.CustomStaticConfig
          priority: 10
  )EOF";
  // the factory is not registered, expect to throw
  EXPECT_THROW_WITH_MESSAGE(
      {
        const envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
        ClusterFactoryImplBase::create(
            server_context_, cluster_config, cm_, stats_, dns_resolver_fn_, ssl_context_manager_,
            std::move(outlier_event_logger_), false, validation_visitor_);
      },
      EnvoyException,
      "Didn't find a registered cluster factory implementation for name: "
      "'envoy.clusters.bad_cluster_name'");
}

TEST_F(TestStaticClusterImplTest, HostnameWithoutDNS) {
  const std::string yaml = R"EOF(
      name: staticcluster
      connect_timeout: 0.25s
      lb_policy: ROUND_ROBIN
      common_lb_config:
        consistent_hashing_lb_config:
          use_hostname_for_hashing: true
      load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 443
      cluster_type:
        name: envoy.clusters.test_static
    )EOF";

  EXPECT_THROW_WITH_MESSAGE(
      {
        const envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
        ClusterFactoryImplBase::create(
            server_context_, cluster_config, cm_, stats_, dns_resolver_fn_, ssl_context_manager_,
            std::move(outlier_event_logger_), false, validation_visitor_);
      },
      EnvoyException,
      "Cannot use hostname for consistent hashing loadbalancing for cluster of type: "
      "'envoy.clusters.test_static'");
}

} // namespace
} // namespace Upstream
} // namespace Envoy


text:
var HUD = require('../lib/hud');

// data
var testdata = (require('./fixtures/navdata.json')).data;

// canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var h = new HUD(canvas);
var i = 0;

setInterval(function() {
  h.clear();
  var data = (testdata.shift()).demo;

  ctx.shadowColor = 'black';
  ctx.shadowBlur = 1;

  //ctx.strokeStyle = h.rgba(0, 125, 255, h.opacity);
  h.name('NODECOPTER')
  h.cartesian(data);
  h.drone(data);
  h.battery(data.batteryPercentage);

  // simulate up/down altitude since test data dont have it
  // between 0 and 30m
  data.altitudeMeters = Math.abs(Math.floor((Math.sin((Math.PI * 2) * i) - 1) * 15));
  h.altimeter(data.altitudeMeters);

  h.render();
  i += 0.01;
}, 100);