text:
nom: Lactarius hygrophoroides
date: 2018-08-18 00:00:00
image: https://c2.staticflickr.com/4/3707/9368669824_b30939639b_n.jpg
image-originale: https://www.flickr.com/photos/kaufholtz/9368669824/in/photolist-fgST95-fgSS7N
album-flickr:
  - 72157677404447085

details:
  nom-francais: Lactaire hygrophore
  domaine: Eucaryote
  regne: Fungi
  phylum: Basidiomycota
  sous-phylum: Agaricomycotina
  classe: Agaricomycetes
  sous-classe: Incertae sedis
  ordre: Russulales
  famille: Russulaceae
  genre: Lactarius
  espece: Lactarius hygrophoroides Berk. & M.A. Curtis
  litterature: Berkeley, MJ; Curtis, MA. 1859. Centuries of North American fungi. Annals and Magazine of Natural History. 4:284-296

collections:
  - fongarium: cKc0091
    date: 25 juillet 2013
    planche:
      numero:
      miniature: # Largeur 320px. ici
      originale: # Exemple: ici
    geolocalisation: 46°18'05.3"N 73°05'41.8"O
    elevation: 95 m
    determinee:
    confirmee: Yves Lamoureux

description:
  acanthocytes:
  acanthophyses:
  aiguillons:
  aleurioconidies:
  anamorphe:
  anamorphe-conidien:
  anneau:
  apothecie:
  arete-lamellaire:
  arthroconidies:
  articles:
  ascome:
  ascospores:
  asques:
  asterohyphidies:
  avertissement:
  base-du-pied:
  base-sterile:
  base-stipitiforme:
  basides:
  basidiospores:
  basidioles:
  basidiome:
  bibliographies:
  biotopes: pousse au sol des forêts de feuillus, chênaie
  boucles:
  brachybasidioles:
  calicule:
  capillitium:
  capitule:
  caulobasides:
  caulocystides:
  caulocystides-medianes:
  caulocystides-sommitales:
  cellules-hymeniales-diverticulees:
  cellules-hymeniales-en-brosses:
  cellules-marginales-paracystides:
  cellules-peritheciales:
  cellules-stromatiques:
  chair: ferme, blanche
  chancre:
  cheilochrysocystides:
  cheilocystides:
  cheiloleptocystides:
  cheilomacrocystides:
  chlamydospores:
  chrysocystides:
  circumcystides:
  clavules:
  columelle:
  commentaires: |
    De Claude Kaufholtz-Couture. « Lactarius hygrophoroides est le Current name. »
  conidies:
  conidiome:
  conidiophores:
  consistance:
  contexte:
  cordons-myceliens:
  cordons-rhizomorphiques:
  cortex:
  cortex-caulinaire:
  cortex-du-pied-et-du-bulbe:
  cortex-peridial:
  cortex-sclerotial:
  cortine:
  couches-de-tubes:
  coupe-sterile:
  cristaux:
  cristaux-d-oxalate:
  cuticule:
  cutis:
  cycle:
  cystides:
  cystides-hymeniales:
  cystides-intermediaires:
  cystidioles:
  dendrohyphydies:
  depots-de-pigment-interhyphal:
  dermatocystides-caulocystides-et-pileipellis:
  derniere-correction:
  dicaryophyses:
  dichophyses:
  disque-basal:
  distribution: occasionnel
  elateres:
  elements-acanthophyses:
  elements-cystidioides:
  elements-hyphoides:
  elements-setoides:
  elements-steriles:
  elements-sur-les-cotes:
  elements-velaires:
  endoperidium:
  especes-identification:
  especes-semblables:
  excipulum:
  excipulum-medullaire-superieur:
  excipulum-medullaire-moyen:
  excipulum-medullaire-inferieur:
  excipulum-ectal:
  exhalaison: faible ou faiblement de fruits de mer
  exhalaison-de-la-chair:
  exhalaison-des-lames:
  exoperidium:
  extremites-hyphales:
  face-externe:
  face-poroïde:
  feutrage-basal:
  fragments-sporaux:
  glebe:
  gleocystides:
  gleocystides-hymeniales:
  gleocystides-subhymeniales:
  granules-calcaires:
  groupe:
  hymenium:
  hymenocystides:
  hymenophore:
  hyphes:
  hyphes-de-la-chair:
  hyphes-de-l-anneau:
  hyphes-du-pied:
  hyphes-glebales:
  hyphes-gleopleres:
  hyphes-hymeniales:
  hyphes-ligatives:
  hyphes-oleiferes:
  hyphes-pectinees:
  hyphes-primordiales:
  hyphes-setales:
  hyphes-squelettiques:
  hyphes-skeletoligative:
  hyphes-subiculaires:
  hyphes-tramales:
  hyphes-vesiculaires:
  hyphidies:
  hyphique:
  hypobasides:
  hypoderme:
  hypoge:
  hypophylle:
  hypothalle:
  hypothece:
  hysterothece:
  lames: adnées à subdécurrentes, espacées à très espacées lorsque mature, larges, épaisses, non fourchues, interveinées, avec lamellules, blanchâtre devenant crème ou jaunâtre pâle, immuables au froissement, parfois avec un stade lavande
  lamprocystides:
  lamprocheilocystides:
  lampropleurocystides:
  lamprocaulocystides:
  latex: abondant, blanc, immuable ou devenant lentement jaunâtre, tachant parfois les tissus de brun violacé
  leptocystides:
  macrocystides:
  macropleurocystides:
  marge:
  marge-et-face-externe:
  mediostrate:
  medulla:
  medulla-caulinaire:
  medulla-clavariale:
  medulla-clavulaire:
  microconidies:
  mode-de-croissance: solitaire, dispersé ou grégaire
  mycelium-basal:
  myxocarpe:
  nouvelle-espece:
  note-taxonomique:
  oeuf:
  paracapillitium:
  paraphyses:
  parasite:
  paroi-peritheciale:
  peridiole:
  peridiopellis:
  peridium:
  peritheces:
  phenologie: de juillet à septembre
  phialoconidies:
  pieds-steriles:
  pigments:
  pileipellis:
  pileitrame:
  pileocystides:
  pileus: 30-100 mm Ø, convexe puis plat, légèrement déprimé au centre, parfois en forme de vase, finement velouté, sec, dont la marge est légèrement incurvée au début; souvent légèrement rugueux, uniformément coloré orange opaque à cannelle orangé
  plasmode:
  pleurochrysocystides:
  pleurocystides:
  poils:
  poils-basaux:
  poils-caulinaires:
  poils-du-cortex:
  poils-externes:
  poils-lateraux-et-caulinaires:
  poils-marginaux:
  poils-mycelien-basaux:
  poils-peridiaux:
  poils-peritheciaux:
  poils-pileiques:
  pores:
  premiere-mention:
  pseudocapillitium:
  pseudocolumelle:
  pseudocystides:
  pseudo-peridioles:
  publications: |
    Bessette, Alan E.; Bessette, Arleen R.; Harris, David B. Milk Mushrooms of North America (A Field Identification Guide to the Genus Lactarius), Syracuse University Press, 2009, 307 p.
    Heilmann-Clausen, J.,; Verbeken, A.; Vesterholt, J. The genus Lactarius, Fungi of Northern Europe vol. 2, 1998, 146 p.
    Smith, Alexander H.; Hesler, Lexemuel R. North American Species of Lactarius, Ann Arbor, The University of Michigan Press, 1979, 853 p.
  publications-microscopiques:
  reactions-macrochimiques: |
    Potasse (KOH 10%) = olive pâle sur le pileus
  receptacle:
  remarques:
  repartition:
  rhizomorphes:
  sac-sporifere:
  saveur: douce
  sclerocystides:
  sclerote:
  soies:
  soies-hymeniales:
  sporee: blanche à crème
  spherocytes:
  sporocystes:
  stipe: 30-50 x 5-15 mm Ø, cylindrique, subégal, plein ou farci, sec, lisse à pruineux, concolore au pileus, ou plus pâle
  stipitipellis:
  stipititrame:
  stroma:
  subhymenium:
  subiculum:
  substrat:
  synonymie: |
    Lactifluus hygrophoroides (Berk. & M.A. Curtis) Kuntze, Revisio generum plantarum 3 (2):857 (1891)
  systeme-hyphal:
  textura:
  tomentum-caulinaire:
  tomentum-pileique:
  trame-hymenophorale:
  trame-lamellaire:
  trame-tubulaire:
  type:
  typique:
  voile:
  voile-general:
  voile-partiel:
  volve:
  zone-perihymeniale:
---


text:
package com.openshift.evg.roadshow.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Created by jmorales on 11/08/16.
 */
@Path("/healthz")
public class Healthz {

    @GET
    @Produces("text/plain")
    public String healthz(){
        return "OK";
    }
}

redpajama_set_name: RedPajamaGithub


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>BlockInstanceExplodeAndGroup — armacode Documentation</title>

    <link rel="stylesheet" href="../../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../../_static/ar-ma_favicon.ico"/>
    <link rel="top" title="armacode Documentation" href="../../index.html" />
    <link rel="up" title="Tools" href="../../tools.html" />
    <link rel="next" title="BlockInstanceExplodeAndName" href="BlockInstanceExplodeAndName.html" />
    <link rel="prev" title="BlockGenerateBasePlaneSurfaces" href="BlockGenerateBasePlaneSurfaces.html" />

Navigation

          index

          next |

          previous |

armacode Documentation »

Tools »

BlockInstanceExplodeAndGroup¶

Explode block instances and add to group. (Experimental)

Previous topic

BlockGenerateBasePlaneSurfaces

Next topic

BlockInstanceExplodeAndName

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

armacode Documentation »

Tools »

        © Copyright 2014, Tony Ho.
      Created using Sphinx 1.3.5.


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

namespace Cats.Models.Hubs
{
    public class UnitModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}


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

<title>Uses of Class experiment.accuracy.gossiplive.GossipLive</title>
<meta name="date" content="2017-02-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
experiment.accuracy.gossiplive.GossipLive

Packages that use GossipLive

Package
Description

experiment.accuracy.gossiplive

Uses of GossipLive in experiment.accuracy.gossiplive

Fields in experiment.accuracy.gossiplive declared as GossipLive

Modifier and Type
Field and Description

static GossipLive
StreamingInit.sourceNode

The source.

Methods in experiment.accuracy.gossiplive that return GossipLive

Modifier and Type
Method and Description

GossipLive
GossipLive.clone()

Methods in experiment.accuracy.gossiplive with parameters of type GossipLive

Modifier and Type
Method and Description

void
GossipLive.doPropose(GossipLive partner,
         java.util.TreeSet<Chunk> proposedChunks,
         int nTransmissibleChunks)

Implement the Propose transition of the GL protocol, invoked by the responder role.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(bool es3_capable) {
  ExpectEnableDisable(GL_BLEND, false);
  ExpectEnableDisable(GL_CULL_FACE, false);
  ExpectEnableDisable(GL_DEPTH_TEST, false);
  ExpectEnableDisable(GL_DITHER, true);
  ExpectEnableDisable(GL_POLYGON_OFFSET_FILL, false);
  ExpectEnableDisable(GL_SAMPLE_ALPHA_TO_COVERAGE, false);
  ExpectEnableDisable(GL_SAMPLE_COVERAGE, false);
  ExpectEnableDisable(GL_SCISSOR_TEST, false);
  ExpectEnableDisable(GL_STENCIL_TEST, false);
  if (group_->feature_info()->feature_flags().ext_multisample_compatibility) {
    ExpectEnableDisable(GL_MULTISAMPLE_EXT, true);
  }
  if (group_->feature_info()->feature_flags().ext_multisample_compatibility) {
    ExpectEnableDisable(GL_SAMPLE_ALPHA_TO_ONE_EXT, false);
  }
  if (es3_capable) {
    ExpectEnableDisable(GL_RASTERIZER_DISCARD, false);
    ExpectEnableDisable(GL_PRIMITIVE_RESTART_FIXED_INDEX, false);
  }
}

void GLES2DecoderTestBase::SetupInitStateExpectations(bool es3_capable) {
  EXPECT_CALL(*gl_, BlendColor(0.0f, 0.0f, 0.0f, 0.0f))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, BlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, BlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, ClearColor(0.0f, 0.0f, 0.0f, 0.0f))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, ClearDepth(1.0f)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, ClearStencil(0)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, ColorMask(true, true, true, true))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, CullFace(GL_BACK)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, DepthFunc(GL_LESS)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, DepthMask(true)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, DepthRange(0.0f, 1.0f)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, FrontFace(GL_CCW)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, Hint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE))
      .Times(1)
      .RetiresOnSaturation();
  if (group_->feature_info()->feature_flags().oes_standard_derivatives) {
    EXPECT_CALL(*gl_,
                Hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES, GL_DONT_CARE))
        .Times(1)
        .RetiresOnSaturation();
  }
  EXPECT_CALL(*gl_, LineWidth(1.0f)).Times(1).RetiresOnSaturation();
  if (group_->feature_info()->feature_flags().chromium_path_rendering) {
    EXPECT_CALL(*gl_, MatrixLoadfEXT(GL_PATH_MODELVIEW_CHROMIUM, _))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (group_->feature_info()->feature_flags().chromium_path_rendering) {
    EXPECT_CALL(*gl_, MatrixLoadfEXT(GL_PATH_PROJECTION_CHROMIUM, _))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (group_->feature_info()->feature_flags().chromium_path_rendering) {
    EXPECT_CALL(*gl_, PathStencilFuncNV(GL_ALWAYS, 0, 0xFFFFFFFFU))
        .Times(1)
        .RetiresOnSaturation();
  }
  EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ALIGNMENT, 4))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_ALIGNMENT, 4))
      .Times(1)
      .RetiresOnSaturation();
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_PACK_ROW_LENGTH, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_PACK_SKIP_PIXELS, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_PACK_SKIP_ROWS, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_ROW_LENGTH, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_SKIP_PIXELS, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_SKIP_ROWS, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  if (es3_capable) {
    EXPECT_CALL(*gl_, PixelStorei(GL_UNPACK_SKIP_IMAGES, 0))
        .Times(1)
        .RetiresOnSaturation();
  }
  EXPECT_CALL(*gl_, PolygonOffset(0.0f, 0.0f)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_, SampleCoverage(1.0f, false)).Times(1).RetiresOnSaturation();
  EXPECT_CALL(*gl_,
              Scissor(kViewportX, kViewportY, kViewportWidth, kViewportHeight))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilFuncSeparate(GL_FRONT, GL_ALWAYS, 0, 0xFFFFFFFFU))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFFU))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilMaskSeparate(GL_FRONT, 0xFFFFFFFFU))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilMaskSeparate(GL_BACK, 0xFFFFFFFFU))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_, StencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP))
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*gl_,
              Viewport(kViewportX, kViewportY, kViewportWidth, kViewportHeight))
      .Times(1)
      .RetiresOnSaturation();
}
#endif  // GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_DECODER_UNITTEST_0_AUTOGEN_H_


text:
layout: post
title:  Template Matching
categories: XAP97NET
parent: querying-the-space.html
weight: 200
---

{% summary %}How to query the space using Template Matching{% endsummary %}

# Overview

Template matching (a.k.a. Match by example) is a simple way to query the space - The template is a POCO of the desired entry type, and the properties which are set on the template (i.e. not null) are matched against the respective properties of entries of the same type in the space. Properties with null values are ignored (not matched).

Since by convention the default constructor usually initializes all the properties to `null` either implicitly or explicitly, in most cases it's enough to simply set the properties which should be matched, without bothering with explicitly setting null to the other properties. Note that setting two or more properties with non-null values provides an **AND** behavior.

{% info %}
It is highly recommended to index one or more of the properties used in the template to speed up the matching process. For more information see [Indexing](./indexing.html).
If you require additional query options refer to [SQLQuery](./query-sql.html).
{%endinfo%}

# Examples

The following examples assume the default constructor of **Person** initializes all its properties to `null`.

Read an entry of type **Person** whose **FirstName** property is **John**:

{% highlight csharp %}
Person template = new Person();
template.FirstName = "John";
Person person = spaceProxy.Read(template);
{% endhighlight %}

Read an entry of type **Person** whose **FirstName** is **John** and **LastName** is **Smith**:

{% highlight csharp %}
Person template = new Person();
template.FirstName = "John";
template.LastName = "Smith";
Person person = spaceProxy.Read(template);
{% endhighlight %}

If none of the properties are set, all the entries of the type are matched. For example, to count all entries of type **Person**:

{% highlight csharp %}
int numOfPersons = spaceProxy.Count(new Person());
{% endhighlight %}

If the template class is null, all the entries in the space are matched. For example, to clear all entries from the space:

{% highlight csharp %}
spaceProxy.Clear(null);
{% endhighlight %}

# Indexes

GigaSpaces XAP includes a sophisticated built-in real-time indexing engine (regardless whether the space is persistent or not) that maintains a hash and btree like indexes for each indexed Space Class attribute. If you store a large number of Space objects from the same class type in the space, consider defining one or more indexes for attributes used with template matching or [SQL Query](./query-sql.html). Defining indexes will improve the `Read/Take/ReadMultiple/TakeMultiple/Clear/Count` operations response time significantly. Remember, indexes impact `Write` and `Take` operations response time, so choose your indexed fields carefully - each index has an overhead. For more information see [Indexing](./indexing.html).

# Inheritance Support

Template Matching support inheritance relationships, so that entries of a sub-class are visible in the context of the super class, but not the other way around.
For example, suppose class **Citizen** extends class **Person**:

{% highlight csharp %}
spaceProxy.Write(new Person());
spaceProxy.Write(new Citizen());
// Count persons - should return 2:
int numberOfPersons = spaceProxy.Count(new Person());
// Count citizends - should return 1:
int numberOfCitizens = spaceProxy.Count(new Citizen());
{% endhighlight %}

{% info%}
Since all classes extends `Object`, a template of type `Object` will match all the entries in the space.
{%endinfo%}

# Partitioned cluster

When querying a partitioned cluster using a template, it is possible to use the routing property to control whether the query is broadcasted to the entire cluster or executed against a specific partition.
For more information see [Routing In Partitioned Spaces](./routing-in-partitioned-spaces.html).

# Primitive Types

Properties with primitive types pose a problem - a primitive type cannot be set to null. For example, suppose class **Person** has property **Age** of type **int**, and we wrote the following piece of code which writes and reads a person:

{% highlight csharp %}
// Create a person and write it to the space:
Person p1 = new Person();
p1.Age = 30;
spaceProxy.Write(p1);
// Read person from space:
Person p = spaceProxy.Read(new Person());
{% endhighlight %}

We expect **p** to hold the person we just wrote to the space, but in fact it will be null: since **age** is primitive it is implicitly initialized to 0 (zero) and cannot be set to null either implicitly or explicitly, which means we're actually matching for Persons whose age is 0 (zero).

To overcome this issue we can map a primitive value to null via the `[SpaceProperty(NullValue = ?)]` attribute. For example:

{% highlight csharp %}
public class Person
{
    private int age = -1;

    [SpaceProperty(NullValue = -1)]
    public int Age { get; set; }

    // The rest of the class is omitted for brevity.
}
{% endhighlight %}

We've indicated that `-1` should be treated as `null` when performing template matching, and initialized age to `-1` so users of Person class need not set it explicitly whenever they use it. For more information refer to [Object Metadata](./object-metadata.html).

{% note%}
Properties of primitive types are implicitly boxed when stored in the space and unboxed when reconstructed to a POCO.
It is highly recommended to use the  primitive wrapper classes instead of primitives to simplify the code and avoid user errors.
{%endnote%}

# Nested Template Matching

Nested template matching is not supported - to match nested properties, collections and arrays use [SQLQuery](./query-sql.html).


text:
package org.hibernate.validator.referenceguide.chapter06.crossparameter;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Constraint(validatedBy = ConsistentDateParameterValidator.class)
@Target({ METHOD, CONSTRUCTOR, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
public @interface ConsistentDateParameters {

	String message() default "{org.hibernate.validator.referenceguide.chapter04." +
			"crossparameter.ConsistentDateParameters.message}";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };
}


text:
package slickext.macros

import scala.reflect.macros.blackbox.Context
import scala.reflect._
import scala.language.experimental.macros
import scala.annotation.StaticAnnotation

class table[T](tableName: String = "") extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro TableMacroImpl.impl
}

class TableMacroImpl(val c: Context) {

  import c.universe._

  case class TableInfo(
    productType: Type,
    productCompanionType: Type,
    productFields: Iterable[MethodSymbol],
    annotationParams: Iterable[Tree]
  )

  def impl(annottees: c.Expr[Any]*): c.Expr[Any] = annottees.map(_.tree) match {
    case (classDecl: ClassDef) :: Nil =>
      extractTableInfo() match {
        case Right(info) =>
          c.Expr(genCode(classDecl, info))
        case Left(err) =>
          c.abort(c.enclosingPosition, err)
      }
    case decl =>
      c.abort(c.enclosingPosition, "Underlying class must not be top-level and without companion")
  }

  private def genCode(classDef: ClassDef, info: TableInfo) = {
    val q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = classDef
    val tableName = Literal(Constant(getTableName(info)))
    val definedColumns = getDefinedColumns(stats)
    val notDefinedFields = info.productFields.filterNot {
      case f => definedColumns.contains(f.name.decodedName.toString)
    }
    val generatedCols = genColumns(info, notDefinedFields)
    val allColNames =  info.productFields.map(_.name)
    val mapping = if(allColNames.size <= 22) genSimpleMapping(info, allColNames) else genHListMapping(info, allColNames)
    q"""
      $mods class $tpname(tag: Tag, slickextTbName: String) extends Table[${info.productType}](tag, slickextTbName) {
        ..$stats
        ..$generatedCols
        $mapping
      }
      object ${tpname.toTermName} extends TableQuery[${tpname}]({tag: Tag => new $tpname(tag, $tableName)})
      """

  }

  private def genSimpleMapping(info: TableInfo, columns: Iterable[TermName]) = {
    val pCompType = info.productCompanionType.typeSymbol.name.toTermName
    q"def * = (..$columns) <> ((${pCompType}.apply _).tupled, ${pCompType}.unapply)"
  }

  private def genHListMapping(info: TableInfo, columns: Iterable[TermName]) = {
    val hlist = hlistConcat(columns)
    val pCompType = info.productCompanionType
    val pType = info.productType
    val columnElems = (0 until columns.size).map(i => q"x($i)")
    val productHList = hlistConcat(columns.map(n =>q"x.$n"))
    val toProduct = q"{case x => new $pType(..$columnElems)}"
    val fromProduct = q"{x: $pType => Option($productHList)}"
    q"def * = ($hlist).shaped <> ($toProduct, $fromProduct)"
  }

  private def genColumns(info: TableInfo, notDefined: Iterable[MethodSymbol]) = {
    notDefined.map{ f =>
      val fName = f.name
      val fType = f.returnType
      val columnName = Literal(Constant(snakify(fName.decodedName.toString)))
      if(fName.decodedName.toString == "id" &&
        (fType =:= typeOf[Option[Long]] || fType =:= typeOf[Option[Int]] )) {
        q"""
         def ${fName.toTermName} = column[$fType]($columnName, O.PrimaryKey, O.AutoInc)
        """
      } else {
        q"""
         def ${fName.toTermName} = column[$fType]($columnName)
        """
      }
    }
  }

  private def extractTableInfo() = {
    c.macroApplication match {
      case  q"new $annotationTpe[$paramTypeTree]().$method(..$methodParams)" =>
        val pType = typeOfTree(paramTypeTree)
        val pCompType = pType.companion
        val pFields = getProductFields(pType)
        Right(TableInfo(pType, pCompType, pFields, Nil))
      case  q"new $annotationTpe[$paramTypeTree](..$params).$method(..$methodParams)" =>
        val pType = typeOfTree(paramTypeTree)
        val pCompType = pType.companion
        val pFields = getProductFields(pType)
        Right(TableInfo(pType, pCompType, pFields, params))
      case _ =>
        Left(c.macroApplication.toString + " illegal macro application, correct usage @table[SomeType]")
    }
  }

  private def getProductFields(productTpe: Type) = {
    productTpe.decls.collect {
      case m: MethodSymbol if m.isCaseAccessor => m
    }
  }

  private def getDefinedColumns(defs: Seq[Tree]) = {
    defs.collect {
      case m: DefDef =>
        val q" def $name = $expr" = m
        name.decodedName.toString
    }
  }

  private def getTableName(info: TableInfo): String = {
    def decodeAnnotateParam(param: Tree) = {
      val q"$fname = $fv" = param
      fname.toString -> fv
    }
    info.annotationParams.map(decodeAnnotateParam(_)).collectFirst {
      case ("tableName", Literal(Constant(name: String))) if name != "" => name
    }.getOrElse(snakify(info.productType.typeSymbol.name.decodedName.toString))
  }

  private def hlistConcat[T: Liftable ](elems: Iterable[T]) = {
    val HNil = q"slick.collection.heterogeneous.HNil": Tree
    elems.toList.reverse.foldLeft(HNil) { (list, c) =>
      q"$c :: $list"
    }
  }

  private def typeOfTree(tree: Tree) = {
    c.typecheck(q"??? : $tree").tpe
  }

  private def snakify(name: String) = {
    "(?<!^)([A-Z\\d])".r.replaceAllIn(name, "_$1").toLowerCase()
  }
}


text:
<?php

class GiveItSdkCollection {
	public $type;

	private $client;
	private $data;
	private $pages;

	public function __construct($type)
	{
		$this->type = $type;

		$this->setupClient();

		$this->pages = (object)array('size' => 10, 'current' => 1, );
	}

	private function setupClient()
	{
		$this->client = GiveItSdkClient::getInstance();
	}

	private function getBaseURL()
	{
		return '/'.Tools::strtolower($this->type).'s';
	}

	public function setLimit($limit)
	{
		$this->pages->size = $limit;
	}

	public function addFilter($name, $value)
	{
		$this->filters[] = "$name=$value";
	}

	public function getPage($page_number = 1)
	{
		$options = array('page' => $page_number, );

		$url = $this->buildURL($options);
		$response = $this->client->sendGET($url);

		return $this->parseCollectionResponse($response);

	}

	public function nextPage()
	{
		if (!$this->pages->next)
			return false;

		return $this->getPage($this->pages->next);
	}

	public function previousPage()
	{
		return $this->getPage($this->pages->previous);
	}

	public function buildURL($override_options = array())
	{
		$url = $this->getBaseURL();

		$options = array('limit' => $this->pages->size, 'page' => $this->pages->current, );

		foreach ($override_options as $key => $val)
		{
			if (isset($options[$key]))
				$options[$key] = $val;
		}

		$url .= '?'.http_build_query($options);

		return $url;
	}

	private function parseCollectionResponse($response)
	{
		if (!is_object($response))
			return false;

		$this->pages = $response->pages;
		$this->data = $response->data;

		return $this->data;
	}

	public function all()
	{
		$url = $this->buildURL();
		$response = $this->client->sendGET($url);

		return $this->parseCollectionResponse($response);
	}

	public function since($date)
	{
		if ($date == 'yesterday')
			$date = date('Y-m-d', strtotime('yesterday'));

		$url = $this->getBaseURL()."?filter:created_at=]$date";

		$collection = $this->client->sendGET($url);

		return $collection;

	}

	public function get($id)
	{
		$url = $this->getBaseURL()."/$id";

		$response = $this->client->sendGET($url);

		// TODO: error checking - valid response? no errors?

		$class = 'GiveItSdk'.$this->type;

		$object = new $class($response);

		return $object;
	}

}


text:
from cyder.api.v1.endpoints.dns import api
from cyder.cydns.srv.models import SRV

class SRVSerializer(api.CommonDNSSerializer, api.LabelDomainMixin):
    class Meta(api.CommonDNSMeta):
        model = SRV

class SRVViewSet(api.CommonDNSViewSet):
    model = SRV
    serializer_class = SRVSerializer


text:
package eu.gruchala

import scala.annotation.tailrec

object OrderAirports {

  //  Having a list of airline tickets List("KRK" -> "GDN", "KTA" -> "WRO", "WRO" -> "KRK")
  // return a list specifying airport visiting order List("KTA", "WRO", "KRK", "GDN")

  def orderAirports(l: List[(String, String)]): Set[String] = {
    @tailrec
    def loop(rest: List[(String, String)], acc: Set[String]): Set[String] = rest match {
      case Nil => acc
      case (from, to) :: t =>
        val restFrom = t.map(_._1)
        val restTo = t.map(_._2)
        if (!restTo.contains(from)) {
          loop(t, acc ++ List(from, to))
        } else if (restFrom.contains(from)) {
          loop(t, acc ++ List(from, to))
        } else {
          loop(t ::: List((from, to)), acc)
        }
    }

    loop(l, Set.empty)
  }

  def orderAirports2(xs: List[(String, String)]): List[String] = {
    val srcToDst = xs.toMap

    val first = srcToDst.keySet.filterNot(v => srcToDst.values.exists(_ == v)).head

    def recurse(src: String, route: List[String]): List[String] = {
      srcToDst.get(src) match {
        case None => src :: route
        case Some(dst) => recurse(dst, src :: route)
      }
    }

    recurse(first, List.empty).reverse
  }

  println(orderAirports(List("KRK" -> "GDN", "KTA" -> "WRO", "WRO" -> "KRK")))
  println(orderAirports2(List("KRK" -> "GDN", "KTA" -> "WRO", "WRO" -> "KRK")))
}


text:
UCLASS()
class LAB_1_API AHouseActor : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	AHouseActor();

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	// Called every frame
	virtual void Tick( float DeltaSeconds ) override;

    int GetHouseIndex() const;

    void SetHouseIndex(int Index);

    bool WaitsPizzaDelivery() const;

    // Called when new order for the house is spawned.
    TSharedRef<FPizzaOrder> OrderPizzaDelivery(int OrderNumber);

    // Called when pizza is delivered.
    void OnPizzaDelivered(int OrderNumber);

    // Returns remaining time of the longest waiting order.
    UFUNCTION(BlueprintCallable, Category = Delivery)
    float GetTimeLeft() const;

    // True if timeout for at least one of the orders is reached.
    bool TimeoutReached() const;

    // Component for handling collisions.
    UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = House)
    USphereComponent* BaseCollisionComponent;

    // Component that represents house in the real world.
    UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = House)
    UStaticMeshComponent* HouseMesh;

    UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = House)
    UParticleSystemComponent *PizzaDeliveryHighlightComponent;

    // Max time the order is ready to wait.
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Delivery)
    float MaxWaitTime;

private:
    int HouseIndex;

    TArray<TSharedRef<FPizzaOrder>> PizzaOrders;

    bool bTimeoutReached;

    void TogglePizzaDeliveryHighlight();
};


text:
<?php echo $title; ?> | Admin

    <?php foreach($post as $p): ?>
    <?php echo form_open('Admin/update_post/' . $p['id']) ?>
       Title
       <input type="text" name="title" value= "<?php echo $p['title']; ?>">

       Content
       <textarea name="content"> <?php echo $p['content']; ?> </textarea>

       Categories
       <textarea name="categories"> <?php echo $p['categories']; ?> </textarea>
       <input type="submit" name="submit" value="Save">
     </form>

     <?php endforeach; ?>


text:
package com.bitdubai.fermat_api.layer.dmp_basic_wallet.discount_wallet.exceptions;

/**
 * Created by eze on 21/05/15.
 */
public class CantCalculateAvailableAmountException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 8599182580815290958L;
}


text:
<?php

namespace Drupal\block;

use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Component\Plugin\Exception\MissingValueContextException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Condition\ConditionAccessResolverTrait;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines the access control handler for the block entity type.
 *
 * @see \Drupal\block\Entity\Block
 */
class BlockAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {

  use ConditionAccessResolverTrait;

  /**
   * The plugin context handler.
   *
   * @var \Drupal\Core\Plugin\Context\ContextHandlerInterface
   */
  protected $contextHandler;

  /**
   * The context manager service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('context.handler'),
      $container->get('context.repository')
    );
  }

  /**
   * Constructs the block access control handler instance.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Plugin\Context\ContextHandlerInterface $context_handler
   *   The ContextHandler for applying contexts to conditions properly.
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The lazy context repository service.
   */
  public function __construct(EntityTypeInterface $entity_type, ContextHandlerInterface $context_handler, ContextRepositoryInterface $context_repository) {
    parent::__construct($entity_type);
    $this->contextHandler = $context_handler;
    $this->contextRepository = $context_repository;
  }

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    /** @var \Drupal\block\BlockInterface $entity */
    if ($operation != 'view') {
      return parent::checkAccess($entity, $operation, $account);
    }

    // Don't grant access to disabled blocks.
    if (!$entity->status()) {
      return AccessResult::forbidden()->addCacheableDependency($entity);
    }
    else {
      $conditions = [];
      $missing_context = FALSE;
      $missing_value = FALSE;
      foreach ($entity->getVisibilityConditions() as $condition_id => $condition) {
        if ($condition instanceof ContextAwarePluginInterface) {
          try {
            $contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
            $this->contextHandler->applyContextMapping($condition, $contexts);
          }
          catch (MissingValueContextException $e) {
            $missing_value = TRUE;
          }
          catch (ContextException $e) {
            $missing_context = TRUE;
          }
        }
        $conditions[$condition_id] = $condition;
      }

      if ($missing_context) {
        // If any context is missing then we might be missing cacheable
        // metadata, and don't know based on what conditions the block is
        // accessible or not. Make sure the result cannot be cached.
        $access = AccessResult::forbidden()->setCacheMaxAge(0);
      }
      elseif ($missing_value) {
        // The contexts exist but have no value. Deny access without
        // disabling caching. For example the node type condition will have a
        // missing context on any non-node route like the frontpage.
        $access = AccessResult::forbidden();
      }
      elseif ($this->resolveConditions($conditions, 'and') !== FALSE) {
        // Delegate to the plugin.
        $block_plugin = $entity->getPlugin();
        try {
          if ($block_plugin instanceof ContextAwarePluginInterface) {
            $contexts = $this->contextRepository->getRuntimeContexts(array_values($block_plugin->getContextMapping()));
            $this->contextHandler->applyContextMapping($block_plugin, $contexts);
          }
          $access = $block_plugin->access($account, TRUE);
        }
        catch (MissingValueContextException $e) {
          // The contexts exist but have no value. Deny access without
          // disabling caching.
          $access = AccessResult::forbidden();
        }
        catch (ContextException $e) {
          // If any context is missing then we might be missing cacheable
          // metadata, and don't know based on what conditions the block is
          // accessible or not. Make sure the result cannot be cached.
          $access = AccessResult::forbidden()->setCacheMaxAge(0);
        }
      }
      else {
        $reason = count($conditions) > 1
          ? "One of the block visibility conditions ('%s') denied access."
          : "The block visibility condition '%s' denied access.";
        $access = AccessResult::forbidden(sprintf($reason, implode("', '", array_keys($conditions))));
      }

      $this->mergeCacheabilityFromConditions($access, $conditions);

      // Ensure that access is evaluated again when the block changes.
      return $access->addCacheableDependency($entity);
    }
  }

  /**
   * Merges cacheable metadata from conditions onto the access result object.
   *
   * @param \Drupal\Core\Access\AccessResult $access
   *   The access result object.
   * @param \Drupal\Core\Condition\ConditionInterface[] $conditions
   *   List of visibility conditions.
   */
  protected function mergeCacheabilityFromConditions(AccessResult $access, array $conditions) {
    foreach ($conditions as $condition) {
      if ($condition instanceof CacheableDependencyInterface) {
        $access->addCacheTags($condition->getCacheTags());
        $access->addCacheContexts($condition->getCacheContexts());
        $access->setCacheMaxAge(Cache::mergeMaxAges($access->getCacheMaxAge(), $condition->getCacheMaxAge()));
      }
    }
  }

}


text:
// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2015, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

//
// MEMLEAK sample source public interface:
//
//  The allocate/free wrappers for the MEMLEAK sample source are not
//  housed with the rest of the MEMLEAK code. They will be separate
//  so that they are not linked into all executables.
//
//  To avoid exposing the details of the MEMLEAK handler via global variables,
//  the following procedural interfaces are provided.
//
//

#ifndef sample_source_memleak_h
#define sample_source_memleak_h

/******************************************************************************
 * local includes
 *****************************************************************************/

#include <cct/cct.h>

/******************************************************************************
 * interface operations
 *****************************************************************************/

int hpcrun_memleak_alloc_id();
int hpcrun_memleak_active();
void hpcrun_alloc_inc(cct_node_t* node, int incr);
void hpcrun_free_inc(cct_node_t* node, int incr);

#endif // sample_source_memleak_h


text:
namespace paddle {
namespace framework {
namespace ir {

using string::PrettyLogDetail;

void CPUQuantizeSquashPass::FindNodesToKeep(
    Graph* graph,
    std::unordered_map<const Node*, int>* nodes_keep_counter) const {
  GraphPatternDetector gpd;
  patterns::DequantAny deq_any_pattern{gpd.mutable_pattern(), "deqant_any"};
  deq_any_pattern();

  int found_count = 0;
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    GET_IR_NODE_FROM_SUBGRAPH(dequant_out, dequant_out, deq_any_pattern);

    if (nodes_keep_counter->find(dequant_out) == nodes_keep_counter->end())
      (*nodes_keep_counter)[dequant_out] = 1;
    else
      (*nodes_keep_counter)[dequant_out] += 1;

    found_count++;
  };
  gpd(graph, handler);
  AddStatis(found_count);
}

void CPUQuantizeSquashPass::Squash(
    Graph* graph,
    std::unordered_map<const Node*, int>* nodes_keep_counter) const {
  GraphPatternDetector gpd;
  patterns::DequantQuantAny squash_pattern{gpd.mutable_pattern(), "squash"};
  squash_pattern();

  int found_squash_count = 0;
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    VLOG(4) << "squash requantize-quantize ops pair";

    GET_IR_NODE_FROM_SUBGRAPH(dequant_in, dequant_in, squash_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(dequant_op, dequant_op, squash_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(dequant_out, dequant_out, squash_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(quant_op, quant_op, squash_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(quant_out, quant_out, squash_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(next_op, next_op, squash_pattern);

    auto* next_op_desc = next_op->Op();
    float dequant_scale = boost::get<float>(dequant_op->Op()->GetAttr("Scale"));
    float quant_scale = boost::get<float>(quant_op->Op()->GetAttr("Scale"));
    PADDLE_ENFORCE(nodes_keep_counter->find(dequant_out) !=
                   nodes_keep_counter->end());

    // check if dequantize op should be kept or removed, decrease the counter
    bool keep_dequant = (*nodes_keep_counter)[dequant_out]-- > 1;

    if (dequant_scale == quant_scale) {
      // squash dequantize-quantize to nothing
      auto quant_out_var_name = quant_out->Name();
      auto next_op_inputs = next_op_desc->InputNames();
      for (const auto& name : next_op_inputs) {
        auto var_name = next_op_desc->Input(name)[0];
        if (var_name.compare(quant_out_var_name) == 0) {
          next_op_desc->SetInput(
              name, std::vector<std::string>({dequant_in->Name()}));
          break;
        }
      }

      if (keep_dequant)
        GraphSafeRemoveNodes(graph, {quant_op, quant_out});
      else
        GraphSafeRemoveNodes(graph,
                             {dequant_op, quant_op, dequant_out, quant_out});

      IR_NODE_LINK_TO(dequant_in, next_op);

      found_squash_count++;
    } else {
      // squash dequantize-quantize to requantize op
      OpDesc desc;
      desc.SetType("requantize");
      desc.SetInput("Input", std::vector<std::string>({dequant_in->Name()}));
      desc.SetOutput("Output", std::vector<std::string>({quant_out->Name()}));
      desc.SetAttr("Scale_in", dequant_scale);
      desc.SetAttr("Scale_out", quant_scale);

      auto requant_op = g->CreateOpNode(&desc);

      if (keep_dequant)
        GraphSafeRemoveNodes(graph, {quant_op});
      else
        GraphSafeRemoveNodes(graph, {dequant_op, quant_op, dequant_out});

      IR_NODE_LINK_TO(dequant_in, requant_op);
      IR_NODE_LINK_TO(requant_op, quant_out);

      found_squash_count++;
    }
  };
  gpd(graph, handler);
  AddStatis(found_squash_count);
  PrettyLogDetail("---    squashed %d dequantize-quantize pairs",
                  found_squash_count);
}

void CPUQuantizeSquashPass::ApplyImpl(ir::Graph* graph) const {
  PADDLE_ENFORCE(graph);
  FusePassBase::Init("cpu_quantize_squash_pass", graph);

  std::unordered_map<const Node*, int> nodes_keep_counter;
  FindNodesToKeep(graph, &nodes_keep_counter);
  Squash(graph, &nodes_keep_counter);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(cpu_quantize_squash_pass,
              paddle::framework::ir::CPUQuantizeSquashPass);


text:
class AddAmountRequestedToCases < ActiveRecord::Migration
  def change
    add_column :cases, :amount_requested, :float
  end
end


text:
#include <common.h>
#include <command.h>
#include <image.h>
#include <u-boot/zlib.h>
#include <asm/byteorder.h>
#include <asm/zimage.h>

/*cmd_boot.c*/
int do_bootm_linux(int flag, int argc, char * const argv[], bootm_headers_t *images)
{
	void		*base_ptr;
	ulong		os_data, os_len;
	image_header_t	*hdr;

#if defined(CONFIG_FIT)
	const void	*data;
	size_t		len;
#endif

	if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
		return 1;

	if (images->legacy_hdr_valid) {
		hdr = images->legacy_hdr_os;
		if (image_check_type (hdr, IH_TYPE_MULTI)) {
			/* if multi-part image, we need to get first subimage */
			image_multi_getimg (hdr, 0, &os_data, &os_len);
		} else {
			/* otherwise get image data */
			os_data = image_get_data (hdr);
			os_len = image_get_data_size (hdr);
		}
#if defined(CONFIG_FIT)
	} else if (images->fit_uname_os) {
		ret = fit_image_get_data (images->fit_hdr_os,
					images->fit_noffset_os, &data, &len);
		if (ret) {
			puts ("Can't get image data/size!\n");
			goto error;
		}
		os_data = (ulong)data;
		os_len = (ulong)len;
#endif
	} else {
		puts ("Could not find kernel image!\n");
		goto error;
	}

	base_ptr = load_zimage ((void*)os_data, os_len,
			images->rd_start, images->rd_end - images->rd_start, 0);

	if (NULL == base_ptr) {
		printf ("## Kernel loading failed ...\n");
		goto error;

	}

#ifdef DEBUG
	printf ("## Transferring control to Linux (at address %08x) ...\n",
		(u32)base_ptr);
#endif

	/* we assume that the kernel is in place */
	printf("\nStarting kernel ...\n\n");

	boot_zimage(base_ptr);
	/* does not return */

error:
	return 1;
}


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Describes the status of the production variant.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProductionVariantStatus implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The endpoint variant status which describes the current deployment stage status or operational status.
     *

     *

     *

     *

     * Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     * Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     * Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     * ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     * Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback configuration.
     *

     *

     *

     */
    private String status;
    /**
     *

     * A message that describes the status of the production variant.
     *

     */
    private String statusMessage;
    /**
     *

     * The start time of the current status change.
     *

     */
    private java.util.Date startTime;

    /**
     *

     * The endpoint variant status which describes the current deployment stage status or operational status.
     *

     *

     *

     *

     * Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     * Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     * Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     * ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     * Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback configuration.
     *

     *

     *

     *
     * @param status
     *        The endpoint variant status which describes the current deployment stage status or operational status.

     *

     *

     *

     *        Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     *        Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     *        Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     *        ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     *        Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback
     *        configuration.
     *

     *

     * @see VariantStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The endpoint variant status which describes the current deployment stage status or operational status.
     *

     *

     *

     *

     * Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     * Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     * Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     * ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     * Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback configuration.
     *

     *

     *

     *
     * @return The endpoint variant status which describes the current deployment stage status or operational
     *         status.

     *

     *

     *

     *         Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     *         Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     *         Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     *         ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     *         Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback
     *         configuration.
     *

     *

     * @see VariantStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The endpoint variant status which describes the current deployment stage status or operational status.
     *

     *

     *

     *

     * Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     * Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     * Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     * ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     * Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback configuration.
     *

     *

     *

     *
     * @param status
     *        The endpoint variant status which describes the current deployment stage status or operational status.

     *

     *

     *

     *        Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     *        Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     *        Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     *        ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     *        Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback
     *        configuration.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see VariantStatus
     */

    public ProductionVariantStatus withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The endpoint variant status which describes the current deployment stage status or operational status.
     *

     *

     *

     *

     * Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     * Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     * Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     * ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     * Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback configuration.
     *

     *

     *

     *
     * @param status
     *        The endpoint variant status which describes the current deployment stage status or operational status.

     *

     *

     *

     *        Creating: Creating inference resources for the production variant.
     *

     *

     *

     *

     *        Deleting: Terminating inference resources for the production variant.
     *

     *

     *

     *

     *        Updating: Updating capacity for the production variant.
     *

     *

     *

     *

     *        ActivatingTraffic: Turning on traffic for the production variant.
     *

     *

     *

     *

     *        Baking: Waiting period to monitor the CloudWatch alarms in the automatic rollback
     *        configuration.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see VariantStatus
     */

    public ProductionVariantStatus withStatus(VariantStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     *

     * A message that describes the status of the production variant.
     *

     *
     * @param statusMessage
     *        A message that describes the status of the production variant.
     */

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     *

     * A message that describes the status of the production variant.
     *

     *
     * @return A message that describes the status of the production variant.
     */

    public String getStatusMessage() {
        return this.statusMessage;
    }

    /**
     *

     * A message that describes the status of the production variant.
     *

     *
     * @param statusMessage
     *        A message that describes the status of the production variant.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProductionVariantStatus withStatusMessage(String statusMessage) {
        setStatusMessage(statusMessage);
        return this;
    }

    /**
     *

     * The start time of the current status change.
     *

     *
     * @param startTime
     *        The start time of the current status change.
     */

    public void setStartTime(java.util.Date startTime) {
        this.startTime = startTime;
    }

    /**
     *

     * The start time of the current status change.
     *

     *
     * @return The start time of the current status change.
     */

    public java.util.Date getStartTime() {
        return this.startTime;
    }

    /**
     *

     * The start time of the current status change.
     *

     *
     * @param startTime
     *        The start time of the current status change.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProductionVariantStatus withStartTime(java.util.Date startTime) {
        setStartTime(startTime);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus()).append(",");
        if (getStatusMessage() != null)
            sb.append("StatusMessage: ").append(getStatusMessage()).append(",");
        if (getStartTime() != null)
            sb.append("StartTime: ").append(getStartTime());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ProductionVariantStatus == false)
            return false;
        ProductionVariantStatus other = (ProductionVariantStatus) obj;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getStatusMessage() == null ^ this.getStatusMessage() == null)
            return false;
        if (other.getStatusMessage() != null && other.getStatusMessage().equals(this.getStatusMessage()) == false)
            return false;
        if (other.getStartTime() == null ^ this.getStartTime() == null)
            return false;
        if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode + ((getStatusMessage() == null) ? 0 : getStatusMessage().hashCode());
        hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
        return hashCode;
    }

    @Override
    public ProductionVariantStatus clone() {
        try {
            return (ProductionVariantStatus) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.sagemaker.model.transform.ProductionVariantStatusMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
using Xunit;

namespace AntMe.Core
{
    public class Index2Test
    {
    }
}


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

namespace CardConcepts
{
    // enumeration of the Counts that a playing card can have:
    public enum Count { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };

}


text:
using System.Linq;
using CodeModel.Builder;
using CodeModel.Conventions;
using CodeModel.Dependencies;

namespace CodeModel.Primitives.Mutators
{
    [Provide(Resources.InlinedImplementations)]
    [Need(Resources.ImplementsLink, Resources.LinkToContainer)]
    [OptionalNeed(Resources.Types, Resources.LinkToContainer, Resources.Methods, Resources.MethodCallLinks, Resources.Dependencies)]
    public class ReplaceInterfaceWithImplementation : ICompositeMutator
    {
        public void Mutate(CodeModelBuilder bulder)
        {
            bulder.RunMutator<ReplaceMethodNodes>();
            bulder.RunMutator<ReplaceTypeNodes>();
        }

        private class ReplaceMethodNodes : INodeMutator<MethodNode>
        {
            private readonly IImplementingConvention convention;

            public ReplaceMethodNodes(IImplementingConvention convention)
            {
                this.convention = convention;
            }

            public void Mutate(MethodNode node, IMutateContext context)
            {
                var containedIn = (TypeNode)node.GetContainer();

                if (containedIn.Type.IsInterface)
                {
                    return;
                }

                var implementedInterfaces = containedIn.OutboundLinks.OfType<ImplementsLink>();

                foreach (var implementedInterface in implementedInterfaces)
                {
                    if (!this.convention.ShouldInlineImplementationsFor((TypeNode) implementedInterface.Target))
                    {
                        continue;
                    }

                    var interfaceMethod = node.Method.GetImplementedMethod(((TypeNode)implementedInterface.Target).Type);

                    if (interfaceMethod != null)
                    {
                        var interfaceMethodNode = context.LookupNode<MethodNode>(MethodNode.IdFor(interfaceMethod));

                        if (interfaceMethodNode != null)
                        {
                            context.ReplaceNode(interfaceMethodNode, node);
                        }
                    }
                }
            }
        }

        private class ReplaceTypeNodes : INodeMutator<TypeNode>
        {
            private readonly IImplementingConvention convention;

            public ReplaceTypeNodes(IImplementingConvention convention)
            {
                this.convention = convention;
            }

            public void Mutate(TypeNode node, IMutateContext context)
            {
                var implements = node.OutboundLinks.OfType<ImplementsLink>().ToList();

                foreach (var implement in implements)
                {
                    if (!this.convention.ShouldInlineImplementationsFor((TypeNode)implement.Target))
                    {
                        continue;
                    }

                    var target = implement.Target;
                    context.RemoveLink(implement);
                    context.ReplaceNode(target, node);
                }
            }
        }
    }
}


text:
import {} from 'jest'

import { Notification } from '../src/index'

describe('Notification', () => {
  describe('Generic', () => {
    let notify: Notification = new Notification('info', 'Notify test')

    it('should set message to "Notify test"', () => {
      expect(notify.getMessage()).toEqual('Notify test')
    })
    it('should have no options', () => {
      expect(notify.getOptions()).toEqual({})
    })
    it('should have timestamp set', () => {
      expect(notify.getTimestamp()).toEqual(expect.any(Date))
    })
    it('shouldn\'t be disaplyed', () => {
      expect(notify.wasDisplayed()).toBeFalsy()
    })
    it('shouldn\'t be dismissable', () => {
      expect(notify.isDismissable()).toBeFalsy()
    })
    it('shouldn\'t be dismissed', () => {
      expect(notify.isDismissed()).toBeFalsy()
    })
  })
  describe('Success', () => {
    const notify = new Notification('success', 'Notify test')
    it('should set state to success', () => {
      expect(notify.getState()).toEqual('success')
    })
  })
  describe('Info', () => {
    const notify = new Notification('info', 'Notify test')
    it('should set state to info', () => {
      expect(notify.getState()).toEqual('info')
    })
  })
  describe('Warning', () => {
    const notify = new Notification('warning', 'Notify test')
    it('should set state to warning', () => {
      expect(notify.getState()).toEqual('warning')
    })
  })
  describe('Error', () => {
    const notify = new Notification('error', 'Notify test')
    it('should set state to error', () => {
      expect(notify.getState()).toEqual('error')
    })
  })
  describe('Fatal', () => {
    const notify = new Notification('fatal', 'Notify test')
    it('should set state to fatal', () => {
      expect(notify.getState()).toEqual('fatal')
    })
  })
})


text:
extern crate protobuf; // depend on rust-protobuf runtime

mod mesos;     // protobuf messages
mod native;    // scheduler and executor native hooks
mod scheduler;
mod scheduler_driver;
mod executor;
mod executor_driver;
mod utils;


text:
package org.smartloli.kafka.eagle.web.sso.pojo;

import org.apache.shiro.authc.AuthenticationToken;

/**
 * Authority and login check entity.
 *
 * @author smartloli.
 *
 *         Created by May 17, 2017
 */
@SuppressWarnings("unused")
public class SSOAuthenticationToken implements AuthenticationToken {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private int code;
	private String realName = "";
	private String userName = "";
	private String email = "";

	public SSOAuthenticationToken() {
	}

	public SSOAuthenticationToken(int code, String realName, String userName, String email) {
		this.code = code;
		this.realName = realName;
		this.userName = userName;
		this.email = email;
	}

	@Override
	public Object getPrincipal() {
		return code;
	}

	@Override
	public Object getCredentials() {
		return code;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

}


text:
package com.mercadopago.android.px.internal.features.bank_deals;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import com.mercadopago.android.px.R;
import com.mercadopago.android.px.internal.adapters.BankDealsAdapter;
import com.mercadopago.android.px.internal.base.PXActivity;
import com.mercadopago.android.px.internal.callbacks.OnSelectedCallback;
import com.mercadopago.android.px.internal.di.Session;
import com.mercadopago.android.px.internal.features.bank_deal_detail.BankDealDetailActivity;
import com.mercadopago.android.px.internal.util.ApiUtil;
import com.mercadopago.android.px.internal.util.ErrorUtil;
import com.mercadopago.android.px.internal.util.ViewUtils;
import com.mercadopago.android.px.model.BankDeal;
import com.mercadopago.android.px.model.exceptions.MercadoPagoError;
import java.util.List;

public class BankDealsActivity extends PXActivity<BankDealsPresenter> implements BankDeals.View {

    public static void start(@NonNull final Activity activity) {
        final Intent intent = new Intent(activity, BankDealsActivity.class);
        activity.startActivity(intent);
    }

    public static void start(@NonNull final Activity activity, final int requestCode) {
        final Intent intent = new Intent(activity, BankDealsActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    protected RecyclerView bankDealsRecyclerView;
    protected Toolbar toolbar;

    @Override
    protected void onCreated(@Nullable final Bundle savedInstanceState) {
        setContentView(R.layout.px_activity_bank_deals);
        initializeControls();
        createPresenter();
        presenter.initialize();
    }

    private void createPresenter() {
        final Session session = Session.getInstance();
        presenter = new BankDealsPresenter(session.getBankDealsRepository());
        presenter.attachView(this);
    }

    protected void initializeControls() {
        initializeToolbar();
        bankDealsRecyclerView = findViewById(R.id.mpsdkBankDealsList);
        bankDealsRecyclerView.setHasFixedSize(true);
        bankDealsRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    }

    private void initializeToolbar() {
        toolbar = findViewById(R.id.mpsdkToolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (requestCode == ErrorUtil.ERROR_REQUEST_CODE) {
            presenter.attachView(this);
            if (resultCode == Activity.RESULT_OK) {
                presenter.recoverFromFailure();
            } else {
                finishWithCancelResult();
            }
        }
    }

    private void finishWithCancelResult() {
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    public void showApiExceptionError(@NonNull final MercadoPagoError error) {
        ErrorUtil.showApiExceptionError(this,
            error.getApiException(),
            ApiUtil.RequestOrigin.GET_BANK_DEALS);
    }

    @Override
    public void showLoadingView() {
        ViewUtils.showProgressLayout(this);
    }

    @Override
    public void showBankDeals(@NonNull final List<BankDeal> bankDeals,
        @NonNull final OnSelectedCallback<BankDeal> onSelectedCallback) {
        initializeAdapter(bankDeals, onSelectedCallback);
        ViewUtils.showRegularLayout(this);
    }

    private void initializeAdapter(@NonNull final List<BankDeal> bankDeals,
        @NonNull final OnSelectedCallback<BankDeal> onSelectedCallback) {
        final BankDealsAdapter bankDealsAdapter = new BankDealsAdapter(bankDeals, onSelectedCallback);
        bankDealsRecyclerView.setAdapter(bankDealsAdapter);
    }

    @Override
    public void showBankDealDetail(@NonNull final BankDeal bankDeal) {
        BankDealDetailActivity.startWithBankDealLegals(this, bankDeal);
    }
}


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

namespace Gear.Geometry
{
    /// <summary>
    /// Represents a 2x2 matrix.
    /// </summary>
    public class Matrix2
    {
    }
}


text:
package org.powertac.visualizer.service;

import org.powertac.visualizer.config.audit.AuditEventConverter;
import org.powertac.visualizer.repository.PersistenceAuditEventRepository;
import java.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * Service for managing audit events.
 * <p>
 * This is the default implementation to support SpringBoot Actuator AuditEventRepository
 * </p>
 */
@Service
@Transactional
public class AuditEventService {

    private final PersistenceAuditEventRepository persistenceAuditEventRepository;

    private final AuditEventConverter auditEventConverter;

    public AuditEventService(
        PersistenceAuditEventRepository persistenceAuditEventRepository,
        AuditEventConverter auditEventConverter) {

        this.persistenceAuditEventRepository = persistenceAuditEventRepository;
        this.auditEventConverter = auditEventConverter;
    }

    public Page<AuditEvent> findAll(Pageable pageable) {
        return persistenceAuditEventRepository.findAll(pageable)
            .map(auditEventConverter::convertToAuditEvent);
    }

    public Page<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable) {
        return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
            .map(auditEventConverter::convertToAuditEvent);
    }

    public Optional<AuditEvent> find(Long id) {
        return Optional.ofNullable(persistenceAuditEventRepository.findById(id))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .map(auditEventConverter::convertToAuditEvent);
    }
}


text:
package edu.wustl.catissuecore.action;

import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.wustl.catissuecore.actionForm.OrderForm;
import edu.wustl.catissuecore.actionForm.OrderSpecimenForm;
import edu.wustl.catissuecore.bizlogic.OrderBizLogic;
import edu.wustl.catissuecore.util.OrderingSystemUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.factory.AbstractFactoryConfig;
import edu.wustl.common.factory.IFactory;
import edu.wustl.common.util.logger.Logger;

/**
 * @author renuka_bajpai
 *
 */
public class OrderSpecimenInitAction extends BaseAction
{

	/**
	 * logger.
	 */
	private transient final Logger logger = Logger.getCommonLogger(OrderSpecimenInitAction.class);

	/**
	 * @param mapping ActionMapping object
	 * @param form ActionForm object
	 * @param request HttpServletRequest object
	 * @param response HttpServletResponse object
	 * @return ActionForward object
	 * @throws Exception object
	 */
	@Override
	public ActionForward executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		final OrderSpecimenForm spec = (OrderSpecimenForm) form;
		final HttpSession session = request.getSession();
		spec.setTypeOfSpecimen("existingSpecimen");
		String target = null;

		if (session.getAttribute("OrderForm") != null)
		{
			final OrderForm orderForm = (OrderForm) session.getAttribute("OrderForm");
			spec.setOrderForm(orderForm);
			if (orderForm.getDistributionProtocol() != null)
			{
				this.getProtocolName(request, spec, orderForm);
			}

			final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
			final OrderBizLogic orderBizLogic = (OrderBizLogic) factory
					.getBizLogic(Constants.REQUEST_LIST_FILTERATION_FORM_ID);
			final Collection specimen = orderBizLogic.getSpecimenDataFromDatabase(request);

			try
			{
				request.setAttribute("specimen", specimen);

				OrderingSystemUtil.setSpecimenTypeAndClass(request);

				//default checked on existing specimen
				spec.setTypeOfSpecimen("existingSpecimen");

			}

			catch (final Exception excp)
			{
				this.logger.error(excp.getMessage(), excp);
			}

			request.setAttribute("typeOf", "specimen");
			request.setAttribute("OrderSpecimenForm", spec);

			final List defineArraysList = OrderingSystemUtil.getDefinedArraysList(session);
			//Add the collection in request scope to be used in the OrderItem.jsp
			request.setAttribute(Constants.ORDERTO_LIST_ARRAY, defineArraysList);

			target = Constants.SUCCESS;
		}
		else
		{
			target = Constants.FAILURE;
		}
		return mapping.findForward(target);
	}

	/** function for getting protocol name.
	 * @param request HttpServletRequest object
	 * @param spec OrderSpecimenForm object
	 * @param orderForm OrderForm object
	 * @throws Exception object
	 */
	private void getProtocolName(HttpServletRequest request, OrderSpecimenForm spec,
			OrderForm orderForm) throws Exception
	{
		final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
		final OrderBizLogic orderBizLogic = (OrderBizLogic) factory
				.getBizLogic(Constants.REQUEST_LIST_FILTERATION_FORM_ID);
		final List protocolList = orderBizLogic.getDistributionProtocol(request);

		for (int i = 0; i < protocolList.size(); i++)
		{
			final NameValueBean obj = (NameValueBean) protocolList.get(i);
			String distributionProtocol = orderForm.getDistributionProtocol();
			if(orderForm.getDistributionProtocol().lastIndexOf("(")!= -1)
			{
				distributionProtocol = distributionProtocol.substring(0,distributionProtocol.lastIndexOf("("));
			}

			if (distributionProtocol.equals(obj.getName()) && !distributionProtocol.equals("-- Select --"))
			{
				spec.setDistrbutionProtocol(obj.getName());
				orderForm.setDistributionProtocol(obj.getValue());
			}
		}
	}

	/** function for getting data from database
	 * @param request HttpServletRequest object
	 * @return List of specimen objects
	 * @throws BizLogicException
	 */

}


text:
package ru.fitgraph.database.entities;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import ru.fitgraph.database.marshals.BirthDateJsonSerializer;

import javax.persistence.*;
import javax.xml.bind.annotation.*;
import java.util.*;

/**
 * Entity class for storing users.
 *
 * @author Morgen Matvey
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@Entity
@Table(name = "users", indexes = {
})
@NamedQueries({
        @NamedQuery(name = "User.getUserByName", query = "select user from User user where user.username = :username"),
        @NamedQuery(name = "User.getUserByVkId", query = "select user from User user where user.vkUserId = :vkId"),
        @NamedQuery(name = "User.getUserByEmail", query = "select user from User user where user.email = :email"),
        @NamedQuery(name = "User.getUserBySessionSecret", query = "select session.owner " +
                "from User user, UserSession session " +
                "where session.sessionSecret = :sessionSecret " +
                "and session.expiresIn > CURRENT_TIMESTAMP"),
        @NamedQuery(name = "User.getUserByVkIdAndSessionSecret", query = "select user " +
                "from User user, UserSession sessions where " +
                "user.vkUserId = :vkId and sessions.sessionSecret = :secret " +
                "and sessions.expiresIn > CURRENT_TIMESTAMP")
})
public class User {
    /**
     * Enum type which represent available state of sex field.
     */
    @XmlType(name = "sex")
    @XmlEnum
    public enum Sex {
        @XmlEnumValue("0") Undefined,
        @XmlEnumValue("1") Female,
        @XmlEnumValue("2") Male,
    }

    /**
     * Unique id field
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId = null;

    /**
     * Full name of user
     */
    @XmlElement
    @Column(name = "username", unique = true, nullable = false)
    private String username;

    /**
     * Users vk id of
     */
    @Column(name = "vk_user_id", unique = true, nullable = false)
    private Long vkUserId;

    /**
     * Vk access token, associated with user
     */
    @Column(name = "access_token")
    private String accessToken;

    /**
     * Users email
     */
    @XmlElement
    @Column(name = "user_email", unique = true, nullable = false)
    private String email;

    /**
     * Is user male, female or other?
     */
    @XmlElement
    @Column(name = "sex")
    private Sex sex;

    /**
     * Birth date, stored day, month and year always midnight in servers time zone as unix timestamp.
     * Serialized to json as dd.MM.yyyy {@link java.util.SimpleTimeZone}
     */
    @XmlElement
    @JsonSerialize(using = BirthDateJsonSerializer.class)
    @Column(name = "birth_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date birthDate;

    /**
     * Virtual field, list which contain all success auth sessions opened by user.
     * Field is virtual, link to user is made by column in {@link UserSession} class.
     */
    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
    @MapKeyColumn(name = "session_secret", insertable = false, updatable = false)
    private Map<String, UserSession> sessions = new HashMap<String, UserSession>();

    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
    @MapKeyColumn(name = "p_id", insertable = false, updatable = false)
    List<WeightPoint> weightPoint = new ArrayList<WeightPoint>();

    /**
     * Default constructor
     */
    public User() {
    }

    /**
     * Create user with specified username
     * @param username users full name.
     */
    public User(String username) {
        this.username = username;
    }

    /**
     * Create user with specified username and email.
     * @param username users full name.
     * @param email users email.
     */
    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    /**
     * Create user with full profile, and add first session for him. This constructor should be used
     * when we user register himself.
     * @param username users full name.
     * @param email users email.
     * @param sex users sex.
     * @param birthDate users date of birth.
     * @param vkUserId user id in vk service.
     * @param sessionSecret session id which user provide.
     * @param accessToken access token returned from vk service.
     * @param expiresIn time of vk sessions life in milliseconds.
     */
    public User(String username, String email, Sex sex, Date birthDate,
                Long vkUserId, String sessionSecret, String accessToken, Long expiresIn) {
        this.username = username;
        this.email = email;
        this.sex = sex;
        this.birthDate = birthDate;
        this.vkUserId = vkUserId;
        this.accessToken = accessToken;

        UserSession firstSession = new UserSession(this, sessionSecret, expiresIn);
        this.sessions.put(firstSession.getSessionSecret(), firstSession);
    }

    /**
     * Add or update (if session with same session secret already exist) user session to list of users sessions as is.
     * After using this method, user session owner field
     * must be managed manually.
     * @param session session object.
     */
    public void addSession(UserSession session) {
        if(sessions.containsKey(session.getSessionSecret()))
            sessions.get(session.getSessionSecret()).setExpiresIn(session.getExpiresIn());
        else
            sessions.put(session.getSessionSecret(), session);
    }

    /**
     * Save new user session opened for user or update session if session with specified session secret already opened.
     * Allow auth user with provided data.
     * @param sessionSecret session id or other secret string used for identity user.
     * @param accessToken access token received from vk.
     * @param expiresIn time that the session is valid in milliseconds.
     */
    public void addSession(String sessionSecret, String accessToken, Long expiresIn) {
        this.accessToken = accessToken;
        if(sessions.containsKey(sessionSecret)) { // Already opened session, update it
            UserSession session = sessions.get(sessionSecret);
            session.setExpiresIn(expiresIn);
        } else { // New session, create it
            UserSession firstSession = new UserSession(this, sessionSecret, expiresIn);
            this.sessions.put(firstSession.getSessionSecret(), firstSession);
        }
    }

    /**
     * Create new weight point and associate it with user.
     * @param date date when weight was seen.
     * @param weight weight in kilograms.
     */
    public void addWeightPoint(Date date, Double weight) {
        WeightPoint newWeightPoint = new WeightPoint(date, weight, this);
        weightPoint.add(newWeightPoint);
    }

    /**
     * Associate weight point with user
     * @param point point which should be associated.
     */
    public void addWeightPoint(WeightPoint point) {
        point.setOwner(this);
        weightPoint.add(point);
    }

    public Long getUserId() {
        return userId;
    }

    public String getUsername() {
        return username;
    }

    public Long getVkUserId() {
        return vkUserId;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public String getEmail() {
        return email;
    }

    public Map<String, UserSession> getSessions() {
        return sessions;
    }

    public Sex getSex() {
        return sex;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public List<WeightPoint> getWeightPoints() {
        return weightPoint;
    }
}