text:
package jsrl.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import jsrl.gui.Monitor.Data;
import jsrl.sys.SystemInfo;

public class CpuMonitor extends Monitor implements MouseListener
{
	private static final long serialVersionUID = 1L;

	protected Data cpu_total = new Data();
	protected Data cpu_user = new Data();
	protected Data cpu_kernel = new Data();

	protected List<Data> cpus = new Vector<Data>();

	public CpuMonitor()
	{
		cpu_user.show_bar = false;
		cpu_user.color = Color.WHITE;

		cpu_kernel.show_bar = false;
		cpu_kernel.color = Color.RED;

		SystemInfo sysinfo = SystemInfo.getInstance();
		header = sysinfo.cpu().modelName() + " x " + sysinfo.cpuCount();
		footer = "";
		add(cpu_total);
		add(cpu_user);
		add(cpu_kernel);

//		if (sysinfo.cpuCount() > 1)
//		{
//			for (int i=0;i<sysinfo.cpuCount();++i)
//			{
//				Data cpu = new Data();
//				cpu.show_plot = false;
//				cpus.add(cpu);
//				add(cpu);
//			}
//		}

		this.addMouseListener(this);
	}

	protected void update()
	{
		SystemInfo sysinfo = SystemInfo.getInstance();
		sysinfo.update();

		footer = String.format(" user: %d%%  kernel: %d%%",
				(int)sysinfo.cpu().userLoad(),(int)sysinfo.cpu().kernelLoad());

		cpu_total.add(sysinfo.cpu().load());
		cpu_user.add(sysinfo.cpu().userLoad());
		cpu_kernel.add(sysinfo.cpu().kernelLoad());

		if (lbl_freq != null)
		{
			lbl_freq.setText("" + sysinfo.cpu().speed());
		}

		int pos = 0;
		for (Data cpu : cpus)
		{
			cpu.add(sysinfo.getCPU(pos).load());
			++pos;
		}

	}

	protected JFrame cpu_info_window = null;
	protected JLabel lbl_freq = null;
	public void showCpuInfo()
	{
		if (cpu_info_window == null)
		{
			JPanel panel = new JPanel();
	        panel.setLayout(new GridBagLayout());
	        GridBagConstraints c = new GridBagConstraints();

	        c.fill = GridBagConstraints.HORIZONTAL;

	        SystemInfo sysinfo = SystemInfo.getInstance();
	        int y = 0;

	        JLabel lbl = new JLabel("Vendor ID:", SwingConstants.RIGHT);
	        c.gridx = 0;
	        c.gridy = y;
	        c.weightx = 1.0;
	        panel.add(lbl, c);

	        JLabel value = new JLabel(sysinfo.cpu().vendor());
	        value.setForeground(cpu_total.color);
	        c.gridx = 1;
	        c.gridy = y;
	        c.gridwidth = 3;
	        panel.add(value, c);

	        lbl = new JLabel("Freq:", SwingConstants.RIGHT);
	        c.gridx = 2;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(lbl, c);
	        lbl_freq = new JLabel("" + sysinfo.cpu().speed());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 1;
	        c.gridx = 3;
	        c.gridy = y;
	        panel.add(lbl_freq, c);

	        ++y;
	        lbl = new JLabel("Model Name:", SwingConstants.RIGHT);
	        c.gridx = 0;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(lbl, c);
	        value = new JLabel(sysinfo.cpu().modelName());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 5;
	        c.gridx = 1;
	        c.gridy = y;
	        panel.add(value, c);

	        ++y;
	        lbl = new JLabel("Family:", SwingConstants.RIGHT);
	        c.gridx = 0;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.cpu().family());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 1;
	        c.gridx = 1;
	        c.gridy = y;
	        panel.add(value, c);

	        lbl = new JLabel("Model:", SwingConstants.RIGHT);
	        c.gridx = 2;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.cpu().model());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 1;
	        c.gridx = 3;
	        c.gridy = y;
	        panel.add(value, c);

	        lbl = new JLabel("Type:", SwingConstants.RIGHT);
	        c.gridx = 4;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.cpu().type());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 5;
	        c.gridx = 5;
	        c.gridy = y;
	        panel.add(value, c);

	        ++y;
	        lbl = new JLabel("Hyper-Threading Support:", SwingConstants.RIGHT);
	        c.gridx = 0;
	        c.gridy = y;
	        c.gridwidth = 2;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.isHtSupported());
	        value.setForeground(cpu_total.color);
	        c.gridwidth = 1;
	        c.gridx = 2;
	        c.gridy = y;
	        panel.add(value, c);

	        lbl = new JLabel("Hyper-Threading Enabled:", SwingConstants.RIGHT);
	        c.gridx = 2;
	        c.gridy = y;
	        c.gridwidth = 2;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.isHtEnabled());
	        value.setForeground(cpu_total.color);
	        c.gridx = 4;
	        c.gridy = y;
	        c.gridwidth = 1;
	        panel.add(value, c);

	        ++y;
	        lbl = new JLabel("Logical Processors:", SwingConstants.RIGHT);
	        c.gridx = 0;
	        c.gridy = y;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.numberOfLogicalProcessors());
	        value.setForeground(cpu_total.color);
	        c.gridx = 1;
	        c.gridy = y;
	        panel.add(value, c);

	        lbl = new JLabel("Physical Processors:", SwingConstants.RIGHT);
	        c.gridx = 2;
	        c.gridy = y;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.numberOfPhysicalProcessors());
	        value.setForeground(cpu_total.color);
	        c.gridx = 3;
	        c.gridy = y;
	        panel.add(value, c);

	        lbl = new JLabel("Cores Per Processor:", SwingConstants.RIGHT);
	        c.gridx = 4;
	        c.gridy = y;
	        panel.add(lbl, c);
	        value = new JLabel("" + sysinfo.numberOfCoresPerProcessor());
	        value.setForeground(cpu_total.color);
	        c.gridx = 5;
	        c.gridy = y;
	        panel.add(value, c);

	//        lbl = new JLabel("Signature:");
	//        c.gridx = 0;
	//        c.gridy = y;
	//        panel.add(lbl, c);
	//        value = new JLabel(sysinfo.cpu().model());
	//        c.gridx = 1;
	//        c.gridy = y;
	//        panel.add(value, c);

	        cpu_info_window = new JFrame("CPU Info");
			//f.addWindowListener(panel);
	        cpu_info_window.getContentPane().add("Center", panel);
	        cpu_info_window.pack();
	        cpu_info_window.setSize(new Dimension(620, 120));
	        cpu_info_window.setVisible(true);

		}
		else
		{
			cpu_info_window.setVisible(true);
			cpu_info_window.toFront();
		}
	}
	public void mouseClicked(MouseEvent evt) {
		// TODO Auto-generated method stub
		if (evt.getButton() > 1)
			showCpuInfo();

	}

	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		final MonitorPanel demo = new MonitorPanel("CPU", new CpuMonitor());
		WindowListener l = new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				System.exit(0);
			}

			public void windowDeiconified(WindowEvent e)
			{
				demo.monitor.start();
			}

			public void windowIconified(WindowEvent e)
			{
				demo.monitor.stop();
			}
		};
		JFrame f = new JFrame("CPU Monitor");
		f.addWindowListener(l);
		f.getContentPane().add("Center", demo);
		f.pack();
		f.setSize(new Dimension(200, 200));
		f.setVisible(true);
		demo.monitor.start();
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.homedns.mkh</groupId>
  <artifactId>databuffer</artifactId>
  <version>1.1.0</version>

    <name>Databuffer</name>
    <description>Database interfacing and data buffering library based on RowSet Implementation</description>
    <url>https://github.com/khomisha/databuffer.git</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

  <dependencies>
  	<dependency>
  		<groupId>com.google.code.gson</groupId>
  		<artifactId>gson</artifactId>
  		<version>2.2.4</version>
  	</dependency>
  	<dependency>
  		<groupId>org.homedns.mkh</groupId>
  		<artifactId>sql-modifier</artifactId>
  		<version>0.0.3</version>
  	</dependency>
  	<dependency>
  		<groupId>log4j</groupId>
  		<artifactId>log4j</artifactId>
  		<version>1.2.17</version>
  	</dependency>
		<dependency>
			<groupId>org.homedns.mkh</groupId>
			<artifactId>util</artifactId>
			<version>0.0.1</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-dbcp2</artifactId>
		    <version>2.7.0</version>
		</dependency>
  </dependencies>
  <build>
	<plugins>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-compiler-plugin</artifactId>
	        <version>2.3.2</version>
	        <configuration>
	          <source>1.8</source>
	          <target>1.8</target>
	        </configuration>
	      </plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-source-plugin</artifactId>
			<version>2.2.1</version>
			<executions>
				<execution>
					<id>attach-sources</id>
					<goals>
						<goal>jar</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <show>protected</show>
          <bottom>Copyright © {inceptionYear}-{currentYear} MKH. All Rights Reserved.</bottom>
        </configuration>
      </plugin>
		<plugin>
		    <groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-jar-plugin</artifactId>
        	<version>2.5</version>
		    <configuration>
		        <archive>
		            <manifest>
		                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
		                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
		            </manifest>
		        </archive>
		    </configuration>
		</plugin>
		<plugin>
		  <groupId>org.jasig.maven</groupId>
		  <artifactId>maven-notice-plugin</artifactId>
		  <version>1.0.4</version>
		  <configuration>
		    <noticeTemplate>https://source.jasig.org/licenses/NOTICE.template</noticeTemplate>

		    <licenseMapping>
		      <param>https://source.jasig.org/licenses/license-mappings.xml</param>
		    </licenseMapping>
		  </configuration>
		</plugin>
	</plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview Earth Engine Developer's Guide examples
 *     from ee.ImageCollection charting section
 */

// [START earthengine__charts_image_collection__doy_series_line_chart]
// Import the example feature collection and subset the grassland feature.
var grassland = ee.FeatureCollection('projects/google/charts_feature_example')
                    .filter(ee.Filter.eq('label', 'Grassland'));

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define the chart and print it to the console.
var chart =
    ui.Chart.image
        .doySeries({
          imageCollection: vegIndices,
          region: grassland,
          regionReducer: ee.Reducer.mean(),
          scale: 500,
          yearReducer: ee.Reducer.mean(),
          startDay: 1,
          endDay: 365
        })
        .setSeriesNames(['EVI', 'NDVI'])
        .setOptions({
          title: 'Average Vegetation Index Value by Day of Year for Grassland',
          hAxis: {
            title: 'Day of year',
            titleTextStyle: {italic: false, bold: true}
          },
          vAxis: {
            title: 'Vegetation index (x1e4)',
            titleTextStyle: {italic: false, bold: true}
          },
          lineWidth: 5,
          colors: ['e37d05', '1d6b99'],
        });
print(chart);
// [END earthengine__charts_image_collection__doy_series_line_chart]

// [START earthengine__charts_image_collection__doy_series_by_year_line_chart]
// Import the example feature collection and subset the grassland feature.
var grassland = ee.FeatureCollection('projects/google/charts_feature_example')
                    .filter(ee.Filter.eq('label', 'Grassland'));

// Load MODIS vegetation indices data and subset years 2012 and 2019.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.or(
                         ee.Filter.date('2012-01-01', '2013-01-01'),
                         ee.Filter.date('2019-01-01', '2020-01-01')))
                     .select(['NDVI', 'EVI']);

// Define the chart and print it to the console.
var chart = ui.Chart.image
                .doySeriesByYear({
                  imageCollection: vegIndices,
                  bandName: 'NDVI',
                  region: grassland,
                  regionReducer: ee.Reducer.mean(),
                  scale: 500,
                  sameDayReducer: ee.Reducer.mean(),
                  startDay: 1,
                  endDay: 365
                })
                .setOptions({
                  title: 'Average NDVI Value by Day of Year for Grassland',
                  hAxis: {
                    title: 'Day of year',
                    titleTextStyle: {italic: false, bold: true}
                  },
                  vAxis: {
                    title: 'NDVI (x1e4)',
                    titleTextStyle: {italic: false, bold: true}
                  },
                  lineWidth: 5,
                  colors: ['39a8a7', '9c4f97'],
                });
print(chart);
// [END earthengine__charts_image_collection__doy_series_by_year_line_chart]

// [START earthengine__charts_image_collection__doy_series_by_region_line_chart]
// Import the example feature collection.
var ecoregions = ee.FeatureCollection('projects/google/charts_feature_example');

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define the chart and print it to the console.
var chart = ui.Chart.image
                .doySeriesByRegion({
                  imageCollection: vegIndices,
                  bandName: 'NDVI',
                  regions: ecoregions,
                  regionReducer: ee.Reducer.mean(),
                  scale: 500,
                  yearReducer: ee.Reducer.mean(),
                  seriesProperty: 'label',
                  startDay: 1,
                  endDay: 365
                })
                .setOptions({
                  title: 'Average NDVI Value by Day of Year',
                  hAxis: {
                    title: 'Day of year',
                    titleTextStyle: {italic: false, bold: true}
                  },
                  vAxis: {
                    title: 'NDVI (x1e4)',
                    titleTextStyle: {italic: false, bold: true}
                  },
                  lineWidth: 5,
                  colors: ['f0af07', '0f8755', '76b349'],
                });
print(chart);
// [END earthengine__charts_image_collection__doy_series_by_region_line_chart]

// [START earthengine__charts_image_collection__series_line_chart]
// Import the example feature collection and subset the forest feature.
var forest = ee.FeatureCollection('projects/google/charts_feature_example')
                 .filter(ee.Filter.eq('label', 'Forest'));

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define the chart and print it to the console.
var chart =
    ui.Chart.image
        .series({
          imageCollection: vegIndices,
          region: forest,
          reducer: ee.Reducer.mean(),
          scale: 500,
          xProperty: 'system:time_start'
        })
        .setSeriesNames(['EVI', 'NDVI'])
        .setOptions({
          title: 'Average Vegetation Index Value by Date for Forest',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {
            title: 'Vegetation index (x1e4)',
            titleTextStyle: {italic: false, bold: true}
          },
          lineWidth: 5,
          colors: ['e37d05', '1d6b99'],
          curveType: 'function'
        });
print(chart);
// [END earthengine__charts_image_collection__series_line_chart]

// [START earthengine__charts_image_collection__series_by_region_chart]
// Import the example feature collection.
var ecoregions = ee.FeatureCollection('projects/google/charts_feature_example');

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define the chart and print it to the console.
var chart =
    ui.Chart.image
        .seriesByRegion({
          imageCollection: vegIndices,
          band: 'NDVI',
          regions: ecoregions,
          reducer: ee.Reducer.mean(),
          scale: 500,
          seriesProperty: 'label',
          xProperty: 'system:time_start'
        })
        .setOptions({
          title: 'Average NDVI Value by Date',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {
            title: 'NDVI (x1e4)',
            titleTextStyle: {italic: false, bold: true}
          },
          lineWidth: 5,
          colors: ['f0af07', '0f8755', '76b349'],
        });
print(chart);
// [END earthengine__charts_image_collection__series_by_region_chart]


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "default", {
  enumerable: true,
  get: function get() {
    return _ExpansionPanel.default;
  }
});

var _ExpansionPanel = _interopRequireDefault(require("./ExpansionPanel"));


text:
package org.vizzini.core.game;

import org.vizzini.core.NamedObject;

/**
 * Defines methods required by an adjudicator.
 */
public interface Adjudicator extends NamedObject
{
    /**
     * @param environment Environment.
     *
     * @return the agent if someone has won, null otherwise.
     */
    Agent determineWinner(Environment environment);

    /**
     * @return description
     */
    String getDescription();

    /**
     * @param action Action.
     *
     * @return true if the given action is legal.
     */
    boolean isActionLegal(Action action);

    /**
     * @param environment Environment.
     *
     * @return true if the given environment represents a completed game.
     */
    boolean isGameOver(Environment environment);
}


text:
import os
import gc
import logging

class Postfix(object):
    def __init__(self):
        gc.enable()

    @staticmethod
    def get_kind():
        """
        return sensor kind
        """
        return "mppostfix"

    @staticmethod
    def get_sensordef():
        """
        Definition of the sensor and data to be shown in the PRTG WebGUI
        """
        sensordefinition = {
            "kind": Postfix.get_kind(),
            "name": "Postfix Mailqueue",
            "description": "Monitors the mailqueue of a postfix server",
            "help": "Monitors the mailqueue of a postfix server for active, deferred, hold or corrupt mail",
            "tag": "mppostfixsensor",
            "fields": [],
            "groups": []
        }
        return sensordefinition

    def check(self):
        spoolcmd = os.popen("postconf -h queue_directory")
        spooldir = spoolcmd.readline().replace('\n', '')
        spoolcmd.close()
        deferredcmd = os.popen("test -d %s/deferred && find %s/deferred -type f | wc -l" % (spooldir, spooldir))
        deferredcnt = deferredcmd.readline().replace('\n', '')
        deferredcmd.close()
        activecmd = os.popen("test -d %s/active && find %s/active -type f | wc -l" % (spooldir, spooldir))
        activecnt = activecmd.readline().replace('\n', '')
        activecmd.close()
        holdcmd = os.popen("test -d %s/hold && find %s/hold -type f | wc -l" % (spooldir, spooldir))
        holdcnt = holdcmd.readline().replace('\n', '')
        holdcmd.close()
        corruptcmd = os.popen("test -d %s/corrupt && find %s/corrupt -type f | wc -l" % (spooldir, spooldir))
        corruptcnt = corruptcmd.readline().replace('\n', '')
        corruptcmd.close()
        channel_list = [
            {
                "name": "Deferred mails",
                "mode": "integer",
                "unit": "Count",
                "limitmaxwarning": 40,
                "limitmaxerror": 50,
                "limitmode": 1,
                "value": deferredcnt
            },
            {
                "name": "Active mails",
                "mode": "integer",
                "unit": "Count",
                "value": activecnt
            },
            {
                "name": "Hold mails",
                "mode": "integer",
                "unit": "Count",
                "value": holdcnt
            },
            {
                "name": "Corrupt mails",
                "mode": "integer",
                "unit": "Count",
                "value": corruptcnt
            },
        ]
        return channel_list

    @staticmethod
    def get_data(data, out_queue):
        postfix = Postfix()
        try:
            postfixdata = postfix.check()
            data_r = {
                "sensorid": int(data['sensorid']),
                "message": "OK",
                "channel": postfixdata
            }
            logging.debug("Running sensor: %s" % postfix.get_kind())
        except Exception as e:
            logging.error("Ooops Something went wrong with '%s' sensor %s. Error: %s" % (postfix.get_kind(),
                                                                                data['sensorid'], e))
            data_r = {
                "sensorid": int(data['sensorid']),
                "error": "Exception",
                "code": 1,
                "message": "Postfix failed. %s" % e
            }
            out_queue.put(data_r)
            return 1
        del postfix
        gc.collect()
        out_queue.put(data_r)
        return 0


text:
<?php

namespace spec\EasyForms\Bridges\Zend\InputFilter;

use EasyForms\Form;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Zend\InputFilter\InputFilter;

class InputFilterValidatorSpec extends ObjectBehavior
{
    function it_should_not_add_messages_to_form_when_validation_succeeds(Form $form, InputFilter $filter)
    {
        $submittedValues = [
            'username' => 'john.doe',
            'password' => 'changeme',
        ];

        $this->beConstructedWith($filter);
        $filter->setData($submittedValues)->shouldBeCalled();
        $filter->isValid()->willReturn(true);
        $filter->getValues()->willReturn($submittedValues);
        $form->values()->willReturn($submittedValues);
        $form->submit($submittedValues)->shouldBeCalled();

        $form->setErrorMessages(Argument::type('array'))->shouldNotBeCalled();

        $this->validate($form);
    }

    function it_should_add_messages_to_form_when_validation_fails(Form $form, InputFilter $filter)
    {
        $submittedValues = [
            'username' => 'john.doe',
            'password' => '',
        ];
        $errors = ['password' => 'Password cannot be empty'];

        $this->beConstructedWith($filter);
        $filter->setData($submittedValues)->shouldBeCalled();
        $filter->isValid()->willReturn(false);
        $filter->getMessages()->willReturn($errors);
        $form->values()->willReturn($submittedValues);

        $form->setErrorMessages($errors)->shouldBeCalled();

        $this->validate($form);
    }
}


text:
package StrategoJava;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Stratego extends JPanel {
	public static int SCREEN_WIDTH = 800;
	public static int SCREEN_HEIGHT = 672;

	public static void main(String[] args)
	{
		JFrame jf = new JFrame("My Frame");
		jf.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.add(new Framework());
		jf.setVisible(true);
	}
}


text:
define("dijit/layout/_ContentPaneResizeMixin",["dojo/_base/array","dojo/_base/declare","dojo/dom-class","dojo/dom-geometry","dojo/dom-style","dojo/_base/lang","dojo/query","dojo/sniff","../registry","../Viewport","./utils"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b){
return _2("dijit.layout._ContentPaneResizeMixin",null,{doLayout:true,isLayoutContainer:true,startup:function(){
if(this._started){
return;
}
var _c=this.getParent();
this._childOfLayoutWidget=_c&&_c.isLayoutContainer;
this._needLayout=!this._childOfLayoutWidget;
this.inherited(arguments);
if(this._isShown()){
this._onShow();
}
if(!this._childOfLayoutWidget){
this.own(_a.on("resize",_6.hitch(this,"resize")));
}
},_checkIfSingleChild:function(){
var _d=[],_e=false;
_7("> *",this.containerNode).some(function(_f){
var _10=_9.byNode(_f);
if(_10&&_10.resize){
_d.push(_10);
}else{
if(!/script|link|style/i.test(_f.nodeName)&&_f.offsetHeight){
_e=true;
}
}
});
this._singleChild=_d.length==1&&!_e?_d[0]:null;
_3.toggle(this.containerNode,this.baseClass+"SingleChild",!!this._singleChild);
},resize:function(_11,_12){
this._resizeCalled=true;
this._scheduleLayout(_11,_12);
},_scheduleLayout:function(_13,_14){
if(this._isShown()){
this._layout(_13,_14);
}else{
this._needLayout=true;
this._changeSize=_13;
this._resultSize=_14;
}
},_layout:function(_15,_16){
delete this._needLayout;
if(!this._wasShown&&this.open!==false){
this._onShow();
}
if(_15){
_4.setMarginBox(this.domNode,_15);
}
var cn=this.containerNode;
if(cn===this.domNode){
var mb=_16||{};
_6.mixin(mb,_15||{});
if(!("h" in mb)||!("w" in mb)){
mb=_6.mixin(_4.getMarginBox(cn),mb);
}
this._contentBox=_b.marginBox2contentBox(cn,mb);
}else{
this._contentBox=_4.getContentBox(cn);
}
this._layoutChildren();
},_layoutChildren:function(){
if(this.doLayout){
this._checkIfSingleChild();
}
if(this._singleChild&&this._singleChild.resize){
var cb=this._contentBox||_4.getContentBox(this.containerNode);
this._singleChild.resize({w:cb.w,h:cb.h});
}else{
var _17=this.getChildren(),_18,i=0;
while(_18=_17[i++]){
if(_18.resize){
_18.resize();
}
}
}
},_isShown:function(){
if(this._childOfLayoutWidget){
if(this._resizeCalled&&"open" in this){
return this.open;
}
return this._resizeCalled;
}else{
if("open" in this){
return this.open;
}else{
var _19=this.domNode,_1a=this.domNode.parentNode;
return (_19.style.display!="none")&&(_19.style.visibility!="hidden")&&!_3.contains(_19,"dijitHidden")&&_1a&&_1a.style&&(_1a.style.display!="none");
}
}
},_onShow:function(){
this._wasShown=true;
if(this._needLayout){
this._layout(this._changeSize,this._resultSize);
}
this.inherited(arguments);
}});
});


text:
package org.antlr.v4.codegen.model;

import org.antlr.v4.codegen.OutputModelFactory;
import org.antlr.v4.runtime.misc.IntervalSet;
import org.antlr.v4.tool.ast.GrammarAST;

import java.util.ArrayList;
import java.util.List;

/** */
public class TestSetInline extends SrcOp {
	public int bitsetWordSize;
	public String varName;
	public Bitset[] bitsets;

	public TestSetInline(OutputModelFactory factory, GrammarAST ast, IntervalSet set, int wordSize) {
		super(factory, ast);
		bitsetWordSize = wordSize;
		Bitset[] withZeroOffset = createBitsets(factory, set, wordSize, true);
		Bitset[] withoutZeroOffset = createBitsets(factory, set, wordSize, false);
		this.bitsets = withZeroOffset.length <= withoutZeroOffset.length ? withZeroOffset : withoutZeroOffset;
		this.varName = "_la";
	}

	private static Bitset[] createBitsets(OutputModelFactory factory,
										  IntervalSet set,
										  int wordSize,
										  boolean useZeroOffset) {
		List<Bitset> bitsetList = new ArrayList<Bitset>();
		for (int ttype : set.toArray()) {
			Bitset current = !bitsetList.isEmpty() ? bitsetList.get(bitsetList.size() - 1) : null;
			if (current == null || ttype > (current.shift + wordSize-1)) {
				current = new Bitset();
				if (useZeroOffset && ttype >= 0 && ttype < wordSize-1) {
					current.shift = 0;
				}
				else {
					current.shift = ttype;
				}

				bitsetList.add(current);
			}

			current.ttypes.add(factory.getGenerator().getTarget().getTokenTypeAsTargetLabel(factory.getGrammar(), ttype));
		}

		return bitsetList.toArray(new Bitset[bitsetList.size()]);
	}

	public static final class Bitset {
		public int shift;
		public final List<String> ttypes = new ArrayList<String>();
	}
}


text:
/* @Author: Gkxd
 *
 * Rotates a GameObject to a list of specified Euler angles
 *
 * */
using UnityEngine;
using System.Collections;

namespace Rhythmify {
    public class RotateToEulers : _AbstractRhythmObject {
        public Vector3[] eulerAngles;
        public int[] indices;
        public int offset;
        public bool local;
        public bool rigid;
        public bool spherical;

        private Rigidbody rigidBody;

        override protected void init() {
            if (rigid) {
                rigidBody = gameObject.GetComponent<Rigidbody>();
                if (rigidBody == null) {
                    Debug.LogError("The GameObject " + gameObject + " has no RigidBody component attached!");
                    Debug.Break();
                }
            }
        }

        override protected void rhythmUpdate(int beat) {
            int size = eulerAngles.Length;

            if (size <= 1) {
                return;
            }

            int idx = beat + offset;

            Quaternion startRot;
            Quaternion endRot;

            if (indices.Length > 0) {
                int idxA = indices[idx % indices.Length];
                int idxB = indices[(idx + 1) % indices.Length];
                startRot = Quaternion.Euler(eulerAngles [idxA % size]);
                endRot = Quaternion.Euler(eulerAngles [idxB % size]);
            }
            else {
                startRot = Quaternion.Euler(eulerAngles [idx % size]);
                endRot = Quaternion.Euler(eulerAngles [(idx + 1) % size]);
            }

            StartCoroutine(rotate(startRot, endRot, secondsPerBeat));
        }

        private IEnumerator rotate(Quaternion startRot, Quaternion endRot, float duration) {
            float startTime = Time.time;

            if (spherical) {
                if (rigid && rigidBody != null) {
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        rigidBody.MoveRotation(Quaternion.Slerp(startRot, endRot, lerpPercent));
                        yield return null;
                    }
                }
                else if (local) {
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        transform.localRotation = Quaternion.Slerp(startRot, endRot, lerpPercent);
                        yield return null;
                    }
                }
                else{
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        transform.rotation = Quaternion.Slerp(startRot, endRot, lerpPercent);
                        yield return null;
                    }
                }
            }
            else {
                if (rigid && rigidBody != null) {
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        rigidBody.MoveRotation(Quaternion.Lerp(startRot, endRot, lerpPercent));
                        yield return null;
                    }
                }
                if (local) {
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        transform.localRotation = Quaternion.Lerp(startRot, endRot, lerpPercent);
                        yield return null;
                    }
                }
                else {
                    while (Time.time <= startTime + duration) {
                        float lerpPercent = Mathf.Clamp01((Time.time - startTime) / duration);
                        transform.rotation = Quaternion.Lerp(startRot, endRot, lerpPercent);
                        yield return null;
                    }
                }
            }
        }
    }
}


text:
package com.gemstone.gemfire.internal.cache;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.RegionService;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import com.gemstone.gemfire.cache.client.internal.BridgePoolImpl;
import com.gemstone.gemfire.cache.client.internal.LocatorDiscoveryCallback;
import com.gemstone.gemfire.cache.client.internal.PoolImpl;
import com.gemstone.gemfire.cache.client.internal.BridgePoolImpl.LBPolicy;
import com.gemstone.gemfire.cache.query.QueryService;
import com.gemstone.gemfire.cache.wan.GatewaySender;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.internal.admin.remote.DistributionLocatorId;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.pdx.internal.TypeRegistry;

/**
 * Implementation of PoolFactory.
 * @author darrel
 * @since 5.7
 */
public class PoolFactoryImpl implements PoolFactory {
  /**
   * Used internally to pass the attributes from this factory to
   * the real pool it is creating.
   */
  private PoolAttributes attributes = new PoolAttributes();

  /**
   * The cache that created this factory
   */
  private final PoolManagerImpl pm;

  public PoolFactoryImpl(PoolManagerImpl pm) {
    this.pm = pm;
  }

  public PoolFactory setFreeConnectionTimeout(int connectionTimeout) {
    if (connectionTimeout <= 0) {
      throw new IllegalArgumentException("connectionTimeout must be greater than zero");
    }
    this.attributes.connectionTimeout = connectionTimeout;
    return this;
  }

  public PoolFactory setLoadConditioningInterval(int connectionLifetime) {
    if (connectionLifetime < -1) {
      throw new IllegalArgumentException("connectionLifetime must be greater than or equal to -1");
    }
    this.attributes.connectionLifetime = connectionLifetime;
    return this;
  }

  public PoolFactory setSocketBufferSize(int bufferSize) {
    if (bufferSize <= 0) {
      throw new IllegalArgumentException("socketBufferSize must be greater than zero");
    }
    this.attributes.socketBufferSize = bufferSize;
    return this;
  }

  public PoolFactory setThreadLocalConnections(boolean threadLocalConnections) {
    this.attributes.threadLocalConnections = threadLocalConnections;
    return this;
  }

  public PoolFactory setIdleTimeout(long idleTimout) {
    if(idleTimout < -1) {
      throw new IllegalArgumentException("idleTimeout must be greater than or equal to -1");
    }
    this.attributes.idleTimeout = idleTimout;
    return this;
  }

  public PoolFactory setMaxConnections(int maxConnections) {
    if(maxConnections < this.attributes.minConnections && maxConnections != -1) {
      throw new IllegalArgumentException(
          "maxConnections must be greater than or equal to minConnections ("
              + attributes.minConnections + ")");
    }
    if(maxConnections <= 0 && maxConnections != -1) {
      throw new IllegalArgumentException(
          "maxConnections must be greater than 0, or set to -1 (no max)");
    }
    this.attributes.maxConnections = maxConnections;
    return this;
  }

  public PoolFactory setMinConnections(int minConnections) {
    if(minConnections > attributes.maxConnections && attributes.maxConnections != -1) {
      throw new IllegalArgumentException(
          "must be less than or equal to maxConnections (" + attributes.maxConnections + ")");
    }
    if(minConnections < 0) {
      throw new IllegalArgumentException(
          "must be greater than or equal to 0");
    }
    this.attributes.minConnections=minConnections;
    return this;
  }

  public PoolFactory setPingInterval(long pingInterval) {
    if(pingInterval <= 0) {
      throw new IllegalArgumentException("pingInterval must be greater than zero");
    }
    this.attributes.pingInterval=pingInterval;
    return this;
  }

  public PoolFactory setStatisticInterval(int statisticInterval) {
    if(statisticInterval < -1) {
      throw new IllegalArgumentException("statisticInterval must be greater than or equal to -1");
    }
    this.attributes.statisticInterval = statisticInterval;
    return this;
  }

  public PoolFactory setRetryAttempts(int retryAttempts) {
    if(retryAttempts < -1) {
      throw new IllegalArgumentException("retryAttempts must be greater than or equal to -1");
    }
    this.attributes.retryAttempts=retryAttempts;
    return this;
  }

  public PoolFactory setReadTimeout(int timeout) {
    if (timeout < 0) {
      throw new IllegalArgumentException("readTimeout must be greater than or equal to zero");
    }
    this.attributes.readTimeout = timeout;
    return this;
  }

  public PoolFactory setServerGroup(String group) {
    if (group == null) {
      group = DEFAULT_SERVER_GROUP;
    }
    this.attributes.serverGroup = group;
    return this;
  }

  public PoolFactory setSubscriptionEnabled(boolean enabled) {
    this.attributes.queueEnabled = enabled;
    return this;
  }

  public PoolFactory setPRSingleHopEnabled(boolean enabled) {
    this.attributes.prSingleHopEnabled = enabled;
    return this;
  }

  public PoolFactory setMultiuserAuthentication(boolean enabled) {
    this.attributes.multiuserSecureModeEnabled = enabled;
    return this;
  }

  public PoolFactory setStartDisabled(boolean disable) {
    this.attributes.startDisabled = disable;
    return this;
  }

  public PoolFactory setLocatorDiscoveryCallback(LocatorDiscoveryCallback callback) {
    this.attributes.locatorCallback = callback;
    return this;
  }

  public PoolFactory setSubscriptionRedundancy(int redundancyLevel) {
    if (redundancyLevel < -1) {
      throw new IllegalArgumentException("queueRedundancyLevel must be greater than or equal to -1");
    }
    this.attributes.queueRedundancyLevel = redundancyLevel;
    return this;
  }

  public PoolFactory setSubscriptionMessageTrackingTimeout(int messageTrackingTimeout) {
    if (messageTrackingTimeout <= 0) {
      throw new IllegalArgumentException("queueMessageTrackingTimeout must be greater than zero");
    }
    this.attributes.queueMessageTrackingTimeout = messageTrackingTimeout;
    return this;
  }

  private PoolFactory add(String host, int port, List l) {
    if (port == 0) {
      throw new IllegalArgumentException("port must be greater than 0 but was " + port);
      // the rest of the port validation is done by InetSocketAddress
    }
    try {
      InetAddress hostAddr = InetAddress.getByName(host);
      InetSocketAddress sockAddr = new InetSocketAddress(hostAddr, port);
      l.add(sockAddr);
    } catch (UnknownHostException cause) {
//      IllegalArgumentException ex = new IllegalArgumentException("Unknown host " + host);
//      ex.initCause(cause);
//      throw ex;
      // Fix for #45348
      GemFireCacheImpl cache =GemFireCacheImpl.getInstance();
      if (cache != null && cache.getLoggerI18n() != null) {
        cache.getLoggerI18n().severe(LocalizedStrings.PoolFactoryImpl_HOSTNAME_UNKNOWN, host);
      }
      InetSocketAddress sockAddr = new InetSocketAddress(host, port);
      l.add(sockAddr);
    }
    return this;
  }

  public PoolFactory setSubscriptionAckInterval(int ackInterval) {
    if(ackInterval <= 0) {
      throw new IllegalArgumentException("ackInterval must be greater than 0");
    }
    this.attributes.queueAckInterval = ackInterval;

    return this;
  }

  public PoolFactory addLocator(String host, int port) {
    if (this.attributes.servers.size() > 0) {
      throw new IllegalStateException("A server has already been added. You can only add locators or servers; not both.");
    }
    return add(host, port, this.attributes.locators);
  }
  public PoolFactory addServer(String host, int port) {
    if (this.attributes.locators.size() > 0) {
      throw new IllegalStateException("A locator has already been added. You can only add locators or servers; not both.");
    }
    return add(host, port, this.attributes.servers);
  }

  public PoolFactory reset() {
    // preserve the startDisabled across resets
    boolean sd = this.attributes.startDisabled;
    this.attributes = new PoolAttributes();
    this.attributes.startDisabled = sd;
    return this;
  }

  /**
   * Initializes the state of this factory for the given pool's state.
   */
  public void init(Pool cp) {
    setFreeConnectionTimeout(cp.getFreeConnectionTimeout());
    setLoadConditioningInterval(cp.getLoadConditioningInterval());
    setSocketBufferSize(cp.getSocketBufferSize());
    setReadTimeout(cp.getReadTimeout());
    setMinConnections(cp.getMinConnections());
    setMaxConnections(cp.getMaxConnections());
    setRetryAttempts(cp.getRetryAttempts());
    setIdleTimeout(cp.getIdleTimeout());
    setPingInterval(cp.getPingInterval());
    setStatisticInterval(cp.getStatisticInterval());
    setThreadLocalConnections(cp.getThreadLocalConnections());
    setSubscriptionEnabled(cp.getSubscriptionEnabled());
    setPRSingleHopEnabled(cp.getPRSingleHopEnabled());
    setSubscriptionRedundancy(cp.getSubscriptionRedundancy());
    setSubscriptionMessageTrackingTimeout(cp.getSubscriptionMessageTrackingTimeout());
    setSubscriptionAckInterval(cp.getSubscriptionAckInterval());
    setServerGroup(cp.getServerGroup());
    setMultiuserAuthentication(cp.getMultiuserAuthentication());
    this.attributes.locators.addAll(cp.getLocators());
    this.attributes.servers.addAll(cp.getServers());
  }

  public void init(Properties properties, boolean usedByBridgeWriter,
      boolean usedByGateway, GatewaySender sender) {
    this.attributes.setGatewaySender(sender);
    init(properties, usedByBridgeWriter, usedByGateway);
  }
  /**
   * Used to create a pool given the old Bridge properties
   * @param properties from a BridgeWriter or BridgeLoader
   * @param usedByBridgeWriter true  if props from BridgeWriter;
   *                           false if props from BridgeLoader.
   * *param usedByGateway true if props from GatewayImpl.
   * @since 5.7
   */
  public void init(Properties properties, boolean usedByBridgeWriter,
                   boolean usedByGateway) {
    this.attributes.setBridge(usedByBridgeWriter || !usedByGateway);
    this.attributes.setBridgeWriter(usedByBridgeWriter);
    this.attributes.setGateway(usedByGateway);
    setIdleTimeout(-1); // never time out
    setLoadConditioningInterval(-1); // never time out
    setMaxConnections(-1);
    int endpointCount = 0;
    boolean useLocators = false;
    boolean useEndPoints = false;
    IllegalArgumentException exception = null;
    if (properties.containsKey(DistributionConfig.LOCATORS_NAME)) {
      String locatorObject = properties
          .getProperty(DistributionConfig.LOCATORS_NAME);
      if (locatorObject != null && !locatorObject.equals("")) {
        StringTokenizer locatorsOnThisVM = new StringTokenizer(locatorObject, ",");
        while (locatorsOnThisVM.hasMoreTokens()) {
          String localLocator = locatorsOnThisVM.nextToken();
          DistributionLocatorId locatorId = new DistributionLocatorId(
              localLocator);
          addLocator(locatorId.getHost().getHostName(), locatorId.getPort());
        }
        useLocators = true;
      }
    }
    if (!useLocators && properties.containsKey("endpoints")) {
      useEndPoints = true;
      String pv = properties.getProperty("endpoints");
      StringTokenizer tokenizer = new StringTokenizer(pv, ",");
      while (tokenizer.hasMoreTokens()) {
        String serverdetail = tokenizer.nextToken();
        int cIndex = serverdetail.indexOf("=");
        // note we throw the name away
//         String name = serverdetail.substring(0, cIndex);
//         if (name != null) {
//           name = name.trim();
//         }
        String remainder = serverdetail.substring(cIndex + 1);
        cIndex = remainder.lastIndexOf(":");
        String host = remainder.substring(0, cIndex);
        if (host != null) {
          host = host.trim();
        }
        String port = remainder.substring(cIndex + 1);
        if (port != null) {
          port = port.trim();
        }
        try {
          addServer(host, Integer.parseInt(port));
          endpointCount++;
        } catch (IllegalArgumentException e) {
          if (!(e.getCause() instanceof UnknownHostException)) {
            throw e;
          } else {
            exception = e;
          }
        }
      }
      if ((endpointCount == 0) && (exception != null)) {
        IllegalArgumentException ex = new IllegalArgumentException("Couldn't find any Endpoint. " + exception.getMessage());
        ex.initCause(exception.getCause());
        throw ex;
      }
    }
    if(!useLocators && !useEndPoints) {
      throw new IllegalArgumentException(
          "Property 'locators ' or 'endpoints' must be specified");
    }
    // @todo grid: handshakeTimeout ignored
    {
      // @todo grid: roundRobin and appAssisted ignored
      LBPolicy policy = new LBPolicy(properties.getProperty("LBPolicy",
          LBPolicy.STICKY_PROPERTY_NAME));
      setThreadLocalConnections(policy.isSticky());
    }

    if (properties.containsKey("retryAttempts")) {
      String strRetryAttempts = properties.getProperty("retryAttempts");
      setRetryAttempts(Integer.parseInt(strRetryAttempts));
    }
    if (properties.containsKey("retryInterval")) {
      String strRetryAttempts = properties.getProperty("retryInterval");
      setPingInterval(Integer.parseInt(strRetryAttempts));
    }
    if (properties.containsKey("establishCallbackConnection")) {
      String str = properties.getProperty("establishCallbackConnection");
      setSubscriptionEnabled(Boolean.valueOf(str).booleanValue());
    }
    if (properties.containsKey("enablePRSingleHop")) {
      String str = properties.getProperty("enablePRSingleHop");
      setPRSingleHopEnabled(Boolean.valueOf(str).booleanValue());
    }
    if (properties.containsKey("connectionsPerServer")) {
      String str = properties.getProperty("connectionsPerServer");
      setMinConnections(Integer.parseInt(str)*endpointCount);
    } else {
      setMinConnections(1*endpointCount);
    }
    if (properties.containsKey("redundancyLevel")) {
      String str = properties.getProperty("redundancyLevel");
      setSubscriptionRedundancy(Integer.parseInt(str));
    }
    if (properties.containsKey("readTimeout")) {
      String strReadTimeout = properties.getProperty("readTimeout");
      setReadTimeout(Integer.parseInt(strReadTimeout));
    }
    if (properties.containsKey("socketBufferSize")) {
      String strSocketBufferSize = properties.getProperty("socketBufferSize");
      setSocketBufferSize(Integer.parseInt(strSocketBufferSize));
    }
    if (properties.containsKey("messageTrackingTimeout")) {
      String pv = properties.getProperty("messageTrackingTimeout");
      setSubscriptionMessageTrackingTimeout(Integer.parseInt(pv));
    }
    if(properties.containsKey("clientAckInterval") ) {
      String pv = properties.getProperty("clientAckInterval");
      setSubscriptionAckInterval(Integer.parseInt(pv));
    }
    if(usedByGateway && exception!= null) {
      throw exception;
    }
  }

  /**
   * Create a new Pool for connecting a client to a set of GemFire Cache Servers.
   * using this factory's settings for attributes.
   *
   * @param name the name of the connection pool, used when connecting regions to it
   * @throws IllegalStateException if the connection pool name already exists
   * @throws IllegalStateException if this factory does not have any locators or servers
   * @return the newly created connection pool.
   * @since 5.7
   */
  public Pool create(String name) throws CacheException {
    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
    if(cache != null) {
      TypeRegistry registry = cache.getPdxRegistry();
      if(registry != null && !attributes.isGateway()) {
        registry.creatingPool();
      }
    }
    if (this.attributes.isBridge()) {
      return new BridgePoolImpl(this.pm, name, this.attributes);
    } else {
      return PoolImpl.create(this.pm, name, this.attributes);
    }
  }

  /**
   * Needed by test framework.
   */
  public PoolAttributes getPoolAttributes() {
    return this.attributes;
  }

  /**
   * Not a true pool just the attributes.
   * Serialization is used by unit tests
   */
  public static class PoolAttributes implements Pool, DataSerializable {

    private static final long serialVersionUID = 1L; // for findbugs

    public int connectionTimeout = DEFAULT_FREE_CONNECTION_TIMEOUT;
    public int connectionLifetime = DEFAULT_LOAD_CONDITIONING_INTERVAL;
    public int socketBufferSize = DEFAULT_SOCKET_BUFFER_SIZE;
    public boolean threadLocalConnections = DEFAULT_THREAD_LOCAL_CONNECTIONS;
    public int readTimeout = DEFAULT_READ_TIMEOUT;
    public int minConnections = DEFAULT_MIN_CONNECTIONS;
    public int maxConnections = DEFAULT_MAX_CONNECTIONS;
    public long idleTimeout = DEFAULT_IDLE_TIMEOUT;
    public int retryAttempts = DEFAULT_RETRY_ATTEMPTS;
    public long pingInterval = DEFAULT_PING_INTERVAL;
    public int statisticInterval = DEFAULT_STATISTIC_INTERVAL;
    public boolean queueEnabled = DEFAULT_SUBSCRIPTION_ENABLED;
    public boolean prSingleHopEnabled = DEFAULT_PR_SINGLE_HOP_ENABLED;
    public int queueRedundancyLevel = DEFAULT_SUBSCRIPTION_REDUNDANCY;
    public int queueMessageTrackingTimeout = DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT;
    public int queueAckInterval = DEFAULT_SUBSCRIPTION_ACK_INTERVAL;
    public String serverGroup = DEFAULT_SERVER_GROUP;
    public boolean multiuserSecureModeEnabled = DEFAULT_MULTIUSER_AUTHENTICATION;
    public ArrayList/*<InetSocketAddress>*/ locators = new ArrayList();
    public ArrayList/*<InetSocketAddress>*/ servers = new ArrayList();
    public transient boolean startDisabled = false; // only used by junit tests
    public transient LocatorDiscoveryCallback locatorCallback = null; //only used by tests
    public GatewaySender gatewaySender = null;
    /**
     * True if this factory needs to produce a pool for use by BridgeWriter
     * or BridgeLoader.
     */
    public boolean bridge = false;
    /**
     * True if bridge is true and the pool is used by a BridgeWriter.
     * False if bridge is true and the pool is used by a BridgeLoader.
     * Ignore this attribute if bridge is false.
     */
    public boolean bridgeWriter = false;
    /**
     * True if bridge is true and the pool is used by a Gateway.
     * Ignore this attribute if bridge is false.
     */
    public boolean gateway = false;

    public int getFreeConnectionTimeout() {
      return this.connectionTimeout;
    }
    public int getLoadConditioningInterval() {
      return this.connectionLifetime;
    }
    public int getSocketBufferSize() {
      return this.socketBufferSize;
    }
    public int getMinConnections() {
      return minConnections;
    }
    public int getMaxConnections() {
      return maxConnections;
    }
    public long getIdleTimeout() {
      return idleTimeout;
    }
    public int getRetryAttempts() {
      return retryAttempts;
    }
    public long getPingInterval() {
      return pingInterval;
    }
    public int getStatisticInterval() {
      return statisticInterval;
    }
    public boolean getThreadLocalConnections() {
      return this.threadLocalConnections;
    }
    public int getReadTimeout() {
      return this.readTimeout;
    }
    public boolean getSubscriptionEnabled() {
      return this.queueEnabled;
    }
    public boolean getPRSingleHopEnabled() {
      return this.prSingleHopEnabled;
    }
    public int getSubscriptionRedundancy() {
      return this.queueRedundancyLevel;
    }
    public int getSubscriptionMessageTrackingTimeout() {
      return this.queueMessageTrackingTimeout;
    }
    public int getSubscriptionAckInterval() {
      return queueAckInterval;
    }
    public String getServerGroup() {
      return this.serverGroup;
    }
    public boolean isBridge() {
      return this.bridge;
    }
    public void setBridge(boolean v) {
      this.bridge = v;
    }
    public boolean isBridgeWriter() {
      return this.bridgeWriter;
    }
    public void setBridgeWriter(boolean v) {
      this.bridgeWriter = v;
    }
    public boolean isGateway() {
      return this.gateway;
    }
    public void setGateway(boolean v) {
      this.gateway = v;
    }
    public void setGatewaySender(GatewaySender sender) {
      this.gatewaySender = sender;
    }
    public GatewaySender getGatewaySender(){
      return this.gatewaySender;
    }
    public boolean getMultiuserAuthentication() {
      return this.multiuserSecureModeEnabled;
    }
    public void setMultiuserSecureModeEnabled(boolean v) {
     this.multiuserSecureModeEnabled = v;
    }
    public List/*<InetSocketAddress>*/ getLocators() {
      if (this.locators.size() == 0 && this.servers.size() == 0) {
        throw new IllegalStateException("At least one locator or server must be added before a connection pool can be created.");
      }
      // needs to return a copy.
      return Collections.unmodifiableList(new ArrayList(this.locators));
    }
    public List/*<InetSocketAddress>*/ getServers() {
      if (this.locators.size() == 0 && this.servers.size() == 0) {
        throw new IllegalStateException("At least one locator or server must be added before a connection pool can be created.");
      }
      // needs to return a copy.
      return Collections.unmodifiableList(new ArrayList(this.servers));
    }

    public String getName() {
      throw new UnsupportedOperationException();
    }

    public void destroy() throws CacheException {
      throw new UnsupportedOperationException();
    }

    public void destroy(boolean keepAlive) throws CacheException {
      throw new UnsupportedOperationException();
    }

    public boolean isDestroyed() {
      throw new UnsupportedOperationException();
    }

    public void releaseThreadLocalConnection() {
      throw new UnsupportedOperationException();
    }

    public QueryService getQueryService() {
      throw new UnsupportedOperationException();
    }
    public RegionService createAuthenticatedCacheView(Properties properties) {
      throw new UnsupportedOperationException();
    }

    public void toData(DataOutput out) throws IOException {
      DataSerializer.writePrimitiveInt(this.connectionTimeout, out);
      DataSerializer.writePrimitiveInt(this.connectionLifetime, out);
      DataSerializer.writePrimitiveInt(this.socketBufferSize, out);
      DataSerializer.writePrimitiveInt(this.readTimeout, out);
      DataSerializer.writePrimitiveInt(this.minConnections, out);
      DataSerializer.writePrimitiveInt(this.maxConnections, out);
      DataSerializer.writePrimitiveInt(this.retryAttempts, out);
      DataSerializer.writePrimitiveLong(this.idleTimeout, out);
      DataSerializer.writePrimitiveLong(this.pingInterval, out);
      DataSerializer.writePrimitiveInt(this.queueRedundancyLevel, out);
      DataSerializer.writePrimitiveInt(this.queueMessageTrackingTimeout, out);
      DataSerializer.writePrimitiveBoolean(this.threadLocalConnections, out);
      DataSerializer.writePrimitiveBoolean(this.queueEnabled, out);
      DataSerializer.writeString(this.serverGroup, out);
      DataSerializer.writeArrayList(this.locators, out);
      DataSerializer.writeArrayList(this.servers, out);
      DataSerializer.writePrimitiveBoolean(this.bridge, out);
      DataSerializer.writePrimitiveInt(this.statisticInterval, out);
      DataSerializer.writePrimitiveBoolean(this.multiuserSecureModeEnabled,out);
    }
    public void fromData(DataInput in)
      throws IOException, ClassNotFoundException
    {
      this.connectionTimeout = DataSerializer.readPrimitiveInt(in);
      this.connectionLifetime = DataSerializer.readPrimitiveInt(in);
      this.socketBufferSize = DataSerializer.readPrimitiveInt(in);
      this.readTimeout = DataSerializer.readPrimitiveInt(in);
      this.minConnections= DataSerializer.readPrimitiveInt(in);
      this.maxConnections= DataSerializer.readPrimitiveInt(in);
      this.retryAttempts= DataSerializer.readPrimitiveInt(in);
      this.idleTimeout= DataSerializer.readPrimitiveLong(in);
      this.pingInterval= DataSerializer.readPrimitiveLong(in);
      this.queueRedundancyLevel = DataSerializer.readPrimitiveInt(in);
      this.queueMessageTrackingTimeout = DataSerializer.readPrimitiveInt(in);
      this.threadLocalConnections = DataSerializer.readPrimitiveBoolean(in);
      this.queueEnabled = DataSerializer.readPrimitiveBoolean(in);
      this.serverGroup = DataSerializer.readString(in);
      this.locators = DataSerializer.readArrayList(in);
      this.servers = DataSerializer.readArrayList(in);
      this.bridge = DataSerializer.readPrimitiveBoolean(in);
      this.statisticInterval= DataSerializer.readPrimitiveInt(in);
      this.multiuserSecureModeEnabled = DataSerializer.readPrimitiveBoolean(in);
    }
  }
}


text:
package org.ovirt.engine.core.bll.storage;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.queries.GetExistingStorageDomainListParameters;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.HSMGetStorageDomainInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.HSMGetStorageDomainsListVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Logged;
import org.ovirt.engine.core.utils.log.Logged.LogLevel;

@Logged(executionLevel = LogLevel.INFO)
public class GetExistingStorageDomainListQuery<P extends GetExistingStorageDomainListParameters>
        extends QueriesCommandBase<P> {
    public GetExistingStorageDomainListQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        ArrayList<StorageDomain> returnValue = new ArrayList<>();
        VDSReturnValue vdsReturnValue = Backend
                .getInstance()
                .getResourceManager()
                .RunVdsCommand(
                        VDSCommandType.HSMGetStorageDomainsList,
                        new HSMGetStorageDomainsListVDSCommandParameters(getParameters()
                                .getId(), Guid.Empty, null, getParameters()
                                .getStorageDomainType(), getParameters().getPath()));
        if (vdsReturnValue.getSucceeded()) {
            ArrayList<Guid> guidsFromIrs = (ArrayList<Guid>) vdsReturnValue.getReturnValue();
            HashSet<Guid> guidsFromDb = new HashSet<>();
            if (guidsFromIrs.size() > 0) {
                List<StorageDomain> domainsInDb = DbFacade.getInstance().getStorageDomainDao().getAll();
                for (StorageDomain domain : domainsInDb) {
                    guidsFromDb.add(domain.getId());
                }
                for (Guid domainId : guidsFromIrs) {
                    if (!guidsFromDb.contains(domainId)) {
                        Pair<StorageDomainStatic, Guid> domainFromIrs =
                                (Pair<StorageDomainStatic, Guid>) Backend
                                        .getInstance()
                                        .getResourceManager()
                                        .RunVdsCommand(
                                                VDSCommandType.HSMGetStorageDomainInfo,
                                                new HSMGetStorageDomainInfoVDSCommandParameters(
                                                        getParameters().getId(), domainId))
                                        .getReturnValue();
                        StorageDomain domain = new StorageDomain();
                        domain.setStorageStaticData(domainFromIrs.getFirst());
                        domain.setStoragePoolId(domainFromIrs.getSecond());
                        if (getParameters().getStorageFormatType() == null
                                || getParameters().getStorageFormatType() == domain.getStorageFormat()) {
                            if (getParameters().getStorageType() != null
                                    && domain.getStorageType().getValue() != getParameters().getStorageType().getValue()) {
                                log.warn("The storage type of domain {} has been changed from {} to {}",
                                        domain.getStorageName(),
                                        domain.getStorageType().toString(),
                                        getParameters().getStorageType().toString());
                                domain.setStorageType(getParameters().getStorageType());
                            }
                            returnValue.add(domain);
                        }
                    }
                }
            }
            getQueryReturnValue().setReturnValue(returnValue);
        }
    }
}


text:
/*
 * This file defines classes for doing temporal layers with VP8.
 */
#ifndef MODULES_VIDEO_CODING_CODECS_VP8_DEFAULT_TEMPORAL_LAYERS_H_
#define MODULES_VIDEO_CODING_CODECS_VP8_DEFAULT_TEMPORAL_LAYERS_H_

#include <stddef.h>
#include <stdint.h>

#include <limits>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>

#include "absl/types/optional.h"
#include "api/video_codecs/vp8_frame_config.h"
#include "api/video_codecs/vp8_temporal_layers.h"
#include "modules/video_coding/codecs/vp8/include/temporal_layers_checker.h"
#include "modules/video_coding/include/video_codec_interface.h"

namespace webrtc {

class DefaultTemporalLayers final : public Vp8FrameBufferController {
 public:
  explicit DefaultTemporalLayers(int number_of_temporal_layers);
  ~DefaultTemporalLayers() override;

  void SetQpLimits(size_t stream_index, int min_qp, int max_qp) override;

  size_t StreamCount() const override;

  bool SupportsEncoderFrameDropping(size_t stream_index) const override;

  // Returns the recommended VP8 encode flags needed. May refresh the decoder
  // and/or update the reference buffers.
  Vp8FrameConfig NextFrameConfig(size_t stream_index,
                                 uint32_t timestamp) override;

  // New target bitrate, per temporal layer.
  void OnRatesUpdated(size_t stream_index,
                      const std::vector<uint32_t>& bitrates_bps,
                      int framerate_fps) override;

  Vp8EncoderConfig UpdateConfiguration(size_t stream_index) override;

  void OnEncodeDone(size_t stream_index,
                    uint32_t rtp_timestamp,
                    size_t size_bytes,
                    bool is_keyframe,
                    int qp,
                    CodecSpecificInfo* info) override;

  void OnFrameDropped(size_t stream_index, uint32_t rtp_timestamp) override;

  void OnPacketLossRateUpdate(float packet_loss_rate) override;

  void OnRttUpdate(int64_t rtt_ms) override;

  void OnLossNotification(
      const VideoEncoder::LossNotification& loss_notification) override;

 private:
  struct DependencyInfo {
    DependencyInfo() = default;
    DependencyInfo(absl::string_view indication_symbols,
                   Vp8FrameConfig frame_config)
        : decode_target_indications(
              GenericFrameInfo::DecodeTargetInfo(indication_symbols)),
          frame_config(frame_config) {}

    absl::InlinedVector<DecodeTargetIndication, 10> decode_target_indications;
    Vp8FrameConfig frame_config;
  };

  static std::vector<DependencyInfo> GetDependencyInfo(size_t num_layers);
  bool IsSyncFrame(const Vp8FrameConfig& config) const;
  void ValidateReferences(Vp8FrameConfig::BufferFlags* flags,
                          Vp8FrameConfig::Vp8BufferReference ref) const;
  void UpdateSearchOrder(Vp8FrameConfig* config);

  const size_t num_layers_;
  const std::vector<unsigned int> temporal_ids_;
  const std::vector<DependencyInfo> temporal_pattern_;
  // Set of buffers that are never updated except by keyframes.
  std::set<Vp8FrameConfig::Vp8BufferReference> kf_buffers_;
  FrameDependencyStructure GetTemplateStructure(int num_layers) const;

  uint8_t pattern_idx_;
  // Updated cumulative bitrates, per temporal layer.
  absl::optional<std::vector<uint32_t>> new_bitrates_bps_;

  struct PendingFrame {
    PendingFrame();
    PendingFrame(bool expired,
                 uint8_t updated_buffers_mask,
                 const DependencyInfo& dependency_info);
    // Flag indicating if this frame has expired, ie it belongs to a previous
    // iteration of the temporal pattern.
    bool expired = false;
    // Bitmask of Vp8BufferReference flags, indicating which buffers this frame
    // updates.
    uint8_t updated_buffer_mask = 0;
    // The frame config returned by NextFrameConfig() for this frame.
    DependencyInfo dependency_info;
  };
  // Map from rtp timestamp to pending frame status. Reset on pattern loop.
  std::map<uint32_t, PendingFrame> pending_frames_;

  // One counter per Vp8BufferReference, indicating number of frames since last
  // refresh. For non-base-layer frames (ie golden, altref buffers), this is
  // reset when the pattern loops.
  std::map<Vp8FrameConfig::Vp8BufferReference, size_t>
      frames_since_buffer_refresh_;

  // Optional utility used to verify reference validity.
  std::unique_ptr<TemporalLayersChecker> checker_;
};

class DefaultTemporalLayersChecker : public TemporalLayersChecker {
 public:
  explicit DefaultTemporalLayersChecker(int number_of_temporal_layers);
  ~DefaultTemporalLayersChecker() override;

  bool CheckTemporalConfig(bool frame_is_keyframe,
                           const Vp8FrameConfig& frame_config) override;

 private:
  struct BufferState {
    BufferState()
        : is_updated_this_cycle(false), is_keyframe(true), pattern_idx(0) {}

    bool is_updated_this_cycle;
    bool is_keyframe;
    uint8_t pattern_idx;
  };
  const size_t num_layers_;
  std::vector<unsigned int> temporal_ids_;
  const std::vector<std::set<uint8_t>> temporal_dependencies_;
  BufferState last_;
  BufferState arf_;
  BufferState golden_;
  uint8_t pattern_idx_;
};

}  // namespace webrtc
#endif  // MODULES_VIDEO_CODING_CODECS_VP8_DEFAULT_TEMPORAL_LAYERS_H_


text:
#include <EnginePCH.hpp>

#include <Audio/SoundListenerComponent.hpp>

using namespace Poly;

RTTI_DEFINE_COMPONENT(::Poly::SoundListenerComponent)

SoundListenerComponent::SoundListenerComponent(SoundWorldComponent* /*worldComponent*/)
{
}

SoundListenerComponent::~SoundListenerComponent()
{
}


text:
namespace omnetpp {

// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument

// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
    int n = v.size();
    doParsimPacking(buffer, n);
    for (int i = 0; i < n; i++)
        doParsimPacking(buffer, v[i]);
}

template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
    int n;
    doParsimUnpacking(buffer, n);
    v.resize(n);
    for (int i = 0; i < n; i++)
        doParsimUnpacking(buffer, v[i]);
}

// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
    doParsimPacking(buffer, (int)l.size());
    for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
        doParsimPacking(buffer, (T&)*it);
}

template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
    int n;
    doParsimUnpacking(buffer, n);
    for (int i=0; i<n; i++) {
        l.push_back(T());
        doParsimUnpacking(buffer, l.back());
    }
}

// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
    doParsimPacking(buffer, (int)s.size());
    for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
        doParsimPacking(buffer, *it);
}

template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
    int n;
    doParsimUnpacking(buffer, n);
    for (int i=0; i<n; i++) {
        T x;
        doParsimUnpacking(buffer, x);
        s.insert(x);
    }
}

// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
    doParsimPacking(buffer, (int)m.size());
    for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
        doParsimPacking(buffer, it->first);
        doParsimPacking(buffer, it->second);
    }
}

template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
    int n;
    doParsimUnpacking(buffer, n);
    for (int i=0; i<n; i++) {
        K k; V v;
        doParsimUnpacking(buffer, k);
        doParsimUnpacking(buffer, v);
        m[k] = v;
    }
}

// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
    for (int i = 0; i < n; i++)
        doParsimPacking(b, t[i]);
}

template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
    for (int i = 0; i < n; i++)
        doParsimUnpacking(b, t[i]);
}

// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
    throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}

template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
    throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}

}  // namespace omnetpp

namespace inet {
namespace bgp {

// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);

// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}

// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
    out.put('{');
    for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
    {
        if (it != vec.begin()) {
            out.put(','); out.put(' ');
        }
        out << *it;
    }
    out.put('}');

    char buf[32];
    sprintf(buf, " (size=%u)", (unsigned int)vec.size());
    out.write(buf, strlen(buf));
    return out;
}

Register_Class(BGPKeepAliveMessage)

BGPKeepAliveMessage::BGPKeepAliveMessage(const char *name, short kind) : ::inet::bgp::BGPHeader(name,kind)
{
    this->setType(BGP_KEEPALIVE);
}

BGPKeepAliveMessage::BGPKeepAliveMessage(const BGPKeepAliveMessage& other) : ::inet::bgp::BGPHeader(other)
{
    copy(other);
}

BGPKeepAliveMessage::~BGPKeepAliveMessage()
{
}

BGPKeepAliveMessage& BGPKeepAliveMessage::operator=(const BGPKeepAliveMessage& other)
{
    if (this==&other) return *this;
    ::inet::bgp::BGPHeader::operator=(other);
    copy(other);
    return *this;
}

void BGPKeepAliveMessage::copy(const BGPKeepAliveMessage& other)
{
}

void BGPKeepAliveMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
    ::inet::bgp::BGPHeader::parsimPack(b);
}

void BGPKeepAliveMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
    ::inet::bgp::BGPHeader::parsimUnpack(b);
}

class BGPKeepAliveMessageDescriptor : public omnetpp::cClassDescriptor
{
  private:
    mutable const char **propertynames;
  public:
    BGPKeepAliveMessageDescriptor();
    virtual ~BGPKeepAliveMessageDescriptor();

    virtual bool doesSupport(omnetpp::cObject *obj) const override;
    virtual const char **getPropertyNames() const override;
    virtual const char *getProperty(const char *propertyname) const override;
    virtual int getFieldCount() const override;
    virtual const char *getFieldName(int field) const override;
    virtual int findField(const char *fieldName) const override;
    virtual unsigned int getFieldTypeFlags(int field) const override;
    virtual const char *getFieldTypeString(int field) const override;
    virtual const char **getFieldPropertyNames(int field) const override;
    virtual const char *getFieldProperty(int field, const char *propertyname) const override;
    virtual int getFieldArraySize(void *object, int field) const override;

    virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
    virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
    virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;

    virtual const char *getFieldStructName(int field) const override;
    virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};

Register_ClassDescriptor(BGPKeepAliveMessageDescriptor)

BGPKeepAliveMessageDescriptor::BGPKeepAliveMessageDescriptor() : omnetpp::cClassDescriptor("inet::bgp::BGPKeepAliveMessage", "inet::bgp::BGPHeader")
{
    propertynames = nullptr;
}

BGPKeepAliveMessageDescriptor::~BGPKeepAliveMessageDescriptor()
{
    delete[] propertynames;
}

bool BGPKeepAliveMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
    return dynamic_cast<BGPKeepAliveMessage *>(obj)!=nullptr;
}

const char **BGPKeepAliveMessageDescriptor::getPropertyNames() const
{
    if (!propertynames) {
        static const char *names[] = {  nullptr };
        omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
        const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
        propertynames = mergeLists(basenames, names);
    }
    return propertynames;
}

const char *BGPKeepAliveMessageDescriptor::getProperty(const char *propertyname) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}

int BGPKeepAliveMessageDescriptor::getFieldCount() const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    return basedesc ? 0+basedesc->getFieldCount() : 0;
}

unsigned int BGPKeepAliveMessageDescriptor::getFieldTypeFlags(int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldTypeFlags(field);
        field -= basedesc->getFieldCount();
    }
    return 0;
}

const char *BGPKeepAliveMessageDescriptor::getFieldName(int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldName(field);
        field -= basedesc->getFieldCount();
    }
    return nullptr;
}

int BGPKeepAliveMessageDescriptor::findField(const char *fieldName) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    return basedesc ? basedesc->findField(fieldName) : -1;
}

const char *BGPKeepAliveMessageDescriptor::getFieldTypeString(int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldTypeString(field);
        field -= basedesc->getFieldCount();
    }
    return nullptr;
}

const char **BGPKeepAliveMessageDescriptor::getFieldPropertyNames(int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldPropertyNames(field);
        field -= basedesc->getFieldCount();
    }
    switch (field) {
        default: return nullptr;
    }
}

const char *BGPKeepAliveMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldProperty(field, propertyname);
        field -= basedesc->getFieldCount();
    }
    switch (field) {
        default: return nullptr;
    }
}

int BGPKeepAliveMessageDescriptor::getFieldArraySize(void *object, int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldArraySize(object, field);
        field -= basedesc->getFieldCount();
    }
    BGPKeepAliveMessage *pp = (BGPKeepAliveMessage *)object; (void)pp;
    switch (field) {
        default: return 0;
    }
}

const char *BGPKeepAliveMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldDynamicTypeString(object,field,i);
        field -= basedesc->getFieldCount();
    }
    BGPKeepAliveMessage *pp = (BGPKeepAliveMessage *)object; (void)pp;
    switch (field) {
        default: return nullptr;
    }
}

std::string BGPKeepAliveMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldValueAsString(object,field,i);
        field -= basedesc->getFieldCount();
    }
    BGPKeepAliveMessage *pp = (BGPKeepAliveMessage *)object; (void)pp;
    switch (field) {
        default: return "";
    }
}

bool BGPKeepAliveMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->setFieldValueAsString(object,field,i,value);
        field -= basedesc->getFieldCount();
    }
    BGPKeepAliveMessage *pp = (BGPKeepAliveMessage *)object; (void)pp;
    switch (field) {
        default: return false;
    }
}

const char *BGPKeepAliveMessageDescriptor::getFieldStructName(int field) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldStructName(field);
        field -= basedesc->getFieldCount();
    }
    return nullptr;
}

void *BGPKeepAliveMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
    omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
    if (basedesc) {
        if (field < basedesc->getFieldCount())
            return basedesc->getFieldStructValuePointer(object, field, i);
        field -= basedesc->getFieldCount();
    }
    BGPKeepAliveMessage *pp = (BGPKeepAliveMessage *)object; (void)pp;
    switch (field) {
        default: return nullptr;
    }
}

} // namespace bgp
} // namespace inet


text:
package de.schreibertobias.sprout.jobportal;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

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

import de.schreibertobias.sprout.base.Link;

public class Job implements Serializable {

    @SerializedName("title")
    @Expose
    private String mTitle;

    @SerializedName("sub_title")
    @Expose
    private String mSubTitle;

    @SerializedName("description")
    @Expose
    private String mDescription;

    @SerializedName("image_url")
    @Expose
    private String mImageUrl;

    @SerializedName("pdf_url")
    @Expose
    private String mPdfUrl;

    @SerializedName("links")
    @Expose
    private List<Link> mLinkList;

    public String getTitle() {
        return mTitle;
    }

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

    public String getDescription() {
        return mDescription;
    }

    public void setDescription(String description) {
        mDescription = description;
    }

    public String getImageUrl() {
        return mImageUrl;
    }

    public void setImageUrl(String imageUrl) {
        mImageUrl = imageUrl;
    }

    public String getPdfUrl() {
        return mPdfUrl;
    }

    public void setPdfUrl(String pdfUrl) {
        mPdfUrl = pdfUrl;
    }

    public List<Link> getLinkList() {
        return mLinkList;
    }

    public void setLinkList(List<Link> linkList) {
        mLinkList = linkList;
    }

    public String getSubTitle() {
        return mSubTitle;
    }

    public void setSubTitle(String subTitle) {
        mSubTitle = subTitle;
    }
}


text:
"""Module that groups code required to handle state restore for component."""
from __future__ import annotations

import asyncio
import logging
from typing import Any, Iterable

from homeassistant.const import (
    ATTR_MODE,
    SERVICE_TURN_OFF,
    SERVICE_TURN_ON,
    STATE_OFF,
    STATE_ON,
)
from homeassistant.core import Context, HomeAssistant, State

from .const import ATTR_HUMIDITY, DOMAIN, SERVICE_SET_HUMIDITY, SERVICE_SET_MODE

_LOGGER = logging.getLogger(__name__)

async def _async_reproduce_states(
    hass: HomeAssistant,
    state: State,
    *,
    context: Context | None = None,
    reproduce_options: dict[str, Any] | None = None,
) -> None:
    """Reproduce component states."""
    cur_state = hass.states.get(state.entity_id)

    if cur_state is None:
        _LOGGER.warning("Unable to find entity %s", state.entity_id)
        return

    async def call_service(service: str, keys: Iterable, data=None):
        """Call service with set of attributes given."""
        data = data or {}
        data["entity_id"] = state.entity_id
        for key in keys:
            if key in state.attributes:
                data[key] = state.attributes[key]

        await hass.services.async_call(
            DOMAIN, service, data, blocking=True, context=context
        )

    if state.state == STATE_OFF:
        # Ensure the device is off if it needs to be and exit
        if cur_state.state != STATE_OFF:
            await call_service(SERVICE_TURN_OFF, [])
        return

    if state.state != STATE_ON:
        # we can't know how to handle this
        _LOGGER.warning(
            "Invalid state specified for %s: %s", state.entity_id, state.state
        )
        return

    # First of all, turn on if needed, because the device might not
    # be able to set mode and humidity while being off
    if cur_state.state != STATE_ON:
        await call_service(SERVICE_TURN_ON, [])
        # refetch the state as turning on might allow us to see some more values
        cur_state = hass.states.get(state.entity_id)

    # Then set the mode before target humidity, because switching modes
    # may invalidate target humidity
    if ATTR_MODE in state.attributes and state.attributes[
        ATTR_MODE
    ] != cur_state.attributes.get(ATTR_MODE):
        await call_service(SERVICE_SET_MODE, [ATTR_MODE])

    # Next, restore target humidity for the current mode
    if ATTR_HUMIDITY in state.attributes and state.attributes[
        ATTR_HUMIDITY
    ] != cur_state.attributes.get(ATTR_HUMIDITY):
        await call_service(SERVICE_SET_HUMIDITY, [ATTR_HUMIDITY])

async def async_reproduce_states(
    hass: HomeAssistant,
    states: Iterable[State],
    *,
    context: Context | None = None,
    reproduce_options: dict[str, Any] | None = None,
) -> None:
    """Reproduce component states."""
    await asyncio.gather(
        *(
            _async_reproduce_states(
                hass, state, context=context, reproduce_options=reproduce_options
            )
            for state in states
        )
    )


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.medipi.devices.drivers.domain;

import java.util.ArrayList;

/**
 *
 * @author riro
 */
public class ContinuaData {

    private int dataSetCounter=-1;
    private String manufacturer;
    private String model;
    private final ArrayList<ContinuaMeasurement> measurement = new ArrayList();

    public static String removeUnwantedDecimalPoints(String s) {
        return s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
    }
    public ContinuaData() {
    }

    public ArrayList<ContinuaMeasurement> getMeasurements() {
        return measurement;
    }

    public void addMeasurement(ContinuaMeasurement measurement) {
        this.measurement.add(measurement);
    }

    public int getDataSetCounter() {
        return dataSetCounter;
    }
    public void addDataSetCounter() {
        dataSetCounter++;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

}


text: SoftUni Homeworks - 2017


text:
namespace ktt
{

RandomSearcher::RandomSearcher() :
    Searcher()
{}

void RandomSearcher::OnInitialize()
{
    m_CurrentConfiguration = GetRandomConfiguration();
}

bool RandomSearcher::CalculateNextConfiguration([[maybe_unused]] const KernelResult& previousResult)
{
    m_CurrentConfiguration = GetRandomConfiguration();
    return true;
}

KernelConfiguration RandomSearcher::GetCurrentConfiguration() const
{
    return m_CurrentConfiguration;
}

} // namespace ktt


text:
from __future__ import print_function, absolute_import
import time

import torch
from torch.autograd import Variable

from .evaluation_metrics import accuracy
from .loss import OIMLoss, TripletLoss
from .utils.meters import AverageMeter

class BaseTrainer(object):
    def __init__(self, model, criterion):
        super(BaseTrainer, self).__init__()
        self.model = model
        self.criterion = criterion

    def train(self, epoch, data_loader, optimizer, print_freq=10):
        self.model.train()

        batch_time = AverageMeter()
        data_time = AverageMeter()
        losses = AverageMeter()
        precisions = AverageMeter()

        end = time.time()

        for i, inputs in enumerate(data_loader):
            if inputs[2].size()[0] < data_loader.batch_size/2:
                print("too less batch {}".format(inputs[3].size()[0]))
                continue

            data_time.update(time.time() - end)
            inputs, targets = self._parse_data(inputs)
            loss, prec1 = self._forward(inputs, targets)
            losses.update(loss.data[0], targets.size(0))
            precisions.update(prec1, targets.size(0))

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            batch_time.update(time.time() - end)
            end = time.time()

            if (i + 1) % print_freq == 0:
                print('Epoch: [{}][{}/{}]\t'
                      'Time {:.3f} ({:.3f})\t'
                      'Data {:.3f} ({:.3f})\t'
                      'Loss {:.3f} ({:.3f})\t'
                      'Prec {:.2%} ({:.2%})\t'
                      .format(epoch, i + 1, len(data_loader),
                              batch_time.val, batch_time.avg,
                              data_time.val, data_time.avg,
                              losses.val, losses.avg,
                              precisions.val, precisions.avg))

    def _parse_data(self, inputs):
        raise NotImplementedError

    def _forward(self, inputs, targets):
        raise NotImplementedError

class Trainer(BaseTrainer):
    def _parse_data(self, inputs):
        imgs, _, pids, _ = inputs
        inputs = [Variable(imgs)]
        targets = Variable(pids).cuda()
        return inputs, targets

    def _forward(self, inputs, targets):
        ## input can be multiple input data
        outputs = self.model(*inputs)
        if isinstance(self.criterion, torch.nn.CrossEntropyLoss):
            loss = self.criterion(outputs, targets)
            prec, = accuracy(outputs.data, targets.data)
            prec = prec[0]
        elif isinstance(self.criterion, OIMLoss):
            loss, outputs = self.criterion(outputs, targets)
            prec, = accuracy(outputs.data, targets.data)
            prec = prec[0]
        elif isinstance(self.criterion, TripletLoss):
            loss, prec = self.criterion(outputs, targets)
        else:
            raise ValueError("Unsupported loss:", self.criterion)
        return loss, prec

class SeqTrainer(BaseTrainer):
    def _parse_data(self, inputs):
        imgs, flows, pids, camid = inputs
        inputs = [Variable(imgs), Variable(flows)]
        targets = Variable(pids).cuda()
        return inputs, targets

    def _forward(self, inputs, targets):
        ## input can be multiple input data
        outputs = self.model(*inputs)
        if isinstance(self.criterion, torch.nn.CrossEntropyLoss):
            loss = self.criterion(outputs, targets)
            prec, = accuracy(outputs.data, targets.data)
            prec = prec[0]
        elif isinstance(self.criterion, OIMLoss):
            loss, outputs = self.criterion(outputs, targets)
            prec, = accuracy(outputs.data, targets.data)
            prec = prec[0]
        elif isinstance(self.criterion, TripletLoss):
            loss, prec = self.criterion(outputs, targets)
        else:
            raise ValueError("Unsupported loss:", self.criterion)

        return loss, prec


text:
@font-face {
    font-family: "Roboto";
    src: url("fonts/Roboto-Regular.ttf");
    font-style: normal;
    font-weight: normal;
}

* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%
}

body {
    font-family: "Roboto", sans-serif;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

img {
    border: none;
}

input {
    vertical-align: middle
}

.connection_problem_container, .authentication_problem_container {
    position: absolute;
    z-index: 1;
    top: 5px;
    left: 0;
    width: 100%;
    text-align: center;
}

.connection_problem_block, .authentication_problem_block {
    color: #fff;
    border: 2px solid #b22222;
    font-size: 24px;
    display: inline-block;
    padding: 3px;
    border-radius: 3px;
}


text:
require 'eidolon/rgss2/rpg/base_item'

module RPG
  # == RGSS2
  # This data structure is specific to RGSS2 (VX).
  #
  # == Weapon
  # Data class for weapons.
  class Weapon < BaseItem
    attr_accessor :animation_id
    attr_accessor :price
    attr_accessor :hit
    attr_accessor :atk
    attr_accessor :def
    attr_accessor :spi
    attr_accessor :agi
    attr_accessor :two_handed
    attr_accessor :fast_attack
    attr_accessor :dual_attack
    attr_accessor :critical_bonus
    attr_accessor :element_set
    attr_accessor :state_set
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GAmOG.utils;
using GAmOG.Tripod;

namespace GAmOG.GA
{
    public abstract class Evolution
    {
        protected Genom currentGenom = null;
        protected Genom futureGenom = null;
        private int mutationChance = 50;     //0-1000
        protected int NumbersOfCandidates = EvolutionControl.pop;

        private int trendSpares = 3;
        private int trendThreshold = 12;

        public Evolution()
        {
            this.defineGenom();
        }

        public virtual void evolve1()
        {
            for(int i=4;i<this.NumbersOfCandidates;i++)
            {
                DNA newChild = this.currentGenom.mate();
                newChild.mutate(mutationChance);
                futureGenom.addDNA(newChild);
            }
        }

		public virtual void evolve2()
		{
			this.futureGenom.calcFitnessTable();
			IList<int> fitness = this.futureGenom.getFitnessTable();
			this.calcMutationChance(fitness);

			//swap Genoms
			DNA best1 = this.futureGenom.getBestDNA ();
            DNA best2 = this.futureGenom.getDNA(1);
            DNA best3 = this.futureGenom.getDNA(2);
            DNA best4 = this.futureGenom.getDNA(3);

            UnityEngine.Debug.Log(best1.fitness );
            UnityEngine.Debug.Log(best2.fitness);
            UnityEngine.Debug.Log(best3.fitness);
            UnityEngine.Debug.Log(best4.fitness+" d");

			this.currentGenom = this.futureGenom;
			this.futureGenom = new Genom_Tripod(this.NumbersOfCandidates);

			this.futureGenom.setDNA(0,best1);
			this.futureGenom.setDNA(1, best2);
			this.futureGenom.setDNA(2, best3);
			this.futureGenom.setDNA(3, best4);

			//NOTE: futureGenom must be redefined in child class
		}

		public DNA_Walking getBestWalkDNA()
		{
			return (DNA_Walking)this.currentGenom.getBestDNA();
		}

		public DNA getDNA(int idx)
		{
			return this.futureGenom.getDNA (idx);
		}

		private void calcMutationChance(IList<int> fitness)
        {
			int trend = 0;
        //    int sumFitOld = 0;
            int sumFitNew = 0;

			IList<int> fitnessOld  = this.currentGenom.getFitnessTable();

            for(int i = 0; i<fitnessOld.Count;i++)
            {
                trend += (fitnessOld[i] - fitness[i]);
           //     sumFitOld += fitnessOld[i];
                sumFitNew += fitness[i];
            }

           if ((trend * trend) > this.trendThreshold * this.trendThreshold)
            {
                this.mutationChance -= 2;
                if(mutationChance<0)
                {
                    mutationChance =1;
                }
            }

            if ((trend * trend) < this.trendThreshold * this.trendThreshold)
            {
                this.trendSpares--;
            }

            if(trendSpares==0)
            {
                this.trendSpares = 3;
                this.mutationChance += 2;
            }

            if (sumFitNew < 50)
            {
           //     this.mutationChance += 2;
            }
            UnityEngine.Debug.Log("Mutation chance: " + this.mutationChance);
        }

        protected abstract void defineGenom();
    }
}