text:
package com.tigertext.lucene;

import java.io.IOException;

import org.apache.lucene.search.FieldComparator;
import org.apache.lucene.search.FieldComparatorSource;

/**
 * Source for {@link MissingLastStringOrdValComparator}
 *
 * @author Fernando Benavides <elbrujohalcon@inaka.net>
 */
public class MissingLastStringOrdValComparatorSource extends
		FieldComparatorSource {

	/**
	 * for serialization
	 */
	private static final long	serialVersionUID	= -8156968111777826061L;

	@Override
	public FieldComparator<?> newComparator(String fieldname, int numHits,
			int sortPos, boolean reversed) throws IOException {
		return new MissingLastStringOrdValComparator(numHits, fieldname,
				sortPos, reversed);
	}

}

redpajama_set_name: RedPajamaGithub


text:
grails jesque-web plugin
========================

docs forthcoming

Release Notes
=============

* 0.3.1 - released 2012-03-13
    * Use resources plugin to fix issue with layout
    * Add "retry all" to failed queue page
* 0.3.2 - released 2012-4-3
    * Try to address address grails compatibility issues
    * Exclude tests from plugin release
* 0.3.3 - released 2012-05-10
    * Further attempts to address grails compatibility issues
* 0.4.0 - released 2012-05-31
    * Upgrade dependencies, including Jedis 2.1.0


text:
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.python;

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

import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.packages.StarlarkProvider;
import com.google.devtools.build.lib.packages.StructImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link PyStarlarkTransitions}. */
@RunWith(JUnit4.class)
public final class PyStarlarkTransitionsTest extends BuildViewTestCase {

  @Before
  public void setUp() throws Exception {
    scratch.file("myinfo/myinfo.bzl", "MyInfo = provider()");
    scratch.file("myinfo/BUILD");

    scratch.file(
        "my_package/my_rule.bzl",
        "load('//myinfo:myinfo.bzl', 'MyInfo')",
        "def impl(ctx):",
        "    return MyInfo(",
        "        wrapped = ctx.attr.wrapped,",
        "    )",
        "my_rule = rule(",
        "    implementation = impl,",
        "    attrs = {",
        "        'wrapped': attr.label(cfg = py_transitions.cfg),",
        "        'python_version': attr.string(),",
        "    },",
        ")",
        "missing_attr_rule = rule(",
        "    implementation = impl,",
        "    attrs = {",
        "        'wrapped': attr.label(cfg = py_transitions.cfg),",
        "    },",
        ")");

    scratch.file(
        "my_package/BUILD",
        "load('//my_package:my_rule.bzl', 'my_rule', 'missing_attr_rule')",
        "cc_binary(name = 'wrapped', srcs = ['wrapped.cc'])",
        "my_rule(name = 'py2', wrapped = ':wrapped', python_version = 'PY2')",
        "my_rule(name = 'py3', wrapped = ':wrapped', python_version = 'PY3')",
        "my_rule(name = 'default', wrapped = ':wrapped', python_version = 'DEFAULT')",
        "my_rule(name = 'invalid', wrapped = ':wrapped', python_version = 'invalid')",
        "missing_attr_rule(name = 'missing_attr', wrapped = ':wrapped')");
    setBuildLanguageOptions("--experimental_google_legacy_api");
  }

  @Test
  public void testTransitionToPY2() throws Exception {
    useConfiguration("--python_version=PY3");
    verifyVersion("//my_package:py2", PythonVersion.PY2);
  }

  @Test
  public void testTransitionToPY3() throws Exception {
    useConfiguration("--python_version=PY2");
    verifyVersion("//my_package:py3", PythonVersion.PY3);
  }

  @Test
  public void testTransitionToDefault() throws Exception {
    useConfiguration("--python_version=PY2", "--incompatible_py3_is_default=true");
    verifyVersion("//my_package:default", PythonVersion.PY3);
  }

  @Test
  public void testNoPythonVersionAttribute() throws Exception {
    useConfiguration("--python_version=PY3", "--incompatible_py3_is_default=false");
    // Make sure no errors occur for invalid values, and no transition is applied.
    verifyVersion("//my_package:missing_attr", PythonVersion.PY3);
  }

  @Test
  public void testInvalidPythonVersionAttribute() throws Exception {
    useConfiguration("--python_version=PY2", "--incompatible_py3_is_default=true");
    // Make sure no errors occur for missing python_version attribute, and no transition is applied.
    verifyVersion("//my_package:invalid", PythonVersion.PY2);
  }

  private void verifyVersion(String target, PythonVersion version) throws Exception {
    ConfiguredTarget configuredTarget = getConfiguredTarget(target);
    Provider.Key key =
        new StarlarkProvider.Key(
            Label.parseAbsolute("//myinfo:myinfo.bzl", ImmutableMap.of()), "MyInfo");
    StructImpl myInfo = (StructImpl) configuredTarget.get(key);
    ConfiguredTarget wrapped = (ConfiguredTarget) myInfo.getValue("wrapped");
    PythonOptions wrappedPythonOptions =
        getConfiguration(wrapped).getOptions().get(PythonOptions.class);
    assertThat(wrappedPythonOptions.pythonVersion).isEqualTo(version);
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

This is my page.

    <button onclick="signOut()">Sign Out</button>


text:
'use strict';

const config = require('config');
const jwt = require('jsonwebtoken');

const secret = config.get('servers.auth.token.secret');
const ttl = config.get('servers.auth.token.ttl');

const encrypt = (text, done) => {
  jwt.sign({
    token: text,
  }, secret, {
    expiresIn: ttl,
  }, (err, token) => {
    if (err) {
      done(err);
    } else {
      done(undefined, token);
    }
  });
};

const decrypt = (text, done) => {
  jwt.verify(text, secret, (err, decoded) => {
    if (err) {
      done(err);
    } else {
      done(undefined, decoded);
    }
  });
};

/**
 * Process the authorization: Basic header
 */
module.exports.basicLDAP = function basicLDAP(passport) {
  const send401 = (msg, req, res, next) => {
    res.set('WWW-Authenticate', res.authenticate).status(401).json(msg || {});
    next();
  };

  return (req, res, next) => {
    const authorization = req.get('Authorization');

    // The default is basic
    res.authenticate = 'Basic';

    if (!authorization) {
      // Send the request for Basic Authentication and exit
      return send401({
        message: 'Missing header',
      }, req, res, next);
    }

    if (authorization.match(/^Form/i)) {
      // Override the authorization header
      req.headers.authorization = authorization.replace(/^Form/i, 'Basic');
      res.authenticate = 'Form';
    }

    // Do the authentication
    return passport.authenticate('ldapauth', (err, user, info) => {
      if (err) {
        return next(err);
      }

      if (!user) {
        // Authentication failed
        return send401(info, req, res, next);
      }

      // Authentication succeeded so login the user
      req.user = user; // req.logIn() is not called because no session is needed

      // Encrypt the header because it contains the password
      return encrypt(authorization, (error, basic) => {
        if (error) {
          next(error);
        } else {
          // Create the bearer token
          const base64 = new Buffer(basic).toString('base64');

          // Put the token in the response and send
          const reply = info || {};
          reply.token = base64;
          res.status(200).json(reply);
        }
      });
    })(req, res, next);
  };
};

/**
 * Process the authorization: Bearer header
 */
module.exports.bearer = function bearer(passport) {
  const send401 = (req, res, next) => {
    res.set('WWW-Authenticate', 'Bearer').status(401).json({
      message: 'Login to get a new bearer token',
    });

    next();
  };

  return (req, res, next) => {
    const authorization = req.get('Authorization');
    const key = authorization ? authorization.match(/bearer\s+([\S]+)$/i) || [] : [];

    if (!authorization) {
      res.redirect('/login');
      return next();
    }

    if (!key[1]) {
      // Invalid bearer authentication
      return send401(req, res, next);
    }

    // Validate token is still valid and decrypt the basic authorization header
    const token = new Buffer(key[1], 'base64').toString('UTF-8');
    return decrypt(token, (err, basic) => {
      if (err) {
        return (err.name === 'TokenExpiredError') ? send401(req, res, next) : next(err);
      }

      // Override the authorization header
      req.headers.authorization = basic.token;

      // Do the authentication with the overridden header
      return passport.authenticate('ldapauth', (error, user) => {
        if (error) {
          next(error);
        } else if (!user) {
          // Authentication failed
          res.redirect('/login');
        } else {
          // Authentication succeeded so login the user
          req.user = user; // req.logIn() is not called because no session is needed
          next();
        }
      })(req, res, next);
    });
  };
};


text:
using OpenCvSharp;

namespace OpenCVSharpSample09
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var src = new Mat(@"..\..\Images\Penguin.Png", ImreadModes.AnyDepth | ImreadModes.AnyColor))
            using (var dst = new Mat())
            {
                src.CopyTo(dst);

                using (var window = new Window("Resize/Rotate/Blur",
                                                image: dst, flags: WindowMode.AutoSize))
                {
                    var angle = 0.0;
                    var scale = 0.7;

                    var angleTrackbar = window.CreateTrackbar(
                        name: "Angle", value: 0, max: 180,
                        callback: (pos, obj) =>
                        {
                            angle = pos;
                            rotateImage(angle, scale, src, dst);
                            window.Image = dst;
                        });

                    var scaleTrackbar = window.CreateTrackbar(
                        name: "Scale", value: 1, max: 10,
                        callback: (pos, obj) =>
                        {
                            scale = pos / 10f;
                            rotateImage(angle, scale, src, dst);
                            window.Image = dst;
                        });

                    var resizeTrackbar = window.CreateTrackbar(
                        name: "Resize", value: 1, max: 100,
                        callback: (pos, obj) =>
                        {
                            rotateImage(angle, scale, src, dst);
                            Cv2.Resize(dst, dst,
                                new Size(src.Width + pos, src.Height + pos),
                                interpolation: InterpolationFlags.Cubic);
                            window.Image = dst;
                        });

                    var blurTrackbar = window.CreateTrackbar(
                       name: "Blur", value: 1, max: 100,
                       callback: (pos, obj) =>
                       {
                           if (pos % 2 == 0) pos++;

                           rotateImage(angle, scale, src, dst);
                           Cv2.GaussianBlur(dst, dst, new Size(pos, pos), sigmaX: 0);
                           window.Image = dst;
                       });

                    angleTrackbar.Callback.DynamicInvoke(0);
                    scaleTrackbar.Callback.DynamicInvoke(1);
                    resizeTrackbar.Callback.DynamicInvoke(1);
                    blurTrackbar.Callback.DynamicInvoke(1);

                    Cv2.WaitKey();
                }
            }
        }

        private static void rotateImage(double angle, double scale, Mat src, Mat dst)
        {
            var imageCenter = new Point2f(src.Cols / 2f, src.Rows / 2f);
            var rotationMat = Cv2.GetRotationMatrix2D(imageCenter, angle, scale);
            Cv2.WarpAffine(src, dst, rotationMat, src.Size());
        }
    }
}


text:
package sample.ant;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.FileFilter;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.springframework.boot.loader.tools.JavaExecutable;
import org.springframework.util.FileCopyUtils;

/**
 * Integration Tests for {@code SampleAntApplication}.
 *
 * @author Dave Syer
 * @author Phillip Webb
 */
public class SampleAntApplicationIT {

	@Test
	public void runJar() throws Exception {
		File target = new File("target");
		File[] jarFiles = target.listFiles(new FileFilter() {

			@Override
			public boolean accept(File file) {
				return file.getName().endsWith(".jar");
			}

		});
		assertThat("Number of jars", jarFiles.length, equalTo(1));
		Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start();
		process.waitFor(5, TimeUnit.MINUTES);
		assertThat(process.exitValue(), equalTo(0));
		String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream()));
		assertThat(output, containsString("Spring Boot Ant Example"));
	}

}


text:
var gulp = require('gulp');
var nwBuilder = require('gulp-nw-builder');

// define tasks here
gulp.task('build', function () {
    return gulp.src(['./app/**/*'])
        .pipe(nwBuilder({
            version: 'v0.12.2',
            platforms: ['win', 'osx', 'linux']
        }));
});

gulp.task('default', ['build']);


text:
layout: post
category : article
tags : [osg, presentations, conferences]
---
{% include JB/setup %}

Shawn McKee was asked to present the OSiRIS project during this year's OSG All Hands meeting at Clemson University.
Slides from the presentation are available [here](https://indico.fnal.gov/contributionDisplay.py?contribId=30&confId=10571)


text:
package mapmap

import (
	"github.com/spf13/cast"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestMapMap(t *testing.T) {
	var v interface{}
	var processingErrors []error
	var err error

	m := map[string]interface{}{
		"cat":        "garfield",
		"dog":        "odie",
		"friends":    []interface{}{"John"},
		"turtle":     "0",
		"57":         int64(57),
		"doesItWork": true,
	}

	r := map[string]interface{}{
		"cat":          "garfield",
		"frog":         "0",
		"myOnlyFriend": "John",
	}

	var mappers []*Mapper
	mappers = append(mappers, NewMapper("cat", "cat"))
	mappers = append(mappers, NewMapper("turtle", "frog"))
	mappers = append(mappers, NewMapper("friends.[0]", "myOnlyFriend"))

	v, processingErrors, err = MapIt(m, mappers)

	assert.Equal(t, cast.ToStringMap(v), r)
	assert.Equal(t, processingErrors, []error{})
	assert.Equal(t, len(processingErrors), 0)
	assert.Equal(t, err, nil)
}


text:
package com.twitter.finatra.http.internal.routing

import com.twitter.inject.Logging
import java.util.regex.Matcher
import scala.collection.immutable
import scala.util.matching.Regex

private[http] object PathPattern extends Logging {

  /* Matches and captures route param names */
  private val NamedRouteParamRegex = """:\w+""".r

  /* Matches and captures wildcard route param */
  private val NamedAsteriskRegex = """:\*$""".r

  def apply(uriPattern: String): PathPattern = {
    PathPattern(
      regex = regex(uriPattern),
      captureNames = captureNames(uriPattern))
  }

  /* Private */

  private def regex(uriPattern: String): Regex = {
    val asterisksReplaced = NamedAsteriskRegex.replaceAllIn(uriPattern, """\\E(.*)\\Q""") // The special token :* captures everything after the prefix string
    val colonNameReplaced = NamedRouteParamRegex.replaceAllIn(asterisksReplaced, """\\E([^/]+)\\Q""") // Replace "colon word (e.g. :id) with a capture group that stops at the next forward slash
    val regexStr = """^\Q""" + colonNameReplaced ++ """\E$"""
    new Regex(regexStr)
  }

  private def captureNames(uriPattern: String): Seq[String] = {
    findNames(uriPattern, NamedRouteParamRegex) ++
      findNames(uriPattern, NamedAsteriskRegex)
  }

  /* We drop to remove the leading ':' */
  private def findNames(uriPattern: String, pattern: Regex): Seq[String] = {
    pattern.findAllIn(uriPattern).toSeq map { _.drop(1) }
  }
}

private[http] case class PathPattern(
  regex: Regex,
  captureNames: Seq[String] = Seq()) {

  def extract(requestPath: String): Option[Map[String, String]] = {
    val matcher = regex.pattern.matcher(requestPath)
    if (!matcher.matches)
      None
    else
      Some(extractMatches(matcher))
  }

  //Optimized
  private def extractMatches(matcher: Matcher): Map[String, String] = {
    var idx = 0
    val builder = immutable.Map.newBuilder[String, String]

    for (captureName <- captureNames) {
      idx += 1
      builder += captureName -> matcher.group(idx)
    }
    builder.result()
  }
}


text:
*The classic [Hello World!](http://rosettacode.org/wiki/Hello_world/Text) problem.*

To run:
```
javac HelloWorld.java
java HelloWorld
```


text:
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <cstdint>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END

namespace pomdog::magicavoxel {

struct VoxChunkHeader final {
    std::int32_t ID;
    std::int32_t ContentSize;
    std::int32_t ChildrenSize;
};

} // namespace pomdog::magicavoxel


text:
IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'pa.GenPla_GeneraRenta_GastoRep')
                    AND type IN ( N'P', N'PC' ) )

/****** Object:  StoredProcedure [pa].[GenPla_GeneraRenta_GastoRep]    Script Date: 16-01-2017 11:05:32 AM ******/
DROP PROCEDURE [pa].[GenPla_GeneraRenta_GastoRep]
GO

/****** Object:  StoredProcedure [pa].[GenPla_GeneraRenta_GastoRep]    Script Date: 16-01-2017 11:05:32 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [pa].[GenPla_GeneraRenta_GastoRep]
   @sessionId UNIQUEIDENTIFIER = NULL,
   @codppl INT,
   @userName VARCHAR(100) = NULL
AS
BEGIN

SET NOCOUNT ON
SET DATEFORMAT DMY

declare @codpai varchar(2),
		@codcia int,
		@codtpl int,
		@codtpl_ordinario int,
		@codtpl_decimo int,
		@codtpl_vacaciones int,
		@fecha_ini datetime,
		@fecha_fin datetime,
		@anio int,
		@isr_deduccion_legal money,
		@agr_base_xiii int,
		@agr_descuentos_isr int,
		@agr_base_isr int,
		@codrsa int,
		@anio_fin datetime,
		@quincenas_pendientes smallint,
		@decimos_pendientes numeric(12,4),
		@periodos_restantes_calculo numeric(12,4)

-- Toma el periodo de la planilla actual
SELECT @codcia = tpl_codcia,
       @codtpl = ppl_codtpl,
	   @fecha_ini = ppl_fecha_ini,
	   @fecha_fin = PPL_FECHA_FIN,
	   @anio = PPL_ANIO,
	   @codpai = cia_codpai
FROM sal.ppl_periodos_planilla
JOIN sal.tpl_tipo_planilla ON tpl_codigo = ppl_codtpl
join eor.cia_companias on cia_codigo = tpl_codcia
WHERE ppl_codigo = @codppl

select @isr_deduccion_legal = gen.get_valor_parametro_float('ISRDeduccionLegal', @codpai, null, null, null)

-- Elimina los registros calculados previamente
DELETE FROM sal.rag_renta_anual_panama_gr
 WHERE rag_codppl = @codppl

select @agr_base_xiii = gen.get_valor_parametro_int('BaseXIII_GastoRep_CodigoAgrupador', @codpai, null, null, null)

select @agr_descuentos_isr = agr_codigo from sal.agr_agrupadores where agr_codpai = @codpai and agr_abreviatura='DescuentosRentaGRepPTY'
select @agr_base_isr = agr_codigo from sal.agr_agrupadores where agr_codpai = @codpai and agr_abreviatura='IngresosRentaGRepPTY'

--DECLARE @INCLUIR_DECIMO VARCHAR(1)
--SELECT @INCLUIR_DECIMO = COALESCE(gen.get_valor_parametro_varchar('ISRIncluyeDecimo', @codpai, null, null, null), 'S')

SET @codrsa = isnull(gen.get_valor_parametro_int ('CodigoRubroGastoRep',null,null,@codcia,null),0)

SET @codtpl_ordinario = isnull(gen.get_valor_parametro_int ('CodigoPlanillaQuincenal',null,null,@codcia,null),0)
SET @codtpl_decimo    = isnull(gen.get_valor_parametro_int ('CodigoPlanillaDecimo',null,null,@codcia,null),0)
SET @codtpl_vacaciones= isnull(gen.get_valor_parametro_int ('CodigoPlanillaVacacion',null,null,@codcia,null),0)

SET @anio_fin = CONVERT(DATETIME,'31/12/'+CONVERT(VARCHAR, @anio), 103)

SET @quincenas_pendientes = CONVERT(INT, DATEDIFF(DD, (case @codtpl when @codtpl_decimo then @fecha_fin else @fecha_ini end), @anio_fin) / 15)

select @decimos_pendientes = 3 - isnull(count(1), 0)
from sal.ppl_periodos_planilla
where ppl_codtpl = @codtpl_decimo
and ppl_anio = @anio
and ppl_estado = 'Autorizado'

set @decimos_pendientes = isnull(@decimos_pendientes, 0)

set @periodos_restantes_calculo = @quincenas_pendientes + @decimos_pendientes * 2 / 3

INSERT INTO sal.rag_renta_anual_panama_gr(
	rag_codcia,
	rag_codtpl,
	rag_codppl,
	rag_codemp,
	rag_acumulado,
	rag_retenido,
	rag_proyectado,
	rag_desc_legal,
	rag_periodos_restantes
)
select codcia,
	   codtpl,
	   codppl,
	   codemp,
	   acumulado,
	   retenido,
	   proyectado,
	   deduccion_legal,
	   periodos_restantes_calculo
from (
select @codcia codcia,
	   @codtpl codtpl,
	   @codppl codppl,
	   codemp,
	   pa.fn_agrupador_valores_periodo_isr2 (@codcia, codemp, @anio, @agr_base_isr) acumulado,
	   pa.fn_agrupador_valores_periodo_isr2 (@codcia, codemp, @anio, @agr_descuentos_isr) retenido,
	   CONVERT(NUMERIC(12, 2), ese_salario_quincenal * (case when @quincenas_pendientes <= 0 then 0 else (@quincenas_pendientes - (case when @codtpl in (@codtpl_ordinario, @codtpl_vacaciones) then isnull(dva_dias / 15, 1) else 0 end)) end))
	   + convert(numeric(12, 2), (ese_salario_mensual * @decimos_pendientes * 1) / 3)
	   as proyectado,
	   (case codclr when 'E' then @isr_deduccion_legal else 0 end) deduccion_legal,
	   @periodos_restantes_calculo periodos_restantes_calculo
from (
	SELECT emp_codigo codemp,
		   isnull(gen.get_pb_field_data(exp_property_bag_data, 'exp_clase_renta'), 'A') codclr,
		   ese_salario_quincenal,
		   ese_salario_mensual
	  FROM exp.emp_empleos
	  join exp.exp_expedientes
	  on exp_codigo = emp_codexp
	  join (select ese_codemp, convert(numeric(12,2), ese_valor / 2.00) ese_salario_quincenal, ese_valor ese_salario_mensual
			from exp.ese_estructura_sal_empleos
			where ese_estado = 'V'
			and ese_codrsa = @codrsa
		) salarios
	  on ese_codemp = emp_codigo
	  WHERE emp_codtpl = @codtpl_ordinario
	   AND emp_estado = 'A'
	   AND emp_fecha_ingreso <= @FECHA_FIN
) V
left join (
	select vac_codemp, isnull(sum(isnull(dva_dias, 0)), 0) dva_dias
	from acc.dva_dias_vacacion
	join acc.vac_vacaciones
	on vac_codigo = dva_codvac
	where dva_codppl = @codppl
	group by vac_codemp
) vacaciones
on vac_codemp = codemp
) W
ORDER BY codemp

END

GO


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.kitteh.irc</groupId>
    <artifactId>client-lib</artifactId>
    <version>0.3.4-SNAPSHOT</version>

    <packaging>jar</packaging>

    <name>Kitteh IRC Client Library</name>
    <description>An IRC client library for Java. KICL uses an event bus model to handle communication with an IRC server.</description>
    <url>http://kitteh.org/irc-client-library/</url>
    <inceptionYear>2013</inceptionYear>

    <licenses>
        <license>
            <name>MIT License (Expat)</name>
            <url>http://opensource.org/licenses/mit-license.php</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <organization>
        <name>Kitteh</name>
        <url>http://kitteh.org</url>
    </organization>

    <developers>
        <developer>
            <id>mbaxter</id>
            <name>Matt Baxter</name>
            <email>matt@kitteh.org</email>
            <url>http://kitteh.org</url>
            <organization>Kitteh</organization>
            <organizationUrl>http://kitteh.org</organizationUrl>
        </developer>
    </developers>

    <issueManagement>
        <system>Github</system>
        <url>https://github.com/KittehOrg/KittehIRCClientLib/issues</url>
    </issueManagement>

    <ciManagement>
        <system>TravisCI</system>
        <url>https://travis-ci.org/KittehOrg/KittehIRCClientLib</url>
    </ciManagement>

    <scm>
        <connection>scm:git:git@github.com:KittehOrg/KittehIRCClientLib.git</connection>
        <developerConnection>scm:git:git@github.com:KittehOrg/KittehIRCClientLib.git</developerConnection>
        <url>git@github.com:KittehOrg/KittehIRCClientLib.git</url>
    </scm>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <plugin.javadocs.version>2.10.3</plugin.javadocs.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.engio</groupId>
            <artifactId>mbassador</artifactId>
            <version>1.2.1</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-codec</artifactId>
            <version>4.0.30.Final</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-handler</artifactId>
            <version>4.0.30.Final</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <pluginRepositories>
        <pluginRepository>
            <id>kitteh-repo</id>
            <url>http://repo.kitteh.org/content/groups/public/</url>
        </pluginRepository>
    </pluginRepositories>

    <distributionManagement>
        <repository>
            <id>kittehReleases</id>
            <name>Kitteh Releases</name>
            <url>http://repo.kitteh.org/content/repositories/releases</url>
        </repository>
        <snapshotRepository>
            <id>kittehSnapshots</id>
            <name>Kitteh Snapshots</name>
            <url>http://repo.kitteh.org/content/repositories/snapshots</url>
        </snapshotRepository>
    </distributionManagement>

    <profiles>
        <profile>
            <id>duckswithsauce</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>${plugin.javadocs.version}</version>
                        <configuration>
                            <excludePackageNames>org.kitteh.irc.client.library.implementation</excludePackageNames>
                        </configuration>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>2.4</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <defaultGoal>clean install</defaultGoal>
        <resources>
            <resource>
                <targetPath>.</targetPath>
                <directory>${basedir}/</directory>
                <includes>
                    <include>LICENSE</include>
                    <include>NOTICE</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>2.6.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${plugin.javadocs.version}</version>
                <configuration>
                    <excludePackageNames>org.kitteh.irc.client.library.implementation</excludePackageNames>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <minimizeJar>true</minimizeJar>
                            <relocations>
                                <relocation>
                                    <pattern>io.netty</pattern>
                                    <shadedPattern>org.kitteh.irc.lib.io.netty</shadedPattern>
                                </relocation>
                                <relocation>
                                    <pattern>net.engio</pattern>
                                    <shadedPattern>org.kitteh.irc.lib.net.engio</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.mycila</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>2.11</version>
                <executions>
                    <execution>
                        <phase>clean</phase>
                        <goals>
                            <goal>format</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <quiet>true</quiet>
                    <encoding>UTF-8</encoding>
                    <strictCheck>true</strictCheck>
                    <header>${basedir}/LICENSE</header>
                    <mapping>
                        <java>SLASHSTAR_STYLE</java>
                    </mapping>
                    <includes>
                        <include>src/main/java/org/kitteh/**</include>
                    </includes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.kitteh</groupId>
                <artifactId>kitteh-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <configuration>
                    <packageName>org.kitteh.irc.client.library</packageName>
                    <toStringRequired>false</toStringRequired>
                    <toStringIgnoreUtilities>true</toStringIgnoreUtilities>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>tostring</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using static Content.Shared.GameObjects.Components.Medical.SharedCloningPodComponent;

namespace Content.Client.GameObjects.Components.CloningPod
{
    public sealed class CloningPodWindow : SS14Window
    {
        private Dictionary<int, string> _scanManager;

        private readonly VBoxContainer _mainVBox;
        private readonly ScanListContainer _scanList;
        private readonly LineEdit _searchBar;
        private readonly Button _clearButton;
        public readonly Button CloneButton;
        public readonly Button EjectButton;
        private readonly CloningScanButton _measureButton;
        private CloningScanButton? _selectedButton;
        private Label _progressLabel;
        private readonly ProgressBar _cloningProgressBar;
        private Label _mindState;

        protected override Vector2 ContentsMinimumSize => _mainVBox?.CombinedMinimumSize ?? Vector2.Zero;
        private CloningPodBoundUserInterfaceState _lastUpdate = null!;

        // List of scans that are visible based on current filter criteria.
        private readonly Dictionary<int, string> _filteredScans = new Dictionary<int, string>();

        // The indices of the visible scans last time UpdateVisibleScans was ran.
        // This is inclusive, so end is the index of the last scan, not right after it.
        private (int start, int end) _lastScanIndices;

        public int? SelectedScan;

        protected override Vector2? CustomSize => (250, 300);

        public CloningPodWindow(
            Dictionary<int, string> scanManager)
        {
            _scanManager = scanManager;

            Title = Loc.GetString("Cloning Machine");

            Contents.AddChild(_mainVBox = new VBoxContainer
            {
                Children =
                {
                    new HBoxContainer
                    {
                        Children =
                        {
                            (_searchBar = new LineEdit
                            {
                                SizeFlagsHorizontal = SizeFlags.FillExpand,
                                PlaceHolder = Loc.GetString("Search")
                            }),

                            (_clearButton = new Button
                            {
                                Disabled = true,
                                Text = Loc.GetString("Clear"),
                            })
                        }
                    },
                    new ScrollContainer
                    {
                        CustomMinimumSize = new Vector2(200.0f, 0.0f),
                        SizeFlagsVertical = SizeFlags.FillExpand,
                        Children =
                        {
                            (_scanList = new ScanListContainer())
                        }
                    },
                    new VBoxContainer
                    {
                        Children =
                        {
                            (CloneButton = new Button
                            {
                                Text = Loc.GetString("Clone")
                            })
                        }
                    },
                    (_measureButton = new CloningScanButton {Visible = false}),
                    (_cloningProgressBar = new ProgressBar
                    {
                        CustomMinimumSize = (200, 20),
                        SizeFlagsHorizontal = SizeFlags.Fill,
                        MinValue = 0,
                        MaxValue = 10,
                        Page = 0,
                        Value = 0.5f,
                        Children =
                        {
                            (_progressLabel = new Label())
                        }
                    }),
                    (EjectButton = new Button
                    {
                        Text = Loc.GetString("Eject Body")
                    }),
                    new HBoxContainer
                    {
                        Children =
                        {
                            new Label()
                            {
                                Text = Loc.GetString("Neural Interface: ")
                            },
                            (_mindState = new Label()
                            {
                                Text = Loc.GetString("No Activity"),
                                FontColorOverride = Color.Red
                            }),
                        }
                    }
                }
            });

            _searchBar.OnTextChanged += OnSearchBarTextChanged;
            _clearButton.OnPressed += OnClearButtonPressed;

            BuildEntityList();

            _searchBar.GrabKeyboardFocus();
        }

        public void Populate(CloningPodBoundUserInterfaceState state)
        {
            //Ignore useless updates or we can't interact with the UI
            //TODO: come up with a better comparision, probably write a comparator because '.Equals' doesn't work
            if (_lastUpdate == null || _lastUpdate.MindIdName.Count != state.MindIdName.Count)
            {
                _scanManager = state.MindIdName;
                BuildEntityList();
                _lastUpdate = state;
            }

            var percentage = state.Progress / _cloningProgressBar.MaxValue * 100;
            _progressLabel.Text = $"{percentage:0}%";

            _cloningProgressBar.Value = state.Progress;
            _mindState.Text = Loc.GetString(state.MindPresent ? "Consciousness Detected" : "No Activity");
            _mindState.FontColorOverride = state.MindPresent ? Color.Green : Color.Red;
        }

        private void OnSearchBarTextChanged(LineEdit.LineEditEventArgs args)
        {
            BuildEntityList(args.Text);
            _clearButton.Disabled = string.IsNullOrEmpty(args.Text);
        }

        private void OnClearButtonPressed(BaseButton.ButtonEventArgs args)
        {
            _searchBar.Clear();
            BuildEntityList("");
        }

        private void BuildEntityList(string? searchStr = null)
        {
            _filteredScans.Clear();
            _scanList.RemoveAllChildren();
            // Reset last scan indices so it automatically updates the entire list.
            _lastScanIndices = (0, -1);
            _scanList.RemoveAllChildren();
            _selectedButton = null;
            searchStr = searchStr?.ToLowerInvariant();

            foreach (var scan in _scanManager)
            {
                if (searchStr != null && !_doesScanMatchSearch(scan.Value, searchStr))
                {
                    continue;
                }

                _filteredScans.Add(scan.Key, scan.Value);
            }

            //TODO: set up sort
            //_filteredScans.Sort((a, b) => string.Compare(a.ToString(), b.ToString(), StringComparison.Ordinal));

            _scanList.TotalItemCount = _filteredScans.Count;
        }

        private void UpdateVisibleScans()
        {
            // Update visible buttons in the scan list.

            // Calculate index of first scan to render based on current scroll.
            var height = _measureButton.CombinedMinimumSize.Y + ScanListContainer.Separation;
            var offset = -_scanList.Position.Y;
            var startIndex = (int) Math.Floor(offset / height);
            _scanList.ItemOffset = startIndex;

            var (prevStart, prevEnd) = _lastScanIndices;

            // Calculate index of final one.
            var endIndex = startIndex - 1;
            var spaceUsed = -height; // -height instead of 0 because else it cuts off the last button.

            while (spaceUsed < _scanList.Parent!.Height)
            {
                spaceUsed += height;
                endIndex += 1;
            }

            endIndex = Math.Min(endIndex, _filteredScans.Count - 1);

            if (endIndex == prevEnd && startIndex == prevStart)
            {
                // Nothing changed so bye.
                return;
            }

            _lastScanIndices = (startIndex, endIndex);

            // Delete buttons at the start of the list that are no longer visible (scrolling down).
            for (var i = prevStart; i < startIndex && i <= prevEnd; i++)
            {
                var control = (CloningScanButton) _scanList.GetChild(0);
                DebugTools.Assert(control.Index == i);
                _scanList.RemoveChild(control);
            }

            // Delete buttons at the end of the list that are no longer visible (scrolling up).
            for (var i = prevEnd; i > endIndex && i >= prevStart; i--)
            {
                var control = (CloningScanButton) _scanList.GetChild(_scanList.ChildCount - 1);
                DebugTools.Assert(control.Index == i);
                _scanList.RemoveChild(control);
            }

            var array = _filteredScans.ToArray();

            // Create buttons at the start of the list that are now visible (scrolling up).
            for (var i = Math.Min(prevStart - 1, endIndex); i >= startIndex; i--)
            {
                InsertEntityButton(array[i], true, i);
            }

            // Create buttons at the end of the list that are now visible (scrolling down).
            for (var i = Math.Max(prevEnd + 1, startIndex); i <= endIndex; i++)
            {
                InsertEntityButton(array[i], false, i);
            }
        }

        // Create a spawn button and insert it into the start or end of the list.
        private void InsertEntityButton(KeyValuePair<int, string> scan, bool insertFirst, int index)
        {
            var button = new CloningScanButton
            {
                Scan = scan.Value,
                Id = scan.Key,
                Index = index // We track this index purely for debugging.
            };
            button.ActualButton.OnToggled += OnItemButtonToggled;
            var entityLabelText = scan.Value;

            button.EntityLabel.Text = entityLabelText;

            if (scan.Key == SelectedScan)
            {
                _selectedButton = button;
                _selectedButton.ActualButton.Pressed = true;
            }

            //TODO: replace with body's face
            /*var tex = IconComponent.GetScanIcon(scan, resourceCache);
            var rect = button.EntityTextureRect;
            if (tex != null)
            {
                rect.Texture = tex.Default;
            }
            else
            {
                rect.Dispose();
            }

            rect.Dispose();
            */

            _scanList.AddChild(button);
            if (insertFirst)
            {
                button.SetPositionInParent(0);
            }
        }

        private static bool _doesScanMatchSearch(string scan, string searchStr)
        {
            return scan.ToLowerInvariant().Contains(searchStr);
        }

        private void OnItemButtonToggled(BaseButton.ButtonToggledEventArgs args)
        {
            var item = (CloningScanButton) args.Button.Parent!;
            if (_selectedButton == item)
            {
                _selectedButton = null;
                SelectedScan = null;
                return;
            }
            else if (_selectedButton != null)
            {
                _selectedButton.ActualButton.Pressed = false;
            }

            _selectedButton = null;
            SelectedScan = null;

            _selectedButton = item;
            SelectedScan = item.Id;
        }

        protected override void FrameUpdate(FrameEventArgs args)
        {
            base.FrameUpdate(args);
            UpdateVisibleScans();
        }

        private class ScanListContainer : Container
        {
            // Quick and dirty container to do virtualization of the list.
            // Basically, get total item count and offset to put the current buttons at.
            // Get a constant minimum height and move the buttons in the list up to match the scrollbar.
            private int _totalItemCount;
            private int _itemOffset;

            public int TotalItemCount
            {
                get => _totalItemCount;
                set
                {
                    _totalItemCount = value;
                    MinimumSizeChanged();
                }
            }

            public int ItemOffset
            {
                get => _itemOffset;
                set
                {
                    _itemOffset = value;
                    UpdateLayout();
                }
            }

            public const float Separation = 2;

            protected override Vector2 CalculateMinimumSize()
            {
                if (ChildCount == 0)
                {
                    return Vector2.Zero;
                }

                var first = GetChild(0);

                var (minX, minY) = first.CombinedMinimumSize;

                return (minX, minY * TotalItemCount + (TotalItemCount - 1) * Separation);
            }

            protected override void LayoutUpdateOverride()
            {
                if (ChildCount == 0)
                {
                    return;
                }

                var first = GetChild(0);

                var height = first.CombinedMinimumSize.Y;
                var offset = ItemOffset * height + (ItemOffset - 1) * Separation;

                foreach (var child in Children)
                {
                    FitChildInBox(child, UIBox2.FromDimensions(0, offset, Width, height));
                    offset += Separation + height;
                }
            }
        }

        [DebuggerDisplay("cloningbutton {" + nameof(Index) + "}")]
        private class CloningScanButton : Control
        {
            public string Scan { get; set; } = default!;
            public int Id { get; set; }
            public Button ActualButton { get; private set; }
            public Label EntityLabel { get; private set; }
            public TextureRect EntityTextureRect { get; private set; }
            public int Index { get; set; }

            public CloningScanButton()
            {
                AddChild(ActualButton = new Button
                {
                    SizeFlagsHorizontal = SizeFlags.FillExpand,
                    SizeFlagsVertical = SizeFlags.FillExpand,
                    ToggleMode = true,
                });

                AddChild(new HBoxContainer
                {
                    Children =
                    {
                        (EntityTextureRect = new TextureRect
                        {
                            CustomMinimumSize = (32, 32),
                            SizeFlagsHorizontal = SizeFlags.ShrinkCenter,
                            SizeFlagsVertical = SizeFlags.ShrinkCenter,
                            Stretch = TextureRect.StretchMode.KeepAspectCentered,
                            CanShrink = true
                        }),
                        (EntityLabel = new Label
                        {
                            SizeFlagsVertical = SizeFlags.ShrinkCenter,
                            SizeFlagsHorizontal = SizeFlags.FillExpand,
                            Text = "",
                            ClipText = true
                        })
                    }
                });
            }
        }
    }
}


text:
This module introduces an [Imbo client](https://github.com/imbo/imboclient-php) service, and a view helper for creating Imbo image URLs in Zend Framework 2 applications.

[![Build Status](https://travis-ci.org/imbo/imbo-zf2-module.png)](https://travis-ci.org/imbo/imbo-zf2-module)

## Installation
Add `imbo/imbo-zf2-module` to your `composer.json` file, and enable the module in your `application.config.php` file:

```php
<?php
return array(
    'modules' => array(
        'Imbo',
        // ...
    ),
    // ...
);
```

## Configuration
The module has some configuration options that you will need to set, and all options are under the `imboModule` key in the configuration array.

### Client configuration
To configure the ImboClient instance you need to specify one or more hosts, a user and a public/private key pair:

```php
return array(
    'imboModule' => array(
        'imboClient' => array(
            'host' => 'http://imboserver',
            // or 'host' => array('http://imboserver1', 'http://imboserver2'),
            'user' => 'some-user',
            'publicKey' => 'somepublickey',
            'privateKey' => 'someprivatekey',
        ),
        // ...
    ),
    // ...
);
```

### View helper transformation presets
The view helper supports presets specified in the configuration array if you want easier access to custom transformation chains:

```php
return array(
    'imboModule' => array(
        'viewHelperPresets' => array(
            'graythumb' => function(ImboClient\Http\ImageUrl $url) {
                return $url->thumbnail()->desaturate();
            },
        ),
        // ...
    ),
    // ...
);
```

See below on how to trigger these presets in your view scripts.

## Usage
### Injection via the initializer
The module ships with a controller initializer that looks for controllers that implement the ``Imbo\Service\ImboClientAwareInterface`` interface. Whenever such a controller is found, the ``setImboClient()`` method will be called with an instance of ``ImboClient\ImboClient``, fetched from the service manager. The interface also defines a ``getImboClient()`` method that whould return the client instance.

The module also includes a trait that implements both these methods, so if you have a controller that needs access to an Imbo client, you will only need to add a couple of lines:

```php
<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Imbo\Service\ImboClientAwareInterface,
    Imbo\Service\ImboClientAware;

class IndexController extends AbstractActionController implements ImboClientAwareInterface {
    use ImboClientAware;

    public function indexAction() {
        $client = $this->getImboClient();

        // ...
    }
}
```

All you need to do is have your controller implement the interface and ``use`` the [trait](http://php.net/traits), and Zend Framework will automatically inject the Imbo client for you.

### Client service
The service is simply called `ImboClient` and can be fetched from the main service manager.

### View helper
The view helper can be used in your view scripts like this:

```php
<img src="<?= $this->imboUrl('imageid')->thumbnail() ?>">
```

For a complete list of available transformations, see the [client documentation](http://imboclient-php.readthedocs.org/).

#### Transformation presets
Transformation presets specified in the configuration can be referred to in the view scripts by specifying a second parameter to the view helper:

```php
<img src="<?= $this->imboUrl('imageid', 'preset') ?>">
```

See how to configure transformation presets in the configuration section above.


text:
<?php

namespace Dizda\Bundle\AppBundle\Traits;

use JMS\Serializer\Annotation as Serializer;

/**
 * Trait Timestampable
 *
 * @author Jonathan Dizdarevic <dizda@dizda.fr>
 */
trait Timestampable
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     *
     * @Serializer\Groups({"Deposits", "Withdraws", "WithdrawOutputs"})
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=false)
     *
     * @Serializer\Groups({"Addresses"})
     */
    protected $updatedAt;

    /**
     * Add creation date when the object is created
     *
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();
    }

    /**
     * Add creation date when the object is created
     *
     * @ORM\PreUpdate
     */
    public function preUpdate()
    {
        $this->updatedAt = new \DateTime();
    }

    /**
     * Set createdAt
     * @codeCoverageIgnore
     *
     * @param \DateTime $createdAt
     *
     * @return $this
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     * @codeCoverageIgnore
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     * @codeCoverageIgnore
     *
     * @param \DateTime $updatedAt
     *
     * @return $this
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     * @codeCoverageIgnore
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}


text:
require "dry/validation/constants"
require "dry/validation/contract"
require "dry/validation/macros"

# Main namespace
#
# @api public
module Dry
  # Main library namespace
  #
  # @api public
  module Validation
    extend Dry::Core::Extensions
    extend Macros::Registrar

    register_extension(:monads) do
      require "dry/validation/extensions/monads"
    end

    register_extension(:hints) do
      require "dry/validation/extensions/hints"
    end

    register_extension(:predicates_as_macros) do
      require "dry/validation/extensions/predicates_as_macros"
    end

    # Define a contract and build its instance
    #
    # @example
    #   my_contract = Dry::Validation.Contract do
    #     params do
    #       required(:name).filled(:string)
    #     end
    #   end
    #
    #   my_contract.call(name: "Jane")
    #
    # @param [Hash] options Contract options
    #
    # @see Contract
    #
    # @return [Contract]
    #
    # @api public
    #
    def self.Contract(options = EMPTY_HASH, &block)
      Contract.build(options, &block)
    end

    # This is needed by Macros::Registrar
    #
    # @api private
    def self.macros
      Macros
    end
  end
end


text:
package com.cloudera.impala.catalog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import com.cloudera.impala.common.AnalysisException;
import com.cloudera.impala.thrift.TColumnType;
import com.cloudera.impala.thrift.TStructField;
import com.cloudera.impala.thrift.TTypeNode;
import com.cloudera.impala.thrift.TTypeNodeType;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Describes a STRUCT type. STRUCT types have a list of named struct fields.
 */
public class StructType extends Type {
  private final HashMap<String, StructField> fieldMap_ = Maps.newHashMap();
  private final ArrayList<StructField> fields_;

  public StructType(ArrayList<StructField> fields) {
    Preconditions.checkNotNull(fields);
    fields_ = fields;
    for (StructField field : fields_) {
      fieldMap_.put(field.getName().toLowerCase(), field);
    }
  }

  @Override
  public void analyze() throws AnalysisException {
    if (isAnalyzed_) return;
    Preconditions.checkNotNull(fields_);
    Preconditions.checkState(!fields_.isEmpty());
    Set<String> fieldNames = Sets.newHashSet();
    for (StructField f : fields_) {
      f.analyze();
      if (!fieldNames.add(f.getName().toLowerCase())) {
        throw new AnalysisException(
            String.format("Duplicate field name '%s' in struct '%s'",
                f.getName(), toSql()));
      }
    }
    isAnalyzed_ = true;
  }

  @Override
  public String toSql() {
    ArrayList<String> fieldsSql = Lists.newArrayList();
    for (StructField f: fields_) {
      fieldsSql.add(f.toSql());
    }
    return String.format("STRUCT<%s>", Joiner.on(",").join(fieldsSql));
  }

  public ArrayList<StructField> getFields() { return fields_; }

  public StructField getField(String fieldName) {
    return fieldMap_.get(fieldName.toLowerCase());
  }

  @Override
  public void toThrift(TColumnType container) {
    TTypeNode node = new TTypeNode();
    container.types.add(node);
    Preconditions.checkNotNull(fields_);
    Preconditions.checkNotNull(!fields_.isEmpty());
    node.setType(TTypeNodeType.STRUCT);
    node.setStruct_fields(new ArrayList<TStructField>());
    for (StructField field: fields_) {
      field.toThrift(container, node);
    }
  }

  @Override
  public boolean matchesType(Type t) { return false; }
}


text:
package subsystem;

/**
 *
 * This class defines three unique layers with unique parent-child relations.
 * Parent-child definition is done through the {@link Layer} generic interface typing
 * for child layers. This class also handles all tasks for the various layers.
 *
 * @param <H> Hardware layer. Extends {@link BaseLayer}.
 * @param <S> System layer. Parents H by extension of {@link Layer} with child type H.
 * @param <C> Command layer. Parents S by extension of{@link Layer} with child type S.
 *
 * @author Toaster Tech
 *
 * @see Layer
 *
 */
public class Subsystem <H extends BaseLayer, S extends Layer<H>, C extends Layer<S>> {

	/**
	 * As the three layers, each with their own distinct
	 * parent-child relations have been defined we need
	 * to assign them to variables for operation
	 */
	private H hardwareLayer;
	private S systemLayer;
	private C commandLayer;

	/**
	 * Constructor. Creates an instance of a subsystem to handle layers.
	 *
	 * @param hardwareLayer : The target hardware layer.
	 * @param systemLayer : The target system layer.
	 * @param commandLayer : The target command layer.
	 */
	public Subsystem(H hardwareLayer, S systemLayer, C commandLayer){
		this.hardwareLayer = hardwareLayer; // Assign local variables to instances given in the constructor
		this.systemLayer = systemLayer;
		this.commandLayer = commandLayer;

		this.systemLayer.setChild(this.hardwareLayer); // Assign child of this instance of systemLayer
		this.commandLayer.setChild(this.systemLayer); // Assign child of this instance of commandLayer
	}

	/**
	 * Executes the {@code robotInit()} method inherited from {@link BaseLayer} for
	 * all defined layers.
	 */
	public void robotInit(){
		this.commandLayer.robotInit(); // This layer is the top layer, so initialize it first
		this.systemLayer.robotInit(); // This layer is the middle layer, so initialize it second
		this.hardwareLayer.robotInit(); // This layer is the bottom layer, so initialize it last
	}

	/**
	 * Executes the {@code runPeriod()} method inherited from {@link BaseLayer} for
	 * all defined layers.
	 */
	public void runPeriodic(){
		this.commandLayer.runPeriodic(); // Commands come in at the top, so run this first
		this.systemLayer.runPeriodic(); // Commands go to system next, so run this second
		this.hardwareLayer.runPeriodic(); // Hardware is the final layer executed
	}

	/**
	 * Sets which command layer input should be accepted from e.x:
	 *

	 *

	 * {@code setCommandLayer(new autonomousCommandLayer)}
	 *

	 * {@code  setCommandLayer(new teleopCommandLayer)}
	 *
	 * @param c The target command layer
	 */
	public void setCommandLayer(C c){
		commandLayer = c;
		this.commandLayer.setChild(this.systemLayer);
		this.commandLayer.robotInit();
	}
}


text:
"""Script used to calculate baselines from raw performance test output."""

# We need to call sys.path.append(os.path.join(os.getcwd(), 'tests'))
# before importing SUPPORTED_KERNELS. But this results in a pyling error.
# pylint: disable=wrong-import-position

import argparse
import os
import tempfile
import json
from typing import List
import sys

from providers.types import FileDataProvider
from providers.iperf3 import Iperf3DataParser
from providers.block import BlockDataParser
from providers.snapshot_restore import SnapshotRestoreDataParser
from providers.latency import LatencyDataParser

sys.path.append(os.path.join(os.getcwd(), "tests"))

from framework.defs import SUPPORTED_KERNELS  # noqa: E402

OUTPUT_FILENAMES = {
    "vsock_throughput": ["test_vsock_throughput"],
    "network_tcp_throughput": ["test_network_tcp_throughput"],
    "block_performance": [
        "test_block_performance_sync",
        "test_block_performance_async",
    ],
    "snap_restore_performance": ["test_snap_restore_performance"],
    "network_latency": ["test_network_latency"],
}

DATA_PARSERS = {
    "vsock_throughput": Iperf3DataParser,
    "network_tcp_throughput": Iperf3DataParser,
    "block_performance": BlockDataParser,
    "snap_restore_performance": SnapshotRestoreDataParser,
    "network_latency": LatencyDataParser,
}

def get_data_files(args) -> List[str]:
    """Return a list of files that contain results for this test."""
    assert os.path.isdir(args.data_folder)

    file_list = []
    res_files = [
        f"{filename}_results_{args.kernel}.json"
        for filename in OUTPUT_FILENAMES[args.test]
    ]
    # Get all files in the dir tree that have the right name.
    for root, _, files in os.walk(args.data_folder):
        for file in files:
            if file in res_files:
                file_list.append(os.path.join(root, file))

    # We need at least one file.
    assert len(file_list) > 0

    return file_list

def concatenate_data_files(data_files: List[str]):
    """Create temp file to hold all concatenated results for this test."""
    outfile = tempfile.NamedTemporaryFile()

    for filename in data_files:
        with open(filename, encoding="utf-8") as infile:
            contents = str.encode(infile.read())
            outfile.write(contents)
    outfile.flush()
    return outfile

def main():
    """Run the main logic.

    This script needs to be run from Firecracker's root since
    it depends on functionality found in tests/ framework.
    The script expects to find at least 2 files containing test results in
    the provided data folder
     (e.q test_results/buildX/test_vsock_throughput_results_5.10.json).
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-d",
        "--data-folder",
        help="Path to folder containing raw test data.",
        action="store",
        required=True,
    )
    parser.add_argument(
        "-t",
        "--test",
        help="Performance test for which baselines \
                            are calculated.",
        action="store",
        choices=[
            "block_performance",
            "network_latency",
            "network_tcp_throughput",
            "snap_restore_performance",
            "vsock_throughput",
        ],
        required=True,
    )
    parser.add_argument(
        "-k",
        "--kernel",
        help="Host kernel version on which baselines \
                            are obtained.",
        action="store",
        choices=SUPPORTED_KERNELS,
        required=True,
    )
    parser.add_argument(
        "-i",
        "--instance",
        help="Instance type on which the baselines \
                            were obtained.",
        action="store",
        choices=["m5d.metal", "m6i.metal", "m6a.metal", "m6g.metal"],
        required=True,
    )
    args = parser.parse_args()

    # Create the concatenated data file.
    data_file = concatenate_data_files(get_data_files(args))

    # Instantiate a file data provider.
    data_provider = FileDataProvider(data_file.name)

    # Instantiate the right data parser.
    parser = DATA_PARSERS[args.test](data_provider)

    # Finally, parse and update the baselines.
    with open(
        f"./tests/integration_tests/performance/configs/"
        f"test_{args.test}_config_{args.kernel}.json",
        "r+",
        encoding="utf8",
    ) as baselines_file:
        json_baselines = json.load(baselines_file)
        current_cpus = json_baselines["hosts"]["instances"][args.instance]["cpus"]
        cpus = parser.parse()

        for cpu in cpus:
            model = cpu["model"]
            for old_cpu in current_cpus:
                if old_cpu["model"] == model:
                    old_cpu["baselines"] = cpu["baselines"]
        baselines_file.truncate(0)
        baselines_file.seek(0, 0)
        json.dump(json_baselines, baselines_file, indent=4)

        # Warn against the fact that not all CPUs pertaining to
        # some arch were updated.
        assert len(cpus) == len(current_cpus), (
            "It may be that only a subset of CPU types were updated! "
            "Need to run again! Nevertheless we updated the baselines..."
        )

if __name__ == "__main__":
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
             http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">

  <!-- use a dummy rest consumer factory for the rest engine -->
  <bean id="dummy-rest" class="org.apache.camel.test.blueprint.component.rest.DummyRestConsumerFactory"/>

  <camelContext xmlns="http://camel.apache.org/schema/blueprint">

    <intercept>
      <to uri="mock:intercept"/>
    </intercept>

    <rest path="/say/hello">
      <get>
        <route>
          <to uri="mock:hello"/>
          <to uri="mock:bar"/>
          <transform>
            <constant>Bye World</constant>
          </transform>
        </route>
      </get>
    </rest>

  </camelContext>

</blueprint>


text:
'use strict';

actionatadistanceApp.controller('MainCtrl', function($scope) {

});