text:
package com.opengamma.sesame.equityindexoptions;

import java.util.LinkedHashMap;

import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.opengamma.analytics.financial.equity.EquityDerivativeSensitivityCalculator;
import com.opengamma.analytics.financial.equity.EquityOptionBlackPresentValueCalculator;
import com.opengamma.analytics.financial.equity.EquityOptionBlackSpotDeltaCalculator;
import com.opengamma.analytics.financial.equity.EquityOptionBlackSpotGammaCalculator;
import com.opengamma.analytics.financial.equity.EquityOptionBlackVegaCalculator;
import com.opengamma.analytics.financial.equity.StaticReplicationDataBundle;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitorAdapter;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.SimpleParameterSensitivity;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.financial.analytics.DoubleLabelledMatrix1D;
import com.opengamma.financial.analytics.conversion.EquityOptionsConverter;
import com.opengamma.financial.analytics.model.fixedincome.BucketedCurveSensitivities;
import com.opengamma.financial.security.option.EquityIndexOptionSecurity;
import com.opengamma.sesame.CurveMatrixLabeller;
import com.opengamma.sesame.Environment;
import com.opengamma.sesame.equity.StaticReplicationDataBundleFn;
import com.opengamma.sesame.trade.EquityIndexOptionTrade;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.CurrencyAmount;
import com.opengamma.util.result.FailureStatus;
import com.opengamma.util.result.Result;
import com.opengamma.util.tuple.Pairs;

/**
 * Default implementation of the {@link EquityIndexOptionFn}.
 */
public class DefaultEquityIndexOptionFn implements EquityIndexOptionFn {

  public static final double BP = 0.0001;
  private StaticReplicationDataBundleFn _dataProviderFn;
  private static final EquityOptionBlackPresentValueCalculator PV_CALC = EquityOptionBlackPresentValueCalculator.getInstance();

  private static final EquityOptionBlackSpotDeltaCalculator DELTA_CALC = EquityOptionBlackSpotDeltaCalculator.getInstance();
  private static final EquityOptionBlackSpotGammaCalculator GAMMA_CALC = EquityOptionBlackSpotGammaCalculator.getInstance();
  private static final EquityOptionBlackVegaCalculator VEGA_CALC = EquityOptionBlackVegaCalculator.getInstance();
  private static final EquityDerivativeSensitivityCalculator SENSITIVITY_CALC = new EquityDerivativeSensitivityCalculator(PV_CALC);

  /**
   * Constructs a function to calculate values for a equity index option.
   * @param dataProviderFn data provider bundle.
   */
  public DefaultEquityIndexOptionFn(StaticReplicationDataBundleFn dataProviderFn) {
    _dataProviderFn = ArgumentChecker.notNull(dataProviderFn, "dataProviderFn");
  }

  @Override
  public Result<CurrencyAmount> calculatePv(Environment env, EquityIndexOptionTrade trade) {
    Result<Double> result = calculateResult(env, trade, PV_CALC);
    if (result.isSuccess()) {
      CurrencyAmount amount = CurrencyAmount.of(trade.getSecurity().getCurrency(), result.getValue());
      return Result.success(amount);
    } else {
      return Result.failure(result);
    }
  }

  @Override
  public Result<Double> calculateDelta(Environment env, EquityIndexOptionTrade trade) {
    return calculateResult(env, trade, DELTA_CALC);
  }

  @Override
  public Result<Double> calculateGamma(Environment env, EquityIndexOptionTrade trade) {
    Result<StaticReplicationDataBundle> dataResult = _dataProviderFn.getEquityIndexDataProvider(env, trade);
    if (dataResult.isSuccess()) {
      // Gamma should be multiply by spot underlying
      double spot = dataResult.getValue().getForwardCurve().getSpot() / 100;
      Result<Double> result = calculateResult(env, trade, GAMMA_CALC);
      if (result.isSuccess()) {
        return Result.success(result.getValue() * spot);
      } else {
        return Result.failure(result);
      }
    } else {
      return Result.failure(dataResult);
    }
  }

  @Override
  public Result<Double> calculateVega(Environment env, EquityIndexOptionTrade trade) {
    Result<Double> result = calculateResult(env, trade, VEGA_CALC);
    if (result.isSuccess()) {
      // Vega should be divided 100
      return Result.success(result.getValue() / 100);
    } else {
      return Result.failure(result);
    }
  }

  @Override
  public Result<Double> calculatePv01(Environment env, EquityIndexOptionTrade trade) {
    Result<StaticReplicationDataBundle> dataResult = _dataProviderFn.getEquityIndexDataProvider(env, trade);
    if (Result.allSuccessful(dataResult)) {
      StaticReplicationDataBundle bundle = dataResult.getValue();
      InstrumentDerivative derivative = createInstrumentDerivative(trade, env.getValuationTime());
      return Result.success(SENSITIVITY_CALC.calcPV01(derivative, bundle));
    } else {
      return Result.failure(dataResult);
    }
  }

  @Override
  public Result<BucketedCurveSensitivities> calculateBucketedPv01(Environment env, EquityIndexOptionTrade trade) {
    Result<StaticReplicationDataBundle> dataResult = _dataProviderFn.getEquityIndexDataProvider(env, trade);
    if (Result.allSuccessful(dataResult)) {
      StaticReplicationDataBundle bundle = dataResult.getValue();
      InstrumentDerivative derivative = createInstrumentDerivative(trade, env.getValuationTime());
      DoubleMatrix1D deltaBucketed = SENSITIVITY_CALC.calcDeltaBucketed(derivative, bundle);
      YieldAndDiscountCurve discountCurve = bundle.getDiscountCurve();

      if (discountCurve instanceof YieldCurve) {
        Currency currency = trade.getSecurity().getCurrency();
        String name = discountCurve.getName();
        Double[] tenors = ((YieldCurve) discountCurve).getCurve().getXData();
        ImmutableList.Builder<String> dayBuilder = ImmutableList.builder();

        for (double tenor : tenors) {
          String day = Math.round(tenor * 365) + "D";
          dayBuilder.add(day);
        }

        LinkedHashMap<String, DoubleMatrix1D> map = new LinkedHashMap<>();
        map.put(name, deltaBucketed);
        SimpleParameterSensitivity sensitivity = new SimpleParameterSensitivity(map);
        CurveMatrixLabeller labeller = new CurveMatrixLabeller(dayBuilder.build());
        DoubleLabelledMatrix1D doubleLabelledMatrix1D =
            labeller.labelMatrix(sensitivity.multipliedBy(BP).getSensitivity(name));
        ImmutableMap.of(Pairs.of(name, currency), doubleLabelledMatrix1D);
        return Result.success(BucketedCurveSensitivities.of(ImmutableMap.of(Pairs.of(name, currency),
                                                                            doubleLabelledMatrix1D)));
      } else {
        return Result.failure(FailureStatus.INVALID_INPUT, "Can only handle YieldCurve instances of YieldAndDiscountCurve");
      }

    } else {
      return Result.failure(dataResult);
    }
  }

  private Result<Double> calculateResult(Environment env,
                                         EquityIndexOptionTrade trade,
                                         InstrumentDerivativeVisitorAdapter<StaticReplicationDataBundle, Double> calculator) {
    Result<StaticReplicationDataBundle> dataResult = _dataProviderFn.getEquityIndexDataProvider(env, trade);
    if (Result.allSuccessful(dataResult)) {
      StaticReplicationDataBundle bundle = dataResult.getValue();
      InstrumentDerivative derivative = createInstrumentDerivative(trade, env.getValuationTime());
      return Result.success(derivative.accept(calculator, bundle));
    } else {
      return Result.failure(dataResult);
    }

  }

  private InstrumentDerivative createInstrumentDerivative(EquityIndexOptionTrade tradeWrapper, ZonedDateTime valTime) {
    EquityOptionsConverter converter = new EquityOptionsConverter();
    EquityIndexOptionSecurity security = tradeWrapper.getSecurity();
    InstrumentDefinition<?> definition = security.accept(converter);
    return definition.toDerivative(valTime);
  }

}


text:
from PIL import Image
from PIL._util import isPath
import io
import logging
import os
import sys
import struct

logger = logging.getLogger(__name__)

MAXBLOCK = 65536

SAFEBLOCK = 1024*1024

LOAD_TRUNCATED_IMAGES = False

ERRORS = {
    -1: "image buffer overrun error",
    -2: "decoding error",
    -3: "unknown error",
    -8: "bad configuration",
    -9: "out of memory error"
}

def raise_ioerror(error):
    try:
        message = Image.core.getcodecstatus(error)
    except AttributeError:
        message = ERRORS.get(error)
    if not message:
        message = "decoder error %d" % error
    raise IOError(message + " when reading image file")

#
# --------------------------------------------------------------------
# Helpers

def _tilesort(t):
    # sort on offset
    return t[2]

#
# --------------------------------------------------------------------
# ImageFile base class

class ImageFile(Image.Image):
    "Base class for image file format handlers."

    def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1  # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if isPath(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except (IndexError,  # end of data
                TypeError,  # end of data (ord)
                KeyError,  # unsupported mode
                EOFError,  # got header but not the first frame
                struct.error) as v:
            logger.exception("%s")
            raise SyntaxError(v)

        if not self.mode or self.size[0] <= 0:
            raise SyntaxError("not identified by this driver")

    def draft(self, mode, size):
        "Set draft mode"

        pass

    def verify(self):
        "Check file integrity"

        # raise exception if something's wrong.  must be called
        # directly after open, and closes file when finished.
        self.fp = None

    def load(self):
        "Load image data based on tile list"

        pixel = Image.Image.load(self)

        if self.tile is None:
            raise IOError("cannot load this image")
        if not self.tile:
            return pixel

        self.map = None
        use_mmap = self.filename and len(self.tile) == 1
        # As of pypy 2.1.0, memory mapping was failing here.
        use_mmap = use_mmap and not hasattr(sys, 'pypy_version_info')

        readonly = 0

        # look for read/seek overrides
        try:
            read = self.load_read
            # don't use mmap if there are custom read/seek functions
            use_mmap = False
        except AttributeError:
            read = self.fp.read

        try:
            seek = self.load_seek
            use_mmap = False
        except AttributeError:
            seek = self.fp.seek

        if use_mmap:
            # try memory mapping
            d, e, o, a = self.tile[0]
            if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES:
                try:
                    if hasattr(Image.core, "map"):
                        # use built-in mapper
                        self.map = Image.core.map(self.filename)
                        self.map.seek(o)
                        self.im = self.map.readimage(
                            self.mode, self.size, a[1], a[2]
                            )
                    else:
                        # use mmap, if possible
                        import mmap
                        fp = open(self.filename, "r+")
                        size = os.path.getsize(self.filename)
                        # FIXME: on Unix, use PROT_READ etc
                        self.map = mmap.mmap(fp.fileno(), size)
                        self.im = Image.core.map_buffer(
                            self.map, self.size, d, e, o, a
                            )
                    readonly = 1
                except (AttributeError, EnvironmentError, ImportError):
                    self.map = None

        self.load_prepare()

        if not self.map:
            # sort tiles in file order
            self.tile.sort(key=_tilesort)

            try:
                # FIXME: This is a hack to handle TIFF's JpegTables tag.
                prefix = self.tile_prefix
            except AttributeError:
                prefix = b""

            for d, e, o, a in self.tile:
                d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
                seek(o)
                try:
                    d.setimage(self.im, e)
                except ValueError:
                    continue
                b = prefix
                while True:
                    try:
                        s = read(self.decodermaxblock)
                    except (IndexError, struct.error):  # truncated png/gif
                        if LOAD_TRUNCATED_IMAGES:
                            break
                        else:
                            raise IOError("image file is truncated")

                    if not s and not d.handles_eof:  # truncated jpeg
                        self.tile = []

                        # JpegDecode needs to clean things up here either way
                        # If we don't destroy the decompressor,
                        # we have a memory leak.
                        d.cleanup()

                        if LOAD_TRUNCATED_IMAGES:
                            break
                        else:
                            raise IOError("image file is truncated "
                                          "(%d bytes not processed)" % len(b))

                    b = b + s
                    n, e = d.decode(b)
                    if n < 0:
                        break
                    b = b[n:]
                # Need to cleanup here to prevent leaks in PyPy
                d.cleanup()

        self.tile = []
        self.readonly = readonly

        self.fp = None  # might be shared

        if not self.map and not LOAD_TRUNCATED_IMAGES and e < 0:
            # still raised if decoder fails to return anything
            raise_ioerror(e)

        # post processing
        if hasattr(self, "tile_post_rotate"):
            # FIXME: This is a hack to handle rotated PCD's
            self.im = self.im.rotate(self.tile_post_rotate)
            self.size = self.im.size

        self.load_end()

        return Image.Image.load(self)

    def load_prepare(self):
        # create image memory if necessary
        if not self.im or\
           self.im.mode != self.mode or self.im.size != self.size:
            self.im = Image.core.new(self.mode, self.size)
        # create palette (optional)
        if self.mode == "P":
            Image.Image.load(self)

    def load_end(self):
        # may be overridden
        pass

    # may be defined for contained formats
    # def load_seek(self, pos):
    #     pass

    # may be defined for blocked formats (e.g. PNG)
    # def load_read(self, bytes):
    #     pass

class StubImageFile(ImageFile):
    """
    Base class for stub image loaders.

    A stub loader is an image loader that can identify files of a
    certain format, but relies on external code to load the file.
    """

    def _open(self):
        raise NotImplementedError(
            "StubImageFile subclass must implement _open"
            )

    def load(self):
        loader = self._load()
        if loader is None:
            raise IOError("cannot find loader for this %s file" % self.format)
        image = loader.load(self)
        assert image is not None
        # become the other object (!)
        self.__class__ = image.__class__
        self.__dict__ = image.__dict__

    def _load(self):
        "(Hook) Find actual image loader."
        raise NotImplementedError(
            "StubImageFile subclass must implement _load"
            )

class Parser(object):
    """
    Incremental image parser.  This class implements the standard
    feed/close consumer interface.

    In Python 2.x, this is an old-style class.
    """
    incremental = None
    image = None
    data = None
    decoder = None
    offset = 0
    finished = 0

    def reset(self):
        """
        (Consumer) Reset the parser.  Note that you can only call this
        method immediately after you've created a parser; parser
        instances cannot be reused.
        """
        assert self.data is None, "cannot reuse parsers"

    def feed(self, data):
        """
        (Consumer) Feed data to the parser.

        :param data: A string buffer.
        :exception IOError: If the parser failed to parse the image file.
        """
        # collect data

        if self.finished:
            return

        if self.data is None:
            self.data = data
        else:
            self.data = self.data + data

        # parse what we have
        if self.decoder:

            if self.offset > 0:
                # skip header
                skip = min(len(self.data), self.offset)
                self.data = self.data[skip:]
                self.offset = self.offset - skip
                if self.offset > 0 or not self.data:
                    return

            n, e = self.decoder.decode(self.data)

            if n < 0:
                # end of stream
                self.data = None
                self.finished = 1
                if e < 0:
                    # decoding error
                    self.image = None
                    raise_ioerror(e)
                else:
                    # end of image
                    return
            self.data = self.data[n:]

        elif self.image:

            # if we end up here with no decoder, this file cannot
            # be incrementally parsed.  wait until we've gotten all
            # available data
            pass

        else:

            # attempt to open this file
            try:
                try:
                    fp = io.BytesIO(self.data)
                    im = Image.open(fp)
                finally:
                    fp.close()  # explicitly close the virtual file
            except IOError:
                # traceback.print_exc()
                pass  # not enough data
            else:
                flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
                if flag or len(im.tile) != 1:
                    # custom load code, or multiple tiles
                    self.decode = None
                else:
                    # initialize decoder
                    im.load_prepare()
                    d, e, o, a = im.tile[0]
                    im.tile = []
                    self.decoder = Image._getdecoder(
                        im.mode, d, a, im.decoderconfig
                        )
                    self.decoder.setimage(im.im, e)

                    # calculate decoder offset
                    self.offset = o
                    if self.offset <= len(self.data):
                        self.data = self.data[self.offset:]
                        self.offset = 0

                self.image = im

    def close(self):
        """
        (Consumer) Close the stream.

        :returns: An image object.
        :exception IOError: If the parser failed to parse the image file either
                            because it cannot be identified or cannot be
                            decoded.
        """
        # finish decoding
        if self.decoder:
            # get rid of what's left in the buffers
            self.feed(b"")
            self.data = self.decoder = None
            if not self.finished:
                raise IOError("image was incomplete")
        if not self.image:
            raise IOError("cannot parse this image")
        if self.data:
            # incremental parsing not possible; reopen the file
            # not that we have all data
            try:
                fp = io.BytesIO(self.data)
                self.image = Image.open(fp)
            finally:
                self.image.load()
                fp.close()  # explicitly close the virtual file
        return self.image

# --------------------------------------------------------------------

def _save(im, fp, tile, bufsize=0):
    """Helper to save image based on tile list

    :param im: Image object.
    :param fp: File object.
    :param tile: Tile list.
    :param bufsize: Optional buffer size
    """

    im.load()
    if not hasattr(im, "encoderconfig"):
        im.encoderconfig = ()
    tile.sort(key=_tilesort)
    # FIXME: make MAXBLOCK a configuration parameter
    # It would be great if we could have the encoder specify what it needs
    # But, it would need at least the image size in most cases. RawEncode is
    # a tricky case.
    bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4)  # see RawEncode.c
    if fp == sys.stdout:
        fp.flush()
        return
    try:
        fh = fp.fileno()
        fp.flush()
    except (AttributeError, io.UnsupportedOperation):
        # compress to Python file-compatible object
        for e, b, o, a in tile:
            e = Image._getencoder(im.mode, e, a, im.encoderconfig)
            if o > 0:
                fp.seek(o, 0)
            e.setimage(im.im, b)
            while True:
                l, s, d = e.encode(bufsize)
                fp.write(d)
                if s:
                    break
            if s < 0:
                raise IOError("encoder error %d when writing image file" % s)
            e.cleanup()
    else:
        # slight speedup: compress to real file object
        for e, b, o, a in tile:
            e = Image._getencoder(im.mode, e, a, im.encoderconfig)
            if o > 0:
                fp.seek(o, 0)
            e.setimage(im.im, b)
            s = e.encode_to_file(fh, bufsize)
            if s < 0:
                raise IOError("encoder error %d when writing image file" % s)
            e.cleanup()
    if hasattr(fp, "flush"):
        fp.flush()

def _safe_read(fp, size):
    """
    Reads large blocks in a safe way.  Unlike fp.read(n), this function
    doesn't trust the user.  If the requested size is larger than
    SAFEBLOCK, the file is read block by block.

    :param fp: File handle.  Must implement a read method.
    :param size: Number of bytes to read.
    :returns: A string containing up to size bytes of data.
    """
    if size <= 0:
        return b""
    if size <= SAFEBLOCK:
        return fp.read(size)
    data = []
    while size > 0:
        block = fp.read(min(size, SAFEBLOCK))
        if not block:
            break
        data.append(block)
        size -= len(block)
    return b"".join(data)

redpajama_set_name: RedPajamaGithub


text:
package com.code.hacks.codered.evnts.evnts.bean;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

/**
 * Created by sandeep on 11/22/2015.
 */
public class Comments {
    @SerializedName("comments")
    ArrayList<Comment> comments;

    public Comments(ArrayList<Comment> comments) {
        this.comments = comments;
    }

    public ArrayList<Comment> getComments() {
        return comments;
    }

    public void setComments(ArrayList<Comment> comments) {
        this.comments = comments;
    }
}


text:
layout: post
title:  "exactly once"
date:   2017-11-06 21:51:37
categories: tools
excerpt: "Apache Kafka's approach to an old problem"
tags:
  - streaming
  - kafka
  - java
---

Some notes I took while watching [*Introducing Exactly Once Semantics*](https://www.confluent.io/thank-you/introducing-exactly-semantics-apache-kafka/) talk, presented by Apurva Mehta of Confluent.

#### 1) Idempotent Producer
* `producer.send` will always lead to one copy in the log
* not in the consumer - you can still consume a message multiple times

Done with configuration:
{% highlight bash %}
enable.idempotence = true
max.inflight.requests.per.connection = 1
acks = all
retries = MAX_INT
{% endhighlight %}

How is this done?  Metadata on each message.
* producer ID (assigned by the broker)
* sequence ID for the message - producer and topic leader agree.  valid for the producer session only.
* this metadata is kept in the log (enabling resilience around changing leaders for example)
* If producer doesn't get an ack, it resends the message.  If broker has already processed the message, it just sends an `ack` without writing it to the log

#### 2) Transaction API

New components in the Kafka ecosystem

* Transaction coordinator - maintains transaction state on a per-producer basis.  Runs within broker.
* Transaction log - persists the state

Producer side:
{% highlight java %}
producer.initTransactions()
  // register transactional.id with the transaction coordinator component
  // resolve outstanding transactions before accepting new messages
  // done once when producer comes online
producer.beginTransaction()
  // a producer can be part of only one transaction at a time
producer.send()
  // partitions are registered with the Transaction coordinator
  // data is written to the log as usual
producer.commitTransaction()
  // two phase commit - 1) producer sends a commit RPC to the Transaction coordinator
  // 2) Transaction coordinator writes transaction "commit markers" to the data logs
{% endhighlight %}

Consumers can `read_committed` or `read_uncommitted` which is a configuration

Messages are still in offset order.  Transaction order can differ but is invisible to consumers.


text:
layout: default
permalink: /confirmation/contact/
---

Thanks for contacting us

Your message was successfully recieved. Someone will take a look at it
          shortly and get back to you. Thanks!


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Encyclop. Mycol. 297 (1938)

#### Original name
Mycena arcangeliana var. oortiana Kühner, 1938

### Remarks
null


text:
// The WordAltList abstracts a alternate list of words and their corresponding
// costs that result from the word recognition process. The class inherits
// from the AltList class
// It provides methods to add a new word alternate, its corresponding score and
// a tag.

#ifndef WORD_ALT_LIST_H
#define WORD_ALT_LIST_H

#include "altlist.h"

namespace tesseract {
class WordAltList : public AltList {
 public:
  explicit WordAltList(int max_alt);
  ~WordAltList();
  // Sort the list of alternates based on cost
  void Sort();
  // insert an alternate word with the specified cost and tag
  bool Insert(char_32 *char_ptr, int cost, void *tag = NULL);
  // returns the alternate string at the specified position
  inline char_32 * Alt(int alt_idx) { return word_alt_[alt_idx]; }
  // print each entry of the altlist, both UTF8 and unichar ids, and
  // their costs, to stderr
  void PrintDebug();
 private:
  char_32 **word_alt_;
};
}  // namespace tesseract

#endif  // WORD_ALT_LIST_H


text:
module Uber
  class Time < Base
    attr_accessor :product_id, :display_name, :estimate
  end
end


text:
from .... import on_appengine
from django.core.exceptions import ImproperlyConfigured

if on_appengine:
    from google.storage.speckle.python.django.backend.base import *
else:
    raise ImproperlyConfigured(
        "Using remote CloudSQL as a local backend. Check your settings.py file."
    )


text:
external help file: ValidationLib-help.xml
Module Name: PowerShell-Lib
online version: https://github.com/Dargmuesli/PowerShell-Lib/blob/master/PowerShell-Lib/Docs/Test-CountValid.md
schema: 2.0.0
---

# Test-CountValid

## SYNOPSIS
Checks whether the count of a variable's values is in a specified range.

## SYNTAX

```
Test-CountValid [-Variable] <Array> [-Min] <Int32> [-Max] <Int32> [<CommonParameters>]
```

## DESCRIPTION
The "Test-CountValid" cmdlet checks if the count of a variable's values is in a specified range and returns true on success.

## EXAMPLES

### EXAMPLE 1
```
Test-CountValid -Variable @(@(1, 2), @(3, 4)) -Min 0 -Max 2
```

## PARAMETERS

### -Variable
The variable that is to be checked.

```yaml
Type: Array
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Min
The minimum count to allow.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```

### -Max
The maximum count to allow.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: 3
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable.
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES

## RELATED LINKS

[https://github.com/Dargmuesli/PowerShell-Lib/blob/master/PowerShell-Lib/Docs/Test-CountValid.md](https://github.com/Dargmuesli/PowerShell-Lib/blob/master/PowerShell-Lib/Docs/Test-CountValid.md)


text:
#include <stdio.h>

#define __STDC_VERSION__ 199901L
#include <greatest/greatest.h>
GREATEST_MAIN_DEFS();
#undef __STDC_VERSION__

#include <astro/logging.h>
astro::log_level astro_log_verbosity = astro::log_level::debug;

#include "application_tests.h"
#include "window_tests.h"

int main(int argc, char **argv)
{
  GREATEST_MAIN_BEGIN();      /* init & parse command-line args */

  if (greatest_info.flags & GREATEST_FLAG_VERBOSE)
    astro_log_verbosity = astro::log_level::debug;

  RUN_SUITE(application_tests);
  RUN_SUITE(window_tests);
  GREATEST_MAIN_END();        /* display results */
}


text:
PointLight::PointLight()
{
    m_nType = LIGHT_POINT;

    m_arPosition[0] = 0.0f;
    m_arPosition[1] = 0.0f;
    m_arPosition[2] = 0.0f;

    m_fIntensity = 1.0f;
    m_fRadius    = 1.0f;
}

PointLight::~PointLight()
{

}

void PointLight::SetRadius(float fRadius)
{
    m_fRadius = fRadius;
}

void PointLight::SetIntensity(float fIntensity)
{
    m_fIntensity = fIntensity;
}

void PointLight::SetPosition(float fX,
                             float fY,
                             float fZ)
{
    Scene* pScene = reinterpret_cast<Scene*>(GetScene());

    // Remove the light from wherever it was in the octree
	if (pScene)
	{
		pScene->RemovePointLightFromOctree(this);
	}

    // Update the position
    m_arPosition[0] = fX;
    m_arPosition[1] = fY;
    m_arPosition[2] = fZ;

    // Update the box center
    m_box.m_arCenter[0] = fX;
    m_box.m_arCenter[1] = fY;
    m_box.m_arCenter[2] = fZ;

	if (pScene)
	{
		pScene->AddPointLightToOctree(this);
	}
}

void PointLight::SetBox(Box& box)
{
    m_box = box;
}

float PointLight::GetRadius()
{
    return m_fRadius;
}

float PointLight::GetIntensity()
{
    return m_fIntensity;
}

Box* PointLight::GetBox()
{
    return &m_box;
}

float* PointLight::GetPosition()
{
    return m_arPosition;
}

void PointLight::SetRenderState(void*        pScene,
                                unsigned int hProg)
{
    // Pointlight OpenGL State is set in Matter class
}


text:
// Copyright 2008 Google Inc.
//
// 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.gwtorm.jdbc;

import com.google.gwtorm.client.Key;
import com.google.gwtorm.schema.ColumnModel;
import com.google.gwtorm.schema.KeyModel;
import com.google.gwtorm.schema.QueryModel;
import com.google.gwtorm.schema.RelationModel;
import com.google.gwtorm.schema.Util;
import com.google.gwtorm.schema.sql.SqlDialect;
import com.google.gwtorm.server.Access;
import com.google.gwtorm.server.CodeGenSupport;
import com.google.gwtorm.server.GeneratedClassLoader;
import com.google.gwtorm.server.OrmException;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/** Generates a concrete implementation of an {@link Access} extension. */
class AccessGen implements Opcodes {
  private static final String REL_ALIAS = "T";

  private static enum DmlType {
    INSERT("bindOneInsert"),

    UPDATE("bindOneUpdate"),

    DELETE("bindOneDelete");

    final String methodName;

    DmlType(final String m) {
      methodName = m;
    }
  }

  private final GeneratedClassLoader classLoader;
  private final RelationModel model;
  private final SqlDialect dialect;

  private ClassWriter cw;
  private String superTypeName;
  private String implClassName;
  private String implTypeName;
  private Type entityType;

  AccessGen(final GeneratedClassLoader loader,
      final RelationModel rm, final SqlDialect sd) {
    classLoader = loader;
    model = rm;
    dialect = sd;
    entityType =
        Type.getObjectType(model.getEntityTypeClassName().replace('.', '/'));
  }

  public Class<?> create() throws OrmException {
    init();
    implementConstructor();
    implementGetString("getRelationName", model.getRelationName());
    implementGetString("getInsertOneSql", model.getInsertOneSql(dialect));
    implementGetRelationID();

    if (model.getPrimaryKey() != null) {
      if (model.getDependentColumns().isEmpty()) {
        implementMissingGetString("getUpdateOneSql", "update");
      } else {
        implementGetString("getUpdateOneSql", model.getUpdateOneSql(dialect));
      }
      implementGetString("getDeleteOneSql", model.getDeleteOneSql(dialect));
    } else {
      implementMissingGetString("getUpdateOneSql", "update");
      implementMissingGetString("getDeleteOneSql", "delete");
    }

    implementPrimaryKey();
    implementGetOne();
    implementNewEntityInstance();
    implementBindOne(DmlType.INSERT);
    implementBindOne(DmlType.UPDATE);
    implementBindOne(DmlType.DELETE);
    implementBindOneFetch();

    if (model.getPrimaryKey() != null) {
      implementKeyQuery(model.getPrimaryKey());
      if ((model.getPrimaryKey().getField().isNested() || !model
          .getPrimaryKey().getField().getPrimitiveType().isPrimitive())
          && model.getPrimaryKey().getAllLeafColumns().size() == 1) {
        overrideGetMany();
      }
    }

    for (final QueryModel q : model.getQueries()) {
      implementQuery(q);
    }
    implementQuery(new QueryModel(model, "iterateAllEntities", ""));

    cw.visitEnd();
    classLoader.defineClass(implClassName, cw.toByteArray());
    return loadClass();
  }

  private Class<?> loadClass() throws OrmException {
    try {
      return Class.forName(implClassName, false, classLoader);
    } catch (ClassNotFoundException err) {
      throw new OrmException("Cannot load generated class", err);
    }
  }

  private void init() {
    superTypeName = Type.getInternalName(JdbcAccess.class);
    implClassName =
        model.getEntityTypeClassName() + "_Access_" + model.getMethodName()
            + "_" + Util.createRandomName();
    implTypeName = implClassName.replace('.', '/');

    cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null,
        superTypeName, new String[] {model.getAccessInterfaceName().replace(
            '.', '/')});
  }

  private void implementConstructor() {
    final String consName = "<init>";
    final String consDesc =
        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type
            .getType(JdbcSchema.class)});
    final MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKESPECIAL, superTypeName, consName, consDesc);
    mv.visitInsn(RETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementGetString(final String methodName,
      final String returnValue) {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, methodName, Type
            .getMethodDescriptor(Type.getType(String.class), new Type[] {}),
            null, null);
    mv.visitCode();
    mv.visitLdcInsn(returnValue);
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementGetRelationID() {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getRelationID", Type
            .getMethodDescriptor(Type.INT_TYPE, new Type[] {}), null, null);
    mv.visitCode();
    new CodeGenSupport(mv).push(model.getRelationID());
    mv.visitInsn(IRETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementMissingGetString(final String methodName,
      final String why) {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, methodName, Type
            .getMethodDescriptor(Type.getType(String.class), new Type[] {}),
            null, null);
    mv.visitCode();
    throwUnsupported(mv, model.getMethodName() + " does not support " + why);
    mv.visitInsn(RETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void throwUnsupported(final MethodVisitor mv, final String message) {
    final Type eType = Type.getType(UnsupportedOperationException.class);
    mv.visitTypeInsn(NEW, eType.getInternalName());
    mv.visitInsn(DUP);
    mv.visitLdcInsn(message);
    mv.visitMethodInsn(INVOKESPECIAL, eType.getInternalName(), "<init>", Type
        .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type
            .getType(String.class)}));
    mv.visitInsn(ATHROW);
  }

  private void implementPrimaryKey() {
    final KeyModel pk = model.getPrimaryKey();
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "primaryKey", Type
            .getMethodDescriptor(Type.getType(Key.class), new Type[] {Type
                .getType(Object.class)}), null, null);
    mv.visitCode();
    if (pk != null && pk.getField().isNested()) {
      final ColumnModel pkf = pk.getField();
      mv.visitVarInsn(ALOAD, 1);
      mv.visitTypeInsn(CHECKCAST, entityType.getInternalName());
      mv.visitFieldInsn(GETFIELD, entityType.getInternalName(), pkf
          .getFieldName(), CodeGenSupport.toType(pkf).getDescriptor());
    } else {
      mv.visitInsn(ACONST_NULL);
    }
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementGetOne() {
    final KeyModel pk = model.getPrimaryKey();

    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "get", Type.getMethodDescriptor(
            Type.getType(Object.class), new Type[] {Type.getType(Key.class)}),
            null, new String[] {Type.getType(OrmException.class)
                .getInternalName()});
    mv.visitCode();
    if (pk != null && pk.getField().isNested()) {
      final Type keyType = CodeGenSupport.toType(pk.getField());
      mv.visitVarInsn(ALOAD, 0);
      mv.visitVarInsn(ALOAD, 1);
      mv.visitTypeInsn(CHECKCAST, keyType.getInternalName());
      mv.visitMethodInsn(INVOKEVIRTUAL, implTypeName, pk.getName(), Type
          .getMethodDescriptor(entityType, new Type[] {keyType}));
      mv.visitInsn(ARETURN);
    } else {
      throwUnsupported(mv, model.getMethodName() + " does not support get(Key)");
    }
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementNewEntityInstance() {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "newEntityInstance", Type
            .getMethodDescriptor(Type.getType(Object.class), new Type[] {}),
            null, null);
    mv.visitCode();
    mv.visitTypeInsn(NEW, entityType.getInternalName());
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, entityType.getInternalName(), "<init>",
        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}));
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementBindOne(final DmlType type) {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, type.methodName, Type
            .getMethodDescriptor(Type.VOID_TYPE, new Type[] {
                Type.getType(PreparedStatement.class),
                Type.getType(Object.class)}), null, new String[] {Type.getType(
            SQLException.class).getInternalName()});
    mv.visitCode();

    if (type != DmlType.INSERT && model.getPrimaryKey() == null) {
      throwUnsupported(mv, model.getMethodName() + " has no primary key");
      mv.visitInsn(RETURN);
      mv.visitMaxs(-1, -1);
      mv.visitEnd();
    }

    mv.visitVarInsn(ALOAD, 2);
    mv.visitTypeInsn(CHECKCAST, entityType.getInternalName());
    mv.visitVarInsn(ASTORE, 2);

    final CodeGenSupport cgs = new CodeGenSupport(mv);
    cgs.setEntityType(entityType);

    for (final ColumnModel col : model.getRowVersionColumns()) {
      cgs.setFieldReference(col);
      cgs.fieldSetBegin();
      cgs.pushFieldValue();
      mv.visitInsn(ICONST_1);
      mv.visitInsn(IADD);
      cgs.fieldSetEnd();
    }
    cgs.resetColumnIndex(0);

    if (type != DmlType.DELETE) {
      final List<ColumnModel> cols = new ArrayList<>();
      cols.addAll(model.getDependentFields());
      cols.addAll(model.getRowVersionFields());
      for (final ColumnModel field : cols) {
        doBindOne(mv, cgs, field);
      }
    }

    for (final ColumnModel col : model.getPrimaryKeyColumns()) {
      cgs.setFieldReference(col);
      dialect.getSqlTypeInfo(col).generatePreparedStatementSet(cgs);
    }
    if (type != DmlType.INSERT) {
      for (final ColumnModel col : model.getRowVersionColumns()) {
        cgs.setFieldReference(col);
        cgs.pushSqlHandle();
        cgs.pushColumnIndex();
        cgs.pushFieldValue();
        mv.visitInsn(ICONST_1);
        mv.visitInsn(ISUB);
        cgs.invokePreparedStatementSet("Int");
      }
    }

    mv.visitInsn(RETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void doBindOne(final MethodVisitor mv, final CodeGenSupport cgs,
      final ColumnModel field) {
    if (field.isNested() && field.isNotNull()) {
      for (final ColumnModel c : field.getAllLeafColumns()) {
        doBindOne(mv, cgs, c);
      }

    } else if (field.isNested()) {
      final int colIdx = cgs.getColumnIndex();
      final Label isnull = new Label();
      final Label end = new Label();

      cgs.setFieldReference(field);
      cgs.pushFieldValue();
      mv.visitJumpInsn(IFNULL, isnull);
      cgs.resetColumnIndex(colIdx);
      for (final ColumnModel c : field.getNestedColumns()) {
        doBindOne(mv, cgs, c);
      }
      mv.visitJumpInsn(GOTO, end);

      mv.visitLabel(isnull);
      cgs.resetColumnIndex(colIdx);
      for (final ColumnModel c : field.getAllLeafColumns()) {
        cgs.setFieldReference(c);
        dialect.getSqlTypeInfo(c).generatePreparedStatementNull(cgs);
      }

      mv.visitLabel(end);
    } else {
      cgs.setFieldReference(field);
      dialect.getSqlTypeInfo(field).generatePreparedStatementSet(cgs);
    }
  }

  private void implementBindOneFetch() {
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "bindOneFetch", Type
            .getMethodDescriptor(Type.VOID_TYPE, new Type[] {
                Type.getType(ResultSet.class), Type.getType(Object.class)}),
            null, new String[] {Type.getType(SQLException.class)
                .getInternalName()});
    mv.visitCode();

    mv.visitVarInsn(ALOAD, 2);
    mv.visitTypeInsn(CHECKCAST, entityType.getInternalName());
    mv.visitVarInsn(ASTORE, 2);

    final CodeGenSupport cgs = new CodeGenSupport(mv);
    cgs.setEntityType(entityType);

    if (model.getPrimaryKey() != null
        && model.getPrimaryKey().getField().isNested()) {
      final ColumnModel pkf = model.getPrimaryKey().getField();
      final Type vType = CodeGenSupport.toType(pkf);
      final int oldIdx = cgs.getColumnIndex();
      cgs.setFieldReference(pkf);
      cgs.fieldSetBegin();
      mv.visitTypeInsn(NEW, vType.getInternalName());
      mv.visitInsn(DUP);
      mv.visitMethodInsn(INVOKESPECIAL, vType.getInternalName(), "<init>", Type
          .getMethodDescriptor(Type.VOID_TYPE, new Type[] {}));
      cgs.fieldSetEnd();
      cgs.resetColumnIndex(oldIdx);
    }

    final List<ColumnModel> cols = new ArrayList<>();
    cols.addAll(model.getDependentFields());
    cols.addAll(model.getRowVersionFields());
    cols.addAll(model.getPrimaryKeyColumns());
    for (final ColumnModel field : cols) {
      doFetchOne(mv, cgs, field, -1);
    }

    mv.visitInsn(RETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void doFetchOne(final MethodVisitor mv, final CodeGenSupport cgs,
      final ColumnModel field, final int reportLiveInto) {
    if (field.isNested()) {
      int oldIdx = cgs.getColumnIndex();
      final Type vType = CodeGenSupport.toType(field);
      final int livecnt;

      if (field.isNotNull()) {
        livecnt = -1;
      } else {
        livecnt = cgs.newLocal();
        cgs.push(0);
        mv.visitVarInsn(ISTORE, livecnt);
      }

      cgs.setFieldReference(field);
      cgs.fieldSetBegin();
      mv.visitTypeInsn(NEW, vType.getInternalName());
      mv.visitInsn(DUP);
      mv.visitMethodInsn(INVOKESPECIAL, vType.getInternalName(), "<init>", Type
          .getMethodDescriptor(Type.VOID_TYPE, new Type[] {}));
      cgs.fieldSetEnd();

      cgs.resetColumnIndex(oldIdx);
      for (final ColumnModel c : field.getNestedColumns()) {
        doFetchOne(mv, cgs, c, livecnt);
      }

      if (livecnt >= 0) {
        oldIdx = cgs.getColumnIndex();

        final Label islive = new Label();
        mv.visitVarInsn(ILOAD, livecnt);
        mv.visitJumpInsn(IFNE, islive);
        cgs.setFieldReference(field);
        cgs.fieldSetBegin();
        mv.visitInsn(ACONST_NULL);
        cgs.fieldSetEnd();

        if (reportLiveInto >= 0) {
          final Label end = new Label();
          mv.visitJumpInsn(GOTO, end);
          mv.visitLabel(islive);
          mv.visitIincInsn(reportLiveInto, 1);
          mv.visitLabel(end);
        } else {
          mv.visitLabel(islive);
        }

        cgs.resetColumnIndex(oldIdx);
        cgs.freeLocal(livecnt);
      }

    } else {
      final int dupTo;
      if (reportLiveInto >= 0
          && CodeGenSupport.toType(field).getSort() == Type.OBJECT) {
        dupTo = cgs.newLocal();
      } else {
        dupTo = -1;
      }

      cgs.setFieldReference(field);
      cgs.setDupOnFieldSetEnd(dupTo);
      dialect.getSqlTypeInfo(field).generateResultSetGet(cgs);

      if (reportLiveInto >= 0) {
        final Label wasnull = new Label();
        if (dupTo >= 0) {
          mv.visitVarInsn(ALOAD, dupTo);
          mv.visitJumpInsn(IFNULL, wasnull);
          cgs.freeLocal(dupTo);
        } else {
          cgs.pushSqlHandle();
          mv.visitMethodInsn(INVOKEINTERFACE, Type.getType(ResultSet.class)
              .getInternalName(), "wasNull", Type.getMethodDescriptor(
              Type.BOOLEAN_TYPE, new Type[] {}));
          mv.visitJumpInsn(IFNE, wasnull);
        }
        mv.visitIincInsn(reportLiveInto, 1);
        mv.visitLabel(wasnull);
      }
    }
  }

  private void implementKeyQuery(final KeyModel info) {
    final Type keyType = CodeGenSupport.toType(info.getField());
    final StringBuilder query = new StringBuilder();
    query.append(model.getSelectSql(dialect, REL_ALIAS));
    query.append(" WHERE ");
    int nth = 1;
    for (final Iterator<ColumnModel> i = info.getAllLeafColumns().iterator(); i
        .hasNext();) {
      final ColumnModel c = i.next();
      query.append(REL_ALIAS);
      query.append('.');
      query.append(c.getColumnName());
      query.append('=');
      query.append(dialect.getParameterPlaceHolder(nth++));
      if (i.hasNext()) {
        query.append(" AND ");
      }
    }

    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, info.getName(), Type
            .getMethodDescriptor(entityType, new Type[] {keyType}), null,
            new String[] {Type.getType(OrmException.class).getInternalName()});
    mv.visitCode();

    final int keyvar = 1, psvar = keyvar + keyType.getSize();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitLdcInsn(query.toString());
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareStatement", Type
        .getMethodDescriptor(Type.getType(PreparedStatement.class),
            new Type[] {Type.getType(String.class)}));
    mv.visitVarInsn(ASTORE, psvar);

    final CodeGenSupport cgs = new CodeGenSupport(mv) {
      @Override
      public void pushSqlHandle() {
        mv.visitVarInsn(ALOAD, psvar);
      }

      @Override
      public void pushFieldValue() {
        appendGetField(getFieldReference());
      }

      @Override
      protected void appendGetField(final ColumnModel c) {
        if (c.getParent() == null) {
          loadVar(keyType, keyvar);
        } else {
          super.appendGetField(c);
        }
      }
    };
    for (final ColumnModel c : info.getAllLeafColumns()) {
      cgs.setFieldReference(c);
      dialect.getSqlTypeInfo(c).generatePreparedStatementSet(cgs);
    }

    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, psvar);
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryOne", Type
        .getMethodDescriptor(Type.getType(Object.class), new Type[] {Type
            .getType(PreparedStatement.class)}));
    mv.visitTypeInsn(CHECKCAST, entityType.getInternalName());
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void overrideGetMany() {
    final KeyModel pk = model.getPrimaryKey();
    final StringBuilder query = new StringBuilder();
    query.append(model.getSelectSql(dialect, REL_ALIAS));
    query.append(" WHERE ");
    final ColumnModel pkcol = pk.getAllLeafColumns().iterator().next();
    query.append(REL_ALIAS);
    query.append('.');
    query.append(pkcol.getColumnName());
    query.append(" IN");

    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getBySqlIn", Type
            .getMethodDescriptor(Type
                .getType(com.google.gwtorm.server.ResultSet.class),
                new Type[] {Type.getType(Collection.class)}), null,
            new String[] {Type.getType(OrmException.class).getInternalName()});
    mv.visitCode();

    final int keyset = 1;
    final int psvar = 2;
    final int itrvar = 3;
    final int colvar = 4;
    final int keyvar = 5;

    mv.visitVarInsn(ALOAD, 0);
    mv.visitLdcInsn(query.toString());
    mv.visitVarInsn(ALOAD, keyset);
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareBySqlIn", Type
        .getMethodDescriptor(Type.getType(PreparedStatement.class), new Type[] {
            Type.getType(String.class), Type.getType(Collection.class)}));
    mv.visitVarInsn(ASTORE, psvar);

    mv.visitVarInsn(ALOAD, keyset);
    mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Collection.class),
        "iterator", Type.getMethodDescriptor(Type.getType(Iterator.class),
            new Type[] {}));
    mv.visitVarInsn(ASTORE, itrvar);

    mv.visitInsn(ICONST_1);
    mv.visitVarInsn(ISTORE, colvar);

    final Label endbind = new Label();
    final Label again = new Label();
    mv.visitLabel(again);
    mv.visitVarInsn(ALOAD, itrvar);
    mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Iterator.class),
        "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {}));
    mv.visitJumpInsn(IFEQ, endbind);

    mv.visitVarInsn(ALOAD, itrvar);
    mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Iterator.class),
        "next", Type.getMethodDescriptor(Type.getType(Object.class),
            new Type[] {}));
    mv.visitTypeInsn(CHECKCAST, CodeGenSupport.toType(pk.getField())
        .getInternalName());
    mv.visitVarInsn(ASTORE, keyvar);

    final CodeGenSupport cgs = new CodeGenSupport(mv) {
      @Override
      public void pushSqlHandle() {
        mv.visitVarInsn(ALOAD, psvar);
      }

      @Override
      public void pushFieldValue() {
        appendGetField(getFieldReference());
      }

      @Override
      public void pushColumnIndex() {
        mv.visitVarInsn(ILOAD, colvar);
      }

      @Override
      protected void appendGetField(final ColumnModel c) {
        if (c.getParent() == null) {
          mv.visitVarInsn(ALOAD, keyvar);
        } else {
          super.appendGetField(c);
        }
      }
    };

    cgs.setFieldReference(pkcol);
    dialect.getSqlTypeInfo(pkcol).generatePreparedStatementSet(cgs);
    mv.visitIincInsn(colvar, 1);
    mv.visitJumpInsn(GOTO, again);

    mv.visitLabel(endbind);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, psvar);
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryList", Type
        .getMethodDescriptor(Type.getType(com.google.gwtorm.server.ResultSet.class),
            new Type[] {Type.getType(PreparedStatement.class)}));
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }

  private void implementQuery(final QueryModel info) {
    final List<ColumnModel> pCols = info.getParameters();
    final boolean hasLimitParam = info.hasLimitParameter();
    final Type[] pTypes = new Type[pCols.size() + (hasLimitParam ? 1 : 0)];
    final int[] pVars = new int[pTypes.length];
    int nextVar = 1;
    for (int i = 0; i < pCols.size(); i++) {
      pTypes[i] = CodeGenSupport.toType(pCols.get(i));
      pVars[i] = nextVar;
      nextVar += pTypes[i].getSize();
    }
    if (hasLimitParam) {
      pTypes[pTypes.length - 1] = Type.INT_TYPE;
      pVars[pTypes.length - 1] = nextVar;
      nextVar += Type.INT_TYPE.getSize();
    }

    final int psvar = nextVar++;
    final MethodVisitor mv =
        cw.visitMethod(ACC_PUBLIC | ACC_FINAL, info.getName(), Type
            .getMethodDescriptor(Type
                .getType(com.google.gwtorm.server.ResultSet.class), pTypes),
            null, new String[] {Type.getType(OrmException.class)
                .getInternalName()});
    mv.visitCode();

    mv.visitVarInsn(ALOAD, 0);
    mv.visitLdcInsn(info.getSelectSql(dialect, REL_ALIAS));
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareStatement", Type
        .getMethodDescriptor(Type.getType(PreparedStatement.class),
            new Type[] {Type.getType(String.class)}));
    mv.visitVarInsn(ASTORE, psvar);

    final int argIdx[] = new int[] {0};
    final CodeGenSupport cgs = new CodeGenSupport(mv) {
      @Override
      public void pushSqlHandle() {
        mv.visitVarInsn(ALOAD, psvar);
      }

      @Override
      public void pushFieldValue() {
        appendGetField(getFieldReference());
      }

      @Override
      protected void appendGetField(final ColumnModel c) {
        final int n = argIdx[0];
        if (c == pCols.get(n)) {
          loadVar(pTypes[n], pVars[n]);
        } else {
          super.appendGetField(c);
        }
      }
    };
    for (final ColumnModel c : pCols) {
      if (c.isNested()) {
        for (final ColumnModel n : c.getAllLeafColumns()) {
          cgs.setFieldReference(n);
          dialect.getSqlTypeInfo(n).generatePreparedStatementSet(cgs);
        }
      } else {
        cgs.setFieldReference(c);
        dialect.getSqlTypeInfo(c).generatePreparedStatementSet(cgs);
      }
      argIdx[0]++;
    }

    if (info.hasLimit()) {
      if (hasLimitParam || !dialect.selectHasLimit()) {
        mv.visitVarInsn(ALOAD, psvar);
        if (hasLimitParam) {
          if (dialect.selectHasLimit()) {
            CodeGenSupport cgs2 = new CodeGenSupport(mv) {
              @Override
              public void pushSqlHandle() {
                mv.visitVarInsn(ALOAD, psvar);
              }

              @Override
              public void pushFieldValue() {
                final int n = argIdx[0];
                loadVar(pTypes[n], pVars[n]);
              }
            };
            cgs2.resetColumnIndex(cgs.getColumnIndex() + 1);
            dialect.getSqlTypeInfo(Integer.TYPE).generatePreparedStatementSet(cgs2);
          }
          mv.visitVarInsn(ILOAD, pVars[pTypes.length - 1]);
        } else {
          cgs.push(info.getStaticLimit());
        }
        mv.visitMethodInsn(INVOKEINTERFACE, Type.getType(
            PreparedStatement.class).getInternalName(), "setMaxRows", Type
            .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE}));
      }
    }

    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, psvar);
    mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryList", Type
        .getMethodDescriptor(Type.getType(com.google.gwtorm.server.ResultSet.class),
            new Type[] {Type.getType(PreparedStatement.class)}));
    mv.visitInsn(ARETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
  }
}


text:
package org.apache.axis.encoding.ser;

import javax.xml.namespace.QName;
import java.beans.IntrospectionException;
import java.lang.reflect.Method;

import org.apache.axis.utils.cache.MethodCache;

/**
 * Deserializer for a JAX-RPC enum.
 *
 * @author Rich Scheuerle (scheu@us.ibm.com)
 * @author Sam Ruby (rubys@us.ibm.com)
 */
public class EnumDeserializer extends SimpleDeserializer {

    private Method fromStringMethod = null;

    private static final Class[] STRING_CLASS = new Class[] { java.lang.String.class };

    public EnumDeserializer(Class javaType, QName xmlType) {
        super(javaType, xmlType);
    }

    public Object makeValue(String source) throws Exception
    {
        // Invoke the fromString static method to get the Enumeration value
        if (isNil)
            return null;
        if (fromStringMethod == null) {
            try {
                fromStringMethod = MethodCache.getInstance().getMethod(javaType, "fromString", STRING_CLASS);
            } catch (Exception e) {
                throw new IntrospectionException(e.toString());
            }
        }
        return fromStringMethod.invoke(null,new Object [] { source });
    }
}


text:
'use strict';

var request = require('supertest')
	, should = require('should')
	, redisService = require('../../lib/redis')
	, app = require('../../app').app;

describe('Test postcode api', function() {

	var url_postcode_list = '/public/postcode';
	var token_id = 'f2cb3e8d653f46008272113c6c72422843901ef3';

	describe('Test get postcode list by pages: GET->' + url_postcode_list, function() {
		var email = 'mary@demo.org';

		beforeEach(function(done) {
			var record = [token_id, 'email', email, 'role', 1];
			redisService.save(token_id, record, function(err, reply){
				console.log(reply.toString());
				done();
			});
		});

		afterEach(function(done){
			redisService.remove(token_id, function(err, reply){
				console.log(reply.toString());
				done();
			});
		});
		/**
		 * [0] = A0A0A0, [last] = G6E1J3
		 * [0] = A0A0A0, [99] = A0B2B0
		 * [100] = A0B2C0, [199] = A0E2J0
		 * Sort direction can be 1 (ascending) or -1 (descending)
		 * mongo query string:
		 * db.postcode.find().sort({postcode:1}).limit(100)
		 * db.postcode.find().limit(100).sort({postcode:1})
		 */
		it('request should return 100 results with first page', function(done) {
			request(app)
			.get(url_postcode_list + '?s=100&f=postcode&d=1&tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.lengthOf(100);
				res.body[0].postcode.should.equal('A0A0A0');
				res.body[99].postcode.should.equal('A0B2B0');
				if (err) return done(err);
				done();
			});
		});

		it('request should return 100 results with 2nd page', function(done) {
			request(app)
			.get(url_postcode_list + '?s=100&f=postcode&d=1&c=A0B2B0&tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.lengthOf(100);
				res.body[0].postcode.should.equal('A0B2C0');
				res.body[99].postcode.should.equal('A0E2J0');
				if (err) return done(err);
				done();
			});
		});

		it('request should return 100 results with 1st page in reverse direction', function(done) {
			request(app)
			.get(url_postcode_list + '?s=100&f=postcode&d=-1&tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.lengthOf(100);
				res.body[0].postcode.should.equal('G6E1J3');
				if (err) return done(err);
				done();
			});
		});
	});
});


text:
import Posts from "meteor/vulcan:posts";
import Categories from "./collection.js";
import { addCallback, Utils } from 'meteor/vulcan:core';

// add callback that adds categories CSS classes
function addCategoryClass (postClass, post) {
  var classArray = _.map(Posts.getCategories(post), function (category){return "category-"+category.slug;});
  return postClass + " " + classArray.join(' ');
}
addCallback("postClass", addCategoryClass);

// ------- Categories Check -------- //

// make sure all categories in the post.categories array exist in the db
var checkCategories = function (post) {

  // if there are no categories, stop here
  if (!post.categories || post.categories.length === 0) {
    return;
  }

  // check how many of the categories given also exist in the db
  var categoryCount = Categories.find({_id: {$in: post.categories}}).count();

  if (post.categories.length !== categoryCount) {
    throw new Error({id: 'categories.invalid'});
  }
};

function postsNewCheckCategories (post) {
  checkCategories(post);
  return post;
}
addCallback("posts.new.sync", postsNewCheckCategories);

function postEditCheckCategories (modifier) {
  checkCategories(modifier.$set);
  return modifier;
}
addCallback("posts.edit.sync", postEditCheckCategories);

function categoriesNewGenerateSlug (category) {
  // if no slug has been provided, generate one
  const slug = category.slug || Utils.slugify(category.name);
  category.slug = Utils.getUnusedSlug(Categories, slug);
  return category;
}
addCallback("categories.new.sync", categoriesNewGenerateSlug);

function categoriesEditGenerateSlug (modifier, document) {
  // if slug is changing
  if (modifier.$set && modifier.$set.slug && modifier.$set.slug !== document.slug) {
    const slug = modifier.$set.slug;
    modifier.$set.slug = Utils.getUnusedSlug(Categories, slug);
  }
  return modifier;
}
addCallback("categories.edit.sync", categoriesEditGenerateSlug);

// TODO: debug this

// function addParentCategoriesOnSubmit (post) {
//   var categories = post.categories;
//   var newCategories = [];
//   if (categories) {
//     categories.forEach(function (categoryId) {
//       var category = Categories.findOne(categoryId);
//       newCategories = newCategories.concat(_.pluck(category.getParents().reverse(), "_id"));
//       newCategories.push(category._id);
//     });
//   }
//   post.categories = _.unique(newCategories);
//   return post;
// }
// addCallback("posts.new.sync", addParentCategoriesOnSubmit);

// function addParentCategoriesOnEdit (modifier, post) {
//   if (modifier.$unset && modifier.$unset.categories !== undefined) {
//     return modifier;
//   }

//   var categories = modifier.$set.categories;
//   var newCategories = [];
//   if (categories) {
//     categories.forEach(function (categoryId) {
//       var category = Categories.findOne(categoryId);
//       newCategories = newCategories.concat(_.pluck(category.getParents().reverse(), "_id"));
//       newCategories.push(category._id);
//     });
//   }
//   modifier.$set.categories = _.unique(newCategories);
//   return modifier;
// }
// addCallback("posts.edit.sync", addParentCategoriesOnEdit);


text:
package com.intellij.dupLocator;

import com.intellij.DynamicBundle;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;

import java.util.function.Supplier;

public class DupLocatorBundle extends DynamicBundle {
  @NonNls private static final String BUNDLE = "messages.DupLocatorBundle";

  private static final DupLocatorBundle INSTANCE = new DupLocatorBundle();

  private DupLocatorBundle() {
    super(BUNDLE);
  }

  @NotNull
  public static String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getMessage(key, params);
  }

  @NotNull
  public static Supplier<String> lazyMessage(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getLazyMessage(key, params);
  }
}


text:
<ly-carousel
  [withClass]="classes.carousel"
  touch
  hasProgressBar
  pauseOnHover
>
  <ly-carousel-item
    *ngFor="let item of items"
    [withClass]="classes.carouselItem"
    [srcImg]="item.img"
  >
    <h1 [lyTyp]="'headline'" gutter>{{ item.title }}</h1>
    <p [lyTyp]="'body1'" gutter>
      Lorem ipsum dolor sit amet consectetur adipisicing elit.
    </p>
  </ly-carousel-item>
</ly-carousel>


text:
using System;
using System.ComponentModel;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Xpo;
using DevExpress.ExpressApp.Win;
using System.Collections.Generic;
using DevExpress.ExpressApp.Updating;
//using DevExpress.ExpressApp.Security;

namespace XafWithAspNetCustomIdentity.Win
{
    // For more typical usage scenarios, be sure to check out http://documentation.devexpress.com/#Xaf/DevExpressExpressAppWinWinApplicationMembersTopicAll
    public partial class XafWithAspNetCustomIdentityWindowsFormsApplication : WinApplication
    {
        public XafWithAspNetCustomIdentityWindowsFormsApplication()
        {
            InitializeComponent();
        }

        protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args)
        {
            args.ObjectSpaceProvider = new XPObjectSpaceProvider(args.ConnectionString, args.Connection);
        }
        private void XafWithAspNetCustomIdentityWindowsFormsApplication_CustomizeLanguagesList(object sender, CustomizeLanguagesListEventArgs e)
        {
            string userLanguageName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            if (userLanguageName != "en-US" && e.Languages.IndexOf(userLanguageName) == -1)
            {
                e.Languages.Add(userLanguageName);
            }
        }
        private void XafWithAspNetCustomIdentityWindowsFormsApplication_DatabaseVersionMismatch(object sender, DevExpress.ExpressApp.DatabaseVersionMismatchEventArgs e)
        {
#if EASYTEST
            e.Updater.Update();
            e.Handled = true;
#else
            if (System.Diagnostics.Debugger.IsAttached)
            {
                e.Updater.Update();
                e.Handled = true;
            }
            else
            {
                throw new InvalidOperationException(
                    "The application cannot connect to the specified database, because the latter doesn't exist or its version is older than that of the application.\r\n" +
                    "This error occurred  because the automatic database update was disabled when the application was started without debugging.\r\n" +
                    "To avoid this error, you should either start the application under Visual Studio in debug mode, or modify the " +
                    "source code of the 'DatabaseVersionMismatch' event handler to enable automatic database update, " +
                    "or manually create a database using the 'DBUpdater' tool.\r\n" +
                    "Anyway, refer to the 'Update Application and Database Versions' help topic at http://www.devexpress.com/Help/?document=ExpressApp/CustomDocument2795.htm " +
                    "for more detailed information. If this doesn't help, please contact our Support Team at http://www.devexpress.com/Support/Center/");
            }
#endif
        }
    }
}


text: Dash


text:
from __future__ import annotations

import io
from contextlib import redirect_stdout

import pytest

from .conftest import DebugMode
from .test_git import wd as wd_fixture  # NOQA evil fixture reuse
from .wd_wrapper import WorkDir
from setuptools_scm._cli import main

PYPROJECT_TOML = "pyproject.toml"
PYPROJECT_SIMPLE = "[tool.setuptools_scm]"
PYPROJECT_ROOT = '[tool.setuptools_scm]\nroot=".."'

def get_output(args: list[str]) -> str:

    with redirect_stdout(io.StringIO()) as out:
        main(args)
    return out.getvalue()

def test_cli_find_pyproject(
    wd: WorkDir, monkeypatch: pytest.MonkeyPatch, debug_mode: DebugMode
) -> None:
    debug_mode.disable()
    wd.commit_testfile()
    wd.write(PYPROJECT_TOML, PYPROJECT_SIMPLE)
    monkeypatch.chdir(wd.cwd)

    out = get_output([])
    assert out.startswith("0.1.dev1+")

    with pytest.raises(SystemExit, match="no version found for"):
        get_output(["--root=.."])

    wd.write(PYPROJECT_TOML, PYPROJECT_ROOT)
    with pytest.raises(SystemExit, match="no version found for"):
        print(get_output(["-c", PYPROJECT_TOML]))

    with pytest.raises(SystemExit, match="no version found for"):

        get_output(["-c", PYPROJECT_TOML, "--root=.."])

    with pytest.warns(UserWarning, match="root .. is overridden by the cli arg ."):
        out = get_output(["-c", PYPROJECT_TOML, "--root=."])
    assert out.startswith("0.1.dev1+")


text:
<?php

declare(strict_types=1);

namespace BEAR\Resource\Module;

use BEAR\Resource\ImportApp;
use BEAR\Resource\ResourceInterface;
use FakeVendor\Sandbox\Module\AppModule;
use PHPUnit\Framework\TestCase;
use Ray\Di\Injector;

class ImportModuleTest extends TestCase
{
    protected function setUp() : void
    {
        $rm = function ($dir) use (&$rm) {
            foreach ((array) glob($dir . '/*') as $f) {
                $file = (string) $f;
                is_dir($file) ? $rm($file) : unlink($file);
                @rmdir($file);
            }
        };
        $tmpDir = dirname(__DIR__, 2) . '/tests/Fake/FakeVendor/Blog/var/tmp';
        $rm($tmpDir);
        file_put_contents($tmpDir . '/tmp.text', '1');
        parent::setUp();
    }

    public function testConfigure()
    {
        $module = new AppModule;
        $importConfig = [
            new ImportApp('blog', 'FakeVendor\Blog', 'app')
        ];
        $module->override(new ImportAppModule($importConfig));
        $resource = (new Injector($module, __DIR__ . '/tmp'))->getInstance(ResourceInterface::class);
        // request
        $news = $resource
            ->get
            ->uri('app://self/news')
            ->withQuery(['date' => 'today'])
            ->request();
        $expect = '{
    "weather": {
        "today": "the weather of today is sunny"
    },
    "headline": "40th anniversary of Rubik\'s Cube invention.",
    "sports": "Pieter Weening wins Giro d\'Italia.",
    "user": {
        "id": 2,
        "name": "Aramis",
        "age": 16,
        "blog_id": 12
    }
}
';
        $this->assertSame($expect, (string) $news);

        $news = $resource
            ->get
            ->uri('app://blog/news')
            ->withQuery(['date' => 'today'])
            ->request();
        $expect = '{
    "weather": {
        "today": "the weather of today is sunny"
    },
    "technology": "Microsoft to stop producing Windows versions",
    "user": {
        "id": 3,
        "name": "Porthos",
        "age": 17,
        "blog_id": 0
    }
}
';
        $this->assertSame($expect, (string) $news);
    }
}


text:
var Home;
(function (Home) {
    'use strict';
    var HomeCtrl = (function () {
        function HomeCtrl() {
        }
        return HomeCtrl;
    })();
    Home.HomeCtrl = HomeCtrl;
})(Home || (Home = {}));


text:
<?php

namespace Comite\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\Session\Container;

use Sistema\Model\Entity\PartidaMantTable;
use Sistema\Model\Entity\CicloAdminTable;

class MantencionesController extends AbstractActionController

{
    public function indexAction()

    {
        //Cargamos Layout
        $this->layout('layout/comite');
        return new ViewModel();
    }

   public function relojesAction()
    {
        //Conectamos con BBDD
        $sid = new Container('base');
        $db_name = $sid->offsetGet('dbNombre');
        $this->dbAdapter=$this->getServiceLocator()->get($db_name);
        //Instancias
        $part = new PartidaMantTable($this->dbAdapter);
        $cicl = new CicloAdminTable($this->dbAdapter);
        //Obtenemos Dia y Hora de cierre Administrativo
        $cierre = $cicl->getCiclo();
        $hora_cierre = substr($cierre[0]['hora'],0,-3);
        //Obtenemos dias de meses a usar
        $dias_mes = cal_days_in_month(CAL_GREGORIAN, date('n'), date('Y'));
        $dias_mes2 = cal_days_in_month(CAL_GREGORIAN, date('n')+1, date('Y'));
        $dias_mes3 = cal_days_in_month(CAL_GREGORIAN, date('n')+2, date('Y'));
        //Horas restantes del dia
        $dif_diaria = (24-date('G'))*3600;
            //Validamos dia y calculamos segundos restantes
            if(date('j')>$cierre[0]['dia']){
              $dif = (((($dias_mes-date('j'))+$cierre[0]['dia'])*86400)-((24-$hora_cierre)*3600)-1)-$dif_diaria;
            }else{
              $dif = ((($cierre[0]['dia']-date('j'))*86400)+$dif_diaria) - ((24-$hora_cierre)*3600) - 1 ;
            }
        //Consultamos Partidas de cada Mes
        $partidas = $part->getPartidasMes($this->dbAdapter,date('M'));
        $partidas2 = $part->getPartidasMes($this->dbAdapter,date('M'));
        $partidas3 = $part->getPartidasMes($this->dbAdapter,date('M',strtotime('+2 month',strtotime(date('M')))));
        //Calculamos segundos de meses proximos
        $dif2 = $dif+($dias_mes2*86400)-((24-$hora_cierre)*3600)-$dif_diaria-1;
        $dif3 = $dif+$dif2+($dias_mes3*86400)-((24-$hora_cierre)*3600)-$dif_diaria-1;
        $this->layout('layout/comite');
        $result = new ViewModel(array(
                                'partidas'=>$partidas,
                                'partidas2'=>$partidas2,
                                'partidas3'=>$partidas3,
                                'segundos'=>$dif,
                                'segundos2'=>$dif2,
                                'segundos3'=>$dif3
                                ));
       // $result->setTerminal(true);

        return $result;
    }

    public function calendarioAction()
    {   //Conectamos con BBDD
        $sid = new Container('base');
        $db_name = $sid->offsetGet('dbNombre');
        $this->dbAdapter=$this->getServiceLocator()->get($db_name);
        //Instancias
        $part = new PartidaMantTable($this->dbAdapter);
        //Consultamos Partidas
        $partidas = $part->getPartidas();

        //Retornamos a la vista
        $this->layout('layout/comite');
        $result = new ViewModel(array('partidas'=>$partidas));
        //$result->setTerminal(true);

        return $result;
    }
    public function asambleaAction()
    {
        //Conectamos a BBDD
        $sid = new Container('base');
        $db_name = $sid->offsetGet('dbNombre');
        $this->dbAdapter=$this->getServiceLocator()->get($db_name);

        //Instancias

        //Obtenemos
        $form="";

        //Retornamos a la vista
        $this->layout('layout/comite');

        return new ViewModel(array('form'=>$form));
    }

}


text:
package sorter

import (
	"fmt"
	"testing"
)

// TestInsertionSortManual sorts the random array and should find result array
func TestInsertionSortManual(t *testing.T) {
	arrRandom := []int{7, 2, 5, 4, 6, 9}
	resultArr := []int{2, 4, 5, 6, 7, 9}
	arr := InsertionSort(arrRandom)
	exp := resultArr

	equals(t, exp, arr)
}

// TestInsertionSort sorts the generated array with insertion sort algorithm
func TestInsertionSort(t *testing.T) {
	generatedArr, err := GenerateArray(8)
	if err != nil {
		t.Fatal(err.Error())
	}

	arr := InsertionSort(generatedArr)

	b, err := IsSorted(arr)
	if err != nil {
		t.Fatal(err.Error())
	}

	if !b {
		fmt.Println("Array is not sorted")
		return
	}
}

// TestRecursiveInsertionSort sorts the generated array with insertion sort algorithm recursively
func TestRecursiveInsertionSort(t *testing.T) {
	generatedArr, err := GenerateArray(8)
	if err != nil {
		t.Fatal(err.Error())
	}

	arr := RecursiveInsertionSort(generatedArr)

	b, err := IsSorted(arr)
	if err != nil {
		t.Fatal(err.Error())
	}

	if !b {
		fmt.Println("Array is not sorted")
		return
	}
}

// TestInsertionSortParallel tests the insertion sort with paralleling
func TestInsertionSortParallel(t *testing.T) {
	tests := []struct {
		arraySize int
		isSorted  bool
		err       error
	}{
		{0, false, ErrArrayNoLength},
		{1, true, nil},
		{2, true, nil},
		{3, true, nil},
		{4, true, nil},
		{10, true, nil},
	}

	for _, test := range tests {
		test := test // capture variable
		t.Run("", func(t *testing.T) {
			t.Parallel()
			arr, err := GenerateArray(test.arraySize)
			if err != test.err {
				t.Fatalf("error should be: %v, but got: %v", test.err, err)
			}

			if len(arr) != test.arraySize {
				t.Fatalf("array length should equal: %v, but got: %v", test.arraySize, len(arr))
			}

			sorted, err := IsSorted(InsertionSort(arr))
			if err != nil {
				t.Fatalf("error should be nil, but got:%v", err)
			}
			if !sorted {
				t.Fatalf("array should be sorted:%v", sorted)
			}
		})
	}
}


text:
import { ModuleRegistry } from '../module-registry';
import { Dict } from '@glimmer/di';

export default class BasicRegistry implements ModuleRegistry {
  private _entries: Dict<any>;

  constructor(entries: Dict<any> = {}) {
    this._entries = entries;
  }

  has(specifier: string): boolean {
    return specifier in this._entries;
  }

  get(specifier: string): any {
    return this._entries[specifier];
  }
}


text:
const utils = (function () {
    const module = {};

    module.breakJobName = function (jobName) {
        return jobName
            .split(/([ _\-])/)
            .filter(function removeWhiteSpace(token) {
                return token !== " ";
            })
            .reduce(function (tokens, currentToken) {
                if (["-", "_"].indexOf(currentToken) >= 0 && tokens.length) {
                    return tokens
                        .slice(0, -1)
                        .concat(tokens.pop() + currentToken);
                }
                return tokens.concat(currentToken);
            }, []);
    };

    const padZero = function (value, padToLength) {
        let paddedValue = String(value);
        while (paddedValue.length < padToLength) {
            paddedValue = "0" + paddedValue;
        }
        return paddedValue;
    };

    const formatHMS = function (values) {
        return [values[0]]
            .concat(
                values.slice(1).map(function (val) {
                    return padZero(val, 2);
                })
            )
            .join(":");
    };

    module.formatTimeInMs = function (timeInMs, options) {
        const hours = Math.floor(timeInMs / (60 * 60 * 1000)),
            minutes = Math.floor((timeInMs % (60 * 60 * 1000)) / (60 * 1000)),
            rawSeconds = (timeInMs % (60 * 1000)) / 1000,
            millis = timeInMs % 1000,
            hms = [];

        if (options && options.showMillis) {
            if (hours > 0) {
                hms.push(hours);
            }

            hms.push(minutes);
            hms.push(Math.floor(rawSeconds));
            return formatHMS(hms) + "." + padZero(Math.floor(millis), 3);
        } else {
            if (hours > 0) {
                hms.push(hours);
            }

            hms.push(minutes);
            hms.push(Math.round(rawSeconds));
            return formatHMS(hms);
        }
    };

    return module;
})();


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('condition-evidence', 'Unit | Model | Condition_Evidence', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:codeable-concept',
    'model:reference'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
  background-color: blue;
}


text:
package cz.larpy.xcom.fieldscanner_v3.ScannerActions;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Parcel;
import android.os.Parcelable;
import cz.larpy.xcom.fieldscanner_v3.HubActivity;
import cz.larpy.xcom.fieldscanner_v3.ScannerAction;
import cz.larpy.xcom.fieldscanner_v3.ScannerDbHelper;
import cz.larpy.xcom.fieldscanner_v3.ScannerRecords.RecordManager;
import cz.larpy.xcom.fieldscanner_v3.ScannerResearch.ResearchManager;
import cz.larpy.xcom.fieldscanner_v3.ScannerSniffer.SnifferLocationManager;

public final class ScannerActionDatabase extends ScannerAction {
  private static String REPOPULATE = "REPOPULATE";

  public static final ScannerActionDatabase repopulate() {
    return new ScannerActionDatabase(REPOPULATE);
  }

  private final String command;

  private ScannerActionDatabase(String pCommand) {
    super();
    command = pCommand;
  }

  private ScannerActionDatabase(Parcel parcel) {
    super(parcel);
    command = parcel.readString();
  }

  public static final Parcelable.Creator<ScannerActionDatabase> CREATOR = new Creator<ScannerActionDatabase>() {
    @Override
    public ScannerActionDatabase createFromParcel(Parcel source) {
      return new ScannerActionDatabase(source);
    }

    @Override
    public ScannerActionDatabase[] newArray(int size) {
      return new ScannerActionDatabase[size];
    }
  };

  @Override
  public String getMessage() {
    if (command.equals(REPOPULATE)) {
      return "The database will be repopulated to the initial state";
    }
    return null;
  }

  @Override
  public void execute(Context context) {
    super.execute(context);
    if (command.equals(REPOPULATE)) {
      ScannerDbHelper dbHelper = new ScannerDbHelper(context);
      SQLiteDatabase db = dbHelper.getWritableDatabase();

      RecordManager recordManager = new RecordManager(context);
      recordManager.clear(db);
      recordManager.populate(db);

      ResearchManager researchManager = new ResearchManager(context);
      researchManager.clear(db);
      researchManager.populate(db);

      SnifferLocationManager locationManager = new SnifferLocationManager(context);
      locationManager.clear(db);
      locationManager.populate(db);

      db.close();
    }
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    super.writeToParcel(dest, flags);
    dest.writeString(command);
  }

  @Override
  public Intent getIntent(Context context) {
    if (command.equals(REPOPULATE)) {
      return new Intent(context, HubActivity.class);
    }
    return null;
  }
}


text:
import requests
import json
import base64

def check(**kwargs):
    """ Checks Heroku's api status for dyno status"""
    jdata = kwargs['jdata']
    logger = kwargs['logger']
    basekey = base64.b64encode(":" + jdata['data']['apikey'])
    headers = {
        "Accept": "application/vnd.heroku+json; version=3",
        "Authorization": basekey
    }
    timeout = 5.00
    url = "https://api.heroku.com/apps/" + jdata['data']['appname'] + "/dynos"
    try:
        result = requests.get(
            url, timeout=timeout, headers=headers, verify=True)
    except:
        return None
    line = "heroku-dyno-status: Got response from heroku for monitor - %s" % (
        result.text)
    logger.debug(line)
    retdata = json.loads(result.text)
    false = 0
    if result.status_code >= 200 and result.status_code <= 299:
        for dyno in retdata:
            if dyno['state'] == "idle":
                false = false + 1
    else:
        return None

    if false == 0:
        return True
    else:
        return False


text:
The four states used for messaging below are exclusive. Only one will ever appear at a time.

```handlebars
<template name="myFormBlock">
  <form>

    {{> UI.contentBlock
        data=data
        form=form
    }}

    <p>
      <button type="submit">Submit</button>
      <span>
        {{#if loading}}
          Loading...
        {{/if}}

        {{#if invalid}}
          Can't submit! There are {{invalidCount}} invalid fields!
        {{/if}}

        {{#if failed}}
          There was a problem submitting the form!
        {{/if}}

        {{#if success}}
          Success! Form submitted (to nowhere)
        {{/if}}
      </span>
    </p>

  </form>
</template>
```


text:
package me.coley.bmf.signature;

public class SigArgArray extends SigArg {
    private final SigArg inner;

    SigArgArray(SigArg inner) {
        this.inner = inner;
    }

    @Override
    String toArg() {
        return "[" + inner.toArg();
    }
}


text:
module BitcoinPayable
  class BitcoinCalculator
    def self.convert_satoshis_to_bitcoin(satoshis)
      satoshis * 0.00000001
    end

    def self.convert_bitcoins_to_satoshis(bitcoins)
      bitcoins / 0.00000001
    end

    def self.exchange_price(price, exchange_rate)
      (price.to_f / exchange_rate.to_f).round(8)
    end
  end
end


text:
package com.google.bigtable.admin.v2;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// AUTO-GENERATED DOCUMENTATION AND CLASS
@javax.annotation.Generated("by GAPIC protoc plugin")
public class AppProfileName implements ResourceName {

  private static final PathTemplate PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding(
          "projects/{project}/instances/{instance}/appProfiles/{app_profile}");

  private volatile Map<String, String> fieldValuesMap;

  private final String project;
  private final String instance;
  private final String appProfile;

  public String getProject() {
    return project;
  }

  public String getInstance() {
    return instance;
  }

  public String getAppProfile() {
    return appProfile;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  private AppProfileName(Builder builder) {
    project = Preconditions.checkNotNull(builder.getProject());
    instance = Preconditions.checkNotNull(builder.getInstance());
    appProfile = Preconditions.checkNotNull(builder.getAppProfile());
  }

  public static AppProfileName of(String project, String instance, String appProfile) {
    return newBuilder().setProject(project).setInstance(instance).setAppProfile(appProfile).build();
  }

  public static String format(String project, String instance, String appProfile) {
    return newBuilder()
        .setProject(project)
        .setInstance(instance)
        .setAppProfile(appProfile)
        .build()
        .toString();
  }

  public static AppProfileName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        PATH_TEMPLATE.validatedMatch(
            formattedString, "AppProfileName.parse: formattedString not in valid format");
    return of(matchMap.get("project"), matchMap.get("instance"), matchMap.get("app_profile"));
  }

  public static List<AppProfileName> parseList(List<String> formattedStrings) {
    List<AppProfileName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<AppProfileName> values) {
    List<String> list = new ArrayList<String>(values.size());
    for (AppProfileName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return PATH_TEMPLATE.matches(formattedString);
  }

  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          fieldMapBuilder.put("project", project);
          fieldMapBuilder.put("instance", instance);
          fieldMapBuilder.put("appProfile", appProfile);
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return PATH_TEMPLATE.instantiate(
        "project", project, "instance", instance, "app_profile", appProfile);
  }

  /** Builder for AppProfileName. */
  public static class Builder {

    private String project;
    private String instance;
    private String appProfile;

    public String getProject() {
      return project;
    }

    public String getInstance() {
      return instance;
    }

    public String getAppProfile() {
      return appProfile;
    }

    public Builder setProject(String project) {
      this.project = project;
      return this;
    }

    public Builder setInstance(String instance) {
      this.instance = instance;
      return this;
    }

    public Builder setAppProfile(String appProfile) {
      this.appProfile = appProfile;
      return this;
    }

    private Builder() {}

    private Builder(AppProfileName appProfileName) {
      project = appProfileName.project;
      instance = appProfileName.instance;
      appProfile = appProfileName.appProfile;
    }

    public AppProfileName build() {
      return new AppProfileName(this);
    }
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof AppProfileName) {
      AppProfileName that = (AppProfileName) o;
      return (this.project.equals(that.project))
          && (this.instance.equals(that.instance))
          && (this.appProfile.equals(that.appProfile));
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= project.hashCode();
    h *= 1000003;
    h ^= instance.hashCode();
    h *= 1000003;
    h ^= appProfile.hashCode();
    return h;
  }
}