text:
/**----------------------------------------------------------------------------
          Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "mfdefs.h"
#include "mfoutline.h"
#include "clusttool.h"           //NEEDED
#include "const.h"
#include "intfx.h"
#include "varable.h"

#include <math.h>

/**----------------------------------------------------------------------------
          Variables
----------------------------------------------------------------------------**/

/* old numbers corresponded to 10.0 degrees and 80.0 degrees */
double_VAR(classify_min_slope, 0.414213562,
           "Slope below which lines are called horizontal");
double_VAR(classify_max_slope, 2.414213562,
           "Slope above which lines are called vertical");
double_VAR(classify_noise_segment_length, 0.00,
           "Length below which outline segments are treated as noise");

/**----------------------------------------------------------------------------
          Macros
----------------------------------------------------------------------------**/
/* miscellaneous macros */
#define NormalizeAngle(A)       ( (((A)<0)?((A)+2*PI):(A)) / (2*PI) )

/*----------------------------------------------------------------------------
          Private Function Prototypes
-----------------------------------------------------------------------------*/
void ComputeBulges(MFOUTLINE Start, MFOUTLINE End, MICROFEATURE MicroFeature);

FLOAT32 ComputeOrientation(MFEDGEPT *Start, MFEDGEPT *End);

MICROFEATURES ConvertToMicroFeatures(MFOUTLINE Outline,
                                     MICROFEATURES MicroFeatures);

MICROFEATURE ExtractMicroFeature(MFOUTLINE Start, MFOUTLINE End);

void SmearBulges(MICROFEATURES MicroFeatures, FLOAT32 XScale, FLOAT32 YScale);

/**----------------------------------------------------------------------------
            Public Code
----------------------------------------------------------------------------**/

/*---------------------------------------------------------------------------*/
CHAR_FEATURES BlobMicroFeatures(TBLOB *Blob, LINE_STATS *LineStats) {
/*
 **      Parameters:
 **              Blob            blob to extract micro-features from
 **              LineStats       statistics for text line normalization
 **      Operation:
 **              This routine extracts micro-features from the specified
 **              blob and returns a list of the micro-features.  All
 **              micro-features are normalized according to the specified
 **              line statistics.
 **      Return: List of micro-features extracted from the blob.
 **      Exceptions: none
 **      History: 7/21/89, DSJ, Created.
 */
  MICROFEATURES MicroFeatures = NIL;
  FLOAT32 XScale, YScale;
  LIST Outlines;
  LIST RemainingOutlines;
  MFOUTLINE Outline;
  INT_FEATURE_ARRAY blfeatures;
  INT_FEATURE_ARRAY cnfeatures;
  INT_FX_RESULT_STRUCT results;

  if (Blob != NULL) {
    Outlines = ConvertBlob (Blob);
//    NormalizeOutlines(Outlines, LineStats, &XScale, &YScale);
    if (!ExtractIntFeat(Blob, blfeatures, cnfeatures, &results))
      return NULL;
    XScale = 0.2f / results.Ry;
    YScale = 0.2f / results.Rx;

    RemainingOutlines = Outlines;
    iterate(RemainingOutlines) {
      Outline = (MFOUTLINE) first_node (RemainingOutlines);
      CharNormalizeOutline (Outline,
        results.Xmean, results.Ymean,
        XScale, YScale);
    }

    RemainingOutlines = Outlines;
    iterate(RemainingOutlines) {
      Outline = (MFOUTLINE) first_node (RemainingOutlines);
      FindDirectionChanges(Outline, classify_min_slope, classify_max_slope);
      FilterEdgeNoise(Outline, classify_noise_segment_length);
      MarkDirectionChanges(Outline);
      SmearExtremities(Outline, XScale, YScale);
      MicroFeatures = ConvertToMicroFeatures (Outline, MicroFeatures);
    }
    SmearBulges(MicroFeatures, XScale, YScale);
    FreeOutlines(Outlines);
  }
  return ((CHAR_FEATURES) MicroFeatures);
}                                /* BlobMicroFeatures */

/**----------------------------------------------------------------------------
              Private Macros
----------------------------------------------------------------------------**/
/**********************************************************************
 * angle_of
 *
 * Return the angle of the line between two points.
 **********************************************************************/
#define angle_of(x1,y1,x2,y2)                   \
((x2-x1) ?                                    \
  (atan2 (y2-y1, x2-x1)) :                     \
  ((y2<y1) ? (- PI / 2.0) : (PI / 2.0)))   \

/**********************************************************************
 * scale_angle
 *
 * Make sure that the angle is non-negative.  Scale it to the right
 * amount.
 **********************************************************************/

#define scale_angle(x)                             \
(((x<0) ? (2.0 * PI + x) : (x)) * 0.5 / PI)  \

/*---------------------------------------------------------------------------
            Private Code
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ComputeBulges(MFOUTLINE Start, MFOUTLINE End, MICROFEATURE MicroFeature) {
/*
 **      Parameters:
 **              Start           starting point of micro-feature
 **              End             ending point of micro-feature
 **              MicroFeature    micro-feature whose bulges are to be computed
 **      Globals: none
 **      Operation:
 **              This routine computes the size of the "bulges" of the
 **              specified micro-feature.  The bulges are the deviations
 **              of the micro-features from a straight line at the 1/3
 **              and 2/3 points along the straight line approximation of
 **              the micro-feature.  The size of each bulge is normalized
 **              to the range -0.5 to 0.5.  A positive bulge indicates a
 **              deviation in the counterclockwise direction and vice versa.
 **              A size of 0.5 (+ or -) corresponds to the largest bulge that
 **              could ever occur for the given feature independent of
 **              orientation.  This routine assumes that Start
 **              and End are not the same point.  It also assumes that the
 **              orientation and length parameters of the micro-feature
 **              have already been computed.
 **      Return: none
 **      Exceptions: none
 **      History: 7/27/89, DSJ, Created.
 */
  MATRIX_2D Matrix;
  MFEDGEPT *Origin;
  MFOUTLINE SegmentStart, SegmentEnd;
  FPOINT CurrentPoint, LastPoint;
  FLOAT32 BulgePosition;

  /* check for simple case */
  if (End == NextPointAfter (Start))
    MicroFeature[FIRSTBULGE] = MicroFeature[SECONDBULGE] = 0;
  else {
    Origin = PointAt (Start);

    InitMatrix(&Matrix);
    RotateMatrix (&Matrix, MicroFeature[ORIENTATION] * -2.0 * PI);
    TranslateMatrix (&Matrix, -Origin->Point.x, -Origin->Point.y);

    SegmentEnd = Start;
    CurrentPoint.x = 0.0f;
    CurrentPoint.y =  0.0f;
    BulgePosition = MicroFeature[MFLENGTH] / 3;
    LastPoint = CurrentPoint;
    while (CurrentPoint.x < BulgePosition) {
      SegmentStart = SegmentEnd;
      SegmentEnd = NextPointAfter (SegmentStart);
      LastPoint = CurrentPoint;

      MapPoint(&Matrix, PointAt(SegmentEnd)->Point, &CurrentPoint);
    }
    MicroFeature[FIRSTBULGE] =
      XIntersectionOf(LastPoint, CurrentPoint, BulgePosition);

    BulgePosition *= 2;

    // Prevents from copying the points before computing the bulge if
    // CurrentPoint will not change. (Which would cause to output nan
    // for the SecondBulge.)
    if (CurrentPoint.x < BulgePosition)
      LastPoint = CurrentPoint;
    while (CurrentPoint.x < BulgePosition) {
      SegmentStart = SegmentEnd;
      SegmentEnd = NextPointAfter (SegmentStart);
      LastPoint = CurrentPoint;
      MapPoint(&Matrix, PointAt(SegmentEnd)->Point, &CurrentPoint);
    }
    MicroFeature[SECONDBULGE] =
      XIntersectionOf(LastPoint, CurrentPoint, BulgePosition);

    MicroFeature[FIRSTBULGE] /= BULGENORMALIZER * MicroFeature[MFLENGTH];
    MicroFeature[SECONDBULGE] /= BULGENORMALIZER * MicroFeature[MFLENGTH];
  }
}                                /* ComputeBulges */

/*---------------------------------------------------------------------------*/
FLOAT32 ComputeOrientation(MFEDGEPT *Start, MFEDGEPT *End) {
/*
 **      Parameters:
 **              Start           starting edge point of micro-feature
 **              End             ending edge point of micro-feature
 **      Globals: none
 **      Operation:
 **              This routine computes the orientation parameter of the
 **              specified micro-feature.  The orientation is the angle of
 **              the vector from Start to End.  It is normalized to a number
 **              between 0 and 1 where 0 corresponds to 0 degrees and 1
 **              corresponds to 360 degrees.  The actual range is [0,1), i.e.
 **              1 is excluded from the range (since it is actual the
 **              same orientation as 0).  This routine assumes that Start
 **              and End are not the same point.
 **      Return: Orientation parameter for the specified micro-feature.
 **      Exceptions: none
 **      History: 7/27/89, DSJ, Created.
 */
  FLOAT32 Orientation;

  Orientation = NormalizeAngle (AngleFrom (Start->Point, End->Point));

  /* ensure that round-off errors do not put circular param out of range */
  if ((Orientation < 0) || (Orientation >= 1))
    Orientation = 0;
  return (Orientation);
}                                /* ComputeOrientation */

/*---------------------------------------------------------------------------*/
MICROFEATURES ConvertToMicroFeatures(MFOUTLINE Outline,
                                     MICROFEATURES MicroFeatures) {
/*
 **      Parameters:
 **              Outline         outline to extract micro-features from
 **              MicroFeatures   list of micro-features to add to
 **      Globals: none
 **      Operation:
 **              This routine
 **      Return: List of micro-features with new features added to front.
 **      Exceptions: none
 **      History: 7/26/89, DSJ, Created.
 */
  MFOUTLINE Current;
  MFOUTLINE Last;
  MFOUTLINE First;
  MICROFEATURE NewFeature;

  if (DegenerateOutline (Outline))
    return (MicroFeatures);

  First = NextExtremity (Outline);
  Last = First;
  do {
    Current = NextExtremity (Last);
    NewFeature = ExtractMicroFeature (Last, Current);
    if (NewFeature != NULL)
      MicroFeatures = push (MicroFeatures, NewFeature);
    Last = Current;
  }
  while (Last != First);

  return (MicroFeatures);
}                                /* ConvertToMicroFeatures */

/*---------------------------------------------------------------------------*/
MICROFEATURE ExtractMicroFeature(MFOUTLINE Start, MFOUTLINE End) {
/*
 **      Parameters:
 **              Start           starting point of micro-feature
 **              End             ending point of micro-feature
 **      Globals: none
 **      Operation:
 **              This routine computes the feature parameters which describe
 **              the micro-feature that starts and Start and ends at End.
 **              A new micro-feature is allocated, filled with the feature
 **              parameters, and returned.  The routine assumes that
 **              Start and End are not the same point.  If they are the
 **              same point, NULL is returned, a warning message is
 **              printed, and the current outline is dumped to stdout.
 **      Return: New micro-feature or NULL if the feature was rejected.
 **      Exceptions: none
 **      History: 7/26/89, DSJ, Created.
 **              11/17/89, DSJ, Added handling for Start and End same point.
 */
  MICROFEATURE NewFeature;
  MFEDGEPT *P1, *P2;

  P1 = PointAt (Start);
  P2 = PointAt (End);

  NewFeature = NewMicroFeature ();
  NewFeature[XPOSITION] = AverageOf (P1->Point.x, P2->Point.x);
  NewFeature[YPOSITION] = AverageOf (P1->Point.y, P2->Point.y);
  NewFeature[MFLENGTH] = DistanceBetween (P1->Point, P2->Point);
  NewFeature[ORIENTATION] = NormalizedAngleFrom(&P1->Point, &P2->Point, 1.0);
  ComputeBulges(Start, End, NewFeature);
  return (NewFeature);
}                                /* ExtractMicroFeature */

/*---------------------------------------------------------------------------*/
void SmearBulges(MICROFEATURES MicroFeatures, FLOAT32 XScale, FLOAT32 YScale) {
/*
 **      Parameters:
 **              MicroFeatures   features to be smeared
 **   XScale    # of normalized units per pixel in x dir
 **   YScale    # of normalized units per pixel in y dir
 **      Globals: none
 **      Operation: Add a random amount to each bulge parameter of each
 **              feature.  The amount added is between -0.5 pixels and
 **              0.5 pixels.  This is done to prevent the prototypes
 **              generated in training from being unrealistically tight.
 **      Return: none
 **      Exceptions: none
 **      History: Thu Jun 28 18:03:38 1990, DSJ, Created.
 */
  MICROFEATURE MicroFeature;
  FLOAT32 MinSmear;
  FLOAT32 MaxSmear;
  FLOAT32 Cos, Sin;
  FLOAT32 Scale;

  iterate(MicroFeatures) {
    MicroFeature = NextFeatureOf (MicroFeatures);

    Cos = fabs(cos(2.0 * PI * MicroFeature[ORIENTATION]));
    Sin = fabs(sin(2.0 * PI * MicroFeature[ORIENTATION]));
    Scale = YScale * Cos + XScale * Sin;

    MinSmear = -0.5 * Scale / (BULGENORMALIZER * MicroFeature[MFLENGTH]);
    MaxSmear = 0.5 * Scale / (BULGENORMALIZER * MicroFeature[MFLENGTH]);

    MicroFeature[FIRSTBULGE] += UniformRandomNumber (MinSmear, MaxSmear);
    MicroFeature[SECONDBULGE] += UniformRandomNumber (MinSmear, MaxSmear);
  }
}                                /* SmearBulges */

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;

#pragma warning disable 1591
#pragma warning disable CA1401 // P/Invokes should not be visible
#pragma warning disable CA1720 // Identifiers should not contain type names
#pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments
#pragma warning disable IDE1006 // Naming style

namespace OpenCvSharp.Internal;

static partial class NativeMethods
{
    // DescriptorMatcher

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_add(
        IntPtr obj, IntPtr[] descriptors, int descriptorLength);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_getTrainDescriptors(IntPtr obj, IntPtr dst);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_clear(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_empty(IntPtr obj, out int returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_isMaskSupported(IntPtr obj, out int returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_train(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_match1(
        IntPtr obj, IntPtr queryDescriptors, IntPtr trainDescriptors, IntPtr matches, IntPtr mask);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_knnMatch1(
        IntPtr obj, IntPtr queryDescriptors, IntPtr trainDescriptors, IntPtr matches, int k,
        IntPtr mask, int compactResult);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_radiusMatch1(
        IntPtr obj, IntPtr queryDescriptors,IntPtr trainDescriptors, IntPtr matches, float maxDistance,
        IntPtr mask, int compactResult);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_match2(
        IntPtr obj, IntPtr queryDescriptors, IntPtr matches,
        IntPtr[] masks, int masksSize);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_knnMatch2(
        IntPtr obj, IntPtr queryDescriptors, IntPtr matches,
        int k, IntPtr[] masks, int masksSize, int compactResult);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_radiusMatch2(
        IntPtr obj, IntPtr queryDescriptors, IntPtr matches,
        float maxDistance, IntPtr[] masks, int masksSize, int compactResult);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_DescriptorMatcher_create(
        [MarshalAs(UnmanagedType.LPStr)] string descriptorMatcherType, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_DescriptorMatcher_get(IntPtr ptr, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_DescriptorMatcher_delete(IntPtr ptr);

    // BFMatcher

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_BFMatcher_new(int normType, int crossCheck, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_BFMatcher_delete(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_BFMatcher_isMaskSupported(IntPtr obj, out int returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_BFMatcher_get(IntPtr ptr, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_BFMatcher_delete(IntPtr ptr);

    // FlannBasedMatcher

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_new(
        IntPtr indexParams, IntPtr searchParams, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_delete(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_add(
        IntPtr obj, IntPtr[] descriptors, int descriptorsSize);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_clear(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_train(IntPtr obj);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_FlannBasedMatcher_isMaskSupported(IntPtr obj, out int returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_FlannBasedMatcher_get(IntPtr ptr, out IntPtr returnValue);

    [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
    public static extern ExceptionStatus features2d_Ptr_FlannBasedMatcher_delete(IntPtr ptr);
}


text:
"""Statistics for the assessment of DA methods.

`Stats` is a data container for ([mostly] time series of) statistics.
It comes with a battery of methods to compute the default statistics.

`Avrgs` is a data container *for the same statistics*,
but after they have been averaged in time (after the assimilation has finished).

Instances of these objects are created by `dapper.da_methods.da_method`
(i.e. "`xp`") objects and written to their `.stats` and `.avrgs` attributes.

.. include:: ../docs/stats_etc.md
"""

import warnings

import numpy as np
import scipy.linalg as sla
import struct_tools
from matplotlib import pyplot as plt
from patlib.std import do_once
from tabulate import tabulate

import dapper.tools.liveplotting as liveplotting
import dapper.tools.series as series
from dapper.dpr_config import rc
from dapper.tools.matrices import CovMat
from dapper.tools.progressbar import progbar

__pdoc__ = {"align_col": False}

class Stats(series.StatPrint):
    """Contains and computes statistics of the DA methods."""

    def __init__(self, xp, HMM, xx, yy, liveplots=False, store_u=rc.store_u):
        """Init the default statistics."""
        ######################################
        # Preamble
        ######################################
        self.xp        = xp
        self.HMM       = HMM
        self.xx        = xx
        self.yy        = yy
        self.liveplots = liveplots
        self.store_u   = store_u
        self.store_s   = any(key in xp.__dict__ for key in
                             ["Lag", "DeCorr"])  # prms used by smoothers

        # Shapes
        K  = xx.shape[0] - 1
        Nx = xx.shape[1]
        Ko = yy.shape[0] - 1
        Ny = yy.shape[1]
        self.K , self.Nx = K, Nx
        self.Ko, self.Ny = Ko, Ny

        # Methods for summarizing multivariate stats ("fields") as scalars
        # Don't use nanmean here; nan's should get propagated!
        en_mean = lambda x: np.mean(x, axis=0)  # noqa
        self.field_summaries = dict(
            m   = lambda x: en_mean(x),                  # mean-field
            ms  = lambda x: en_mean(x**2),               # root-mean-square
            rms = lambda x: np.sqrt(en_mean(x**2)),      # root-mean-square
            ma  = lambda x: en_mean(np.abs(x)),          # mean-absolute
            gm  = lambda x: np.exp(en_mean(np.log(x))),  # geometric mean
        )
        # Only keep the methods listed in rc
        self.field_summaries = struct_tools.intersect(self.field_summaries,
                                                      rc.field_summaries)

        # Define similar methods, but restricted to sectors
        self.sector_summaries = {}
        def restrict(fun, inds): return (lambda x: fun(x[inds]))
        for suffix, formula in self.field_summaries.items():
            for sector, inds in HMM.sectors.items():
                f = restrict(formula, inds)
                self.sector_summaries['%s.%s' % (suffix, sector)] = f

        ######################################
        # Allocate time series of various stats
        ######################################
        self.new_series('mu'    , Nx, field_mean='sectors')  # Mean
        self.new_series('spread', Nx, field_mean='sectors')  # Std. dev. ("spread")
        self.new_series('err'   , Nx, field_mean='sectors')  # Error (mu - truth)
        self.new_series('gscore', Nx, field_mean='sectors')  # Gaussian (log) score

        # To save memory, we only store these field means:
        self.new_series('mad' , 1)  # Mean abs deviations
        self.new_series('skew', 1)  # Skewness
        self.new_series('kurt', 1)  # Kurtosis

        if hasattr(xp, 'N'):
            N = xp.N
            self.new_series('w', N, field_mean=True)  # Importance weights
            self.new_series('rh', Nx, dtype=int)  # Rank histogram

            self._is_ens = True
            minN = min(Nx, N)
            self.do_spectral  = np.sqrt(Nx*N) <= rc.comps["max_spectral"]
        else:
            self._is_ens = False
            minN = Nx
            self.do_spectral = Nx <= rc.comps["max_spectral"]

        if self.do_spectral:
            # Note: the mean-field and RMS time-series of
            # (i) svals and (ii) umisf should match the corresponding series of
            # (i) spread and (ii) err.
            self.new_series('svals', minN)  # Principal component (SVD) scores
            self.new_series('umisf', minN)  # Error in component directions

        ######################################
        # Allocate a few series for outside use
        ######################################
        self.new_series('trHK' , 1, Ko+1)
        self.new_series('infl' , 1, Ko+1)
        self.new_series('iters', 1, Ko+1)

        # Weight-related
        self.new_series('N_eff' , 1, Ko+1)
        self.new_series('wroot' , 1, Ko+1)
        self.new_series('resmpl', 1, Ko+1)

    def new_series(self, name, shape, length='FAUSt', field_mean=False, **kws):
        """Create (and register) a statistics time series, initialized with `nan`s.

        If `length` is an integer, a `DataSeries` (a trivial subclass of
        `numpy.ndarray`) is made. By default, though, a `series.FAUSt` is created.

        NB: The `sliding_diagnostics` liveplotting relies on detecting `nan`'s
            to avoid plotting stats that are not being used.
            Thus, you cannot use `dtype=bool` or `int` for stats that get plotted.
        """
        # Convert int shape to tuple
        if not hasattr(shape, '__len__'):
            if shape == 1:
                shape = ()
            else:
                shape = (shape,)

        def make_series(parent, name, shape):
            if length == 'FAUSt':
                total_shape = self.K, self.Ko, shape
                store_opts = self.store_u, self.store_s
                tseries = series.FAUSt(*total_shape, *store_opts, **kws)
            else:
                total_shape = (length,)+shape
                tseries = series.DataSeries(total_shape, *kws)
            register_stat(parent, name, tseries)

        # Principal series
        make_series(self, name, shape)

        # Summary (scalar) series:
        if shape != ():
            if field_mean:
                for suffix in self.field_summaries:
                    make_series(getattr(self, name), suffix, ())
            # Make a nested level for sectors
            if field_mean == 'sectors':
                for ss in self.sector_summaries:
                    suffix, sector = ss.split('.')
                    make_series(struct_tools.deep_getattr(
                        self, f"{name}.{suffix}"), sector, ())

    @property
    def data_series(self):
        return [k for k in vars(self)
                if isinstance(getattr(self, k), series.DataSeries)]

    def assess(self, k, ko=None, faus=None,
               E=None, w=None, mu=None, Cov=None):
        """Common interface for both `Stats.assess_ens` and `Stats.assess_ext`.

        The `_ens` assessment function gets called if `E is not None`,
        and `_ext` if `mu is not None`.

        faus: One or more of `['f',' a', 'u', 's']`, indicating
              that the result should be stored in (respectively)
              the forecast/analysis/universal attribute.
              Default: `'u' if ko is None else 'au' ('a' and 'u')`.
        """
        # Initial consistency checks.
        if k == 0:
            if ko is not None:
                raise KeyError("DAPPER convention: no obs at t=0. Helps avoid bugs.")
            if self._is_ens == True:
                if E is None:
                    raise TypeError("Expected ensemble input but E is None")
                if mu is not None:
                    raise TypeError("Expected ensemble input but mu/Cov is not None")
            else:
                if E is not None:
                    raise TypeError("Expected mu/Cov input but E is not None")
                if mu is None:
                    raise TypeError("Expected mu/Cov input but mu is None")

        # Default. Don't add more defaults. It just gets confusing.
        if faus is None:
            faus = 'u' if ko is None else 'au'

        # TODO 4: for faus="au" (e.g.) we don't need to re-**compute** stats,
        #         merely re-write them?
        for sub in faus:

            # Skip assessment if ('u' and stats not stored or plotted)
            if k != 0 and ko == None:
                if not (self.store_u or self.LP_instance.any_figs):
                    continue

            # Silence repeat warnings caused by zero variance
            with np.errstate(divide='call', invalid='call'):
                np.seterrcall(warn_zero_variance)

                # Assess
                stats_now = Avrgs()
                if self._is_ens:
                    self.assess_ens(stats_now, self.xx[k], E, w)
                else:
                    self.assess_ext(stats_now, self.xx[k], mu, Cov)
                self.derivative_stats(stats_now)
                self.summarize_marginals(stats_now)

            self.write(stats_now, k, ko, sub)

            # LivePlot -- Both init and update must come after the assessment.
            try:
                self.LP_instance.update((k, ko, sub), E, Cov)
            except AttributeError:
                self.LP_instance = liveplotting.LivePlot(
                    self, self.liveplots, (k, ko, sub), E, Cov)

    def write(self, stat_dict, k, ko, sub):
        """Write `stat_dict` to series at `(k, ko, sub)`."""
        for name, val in stat_dict.items():
            stat = struct_tools.deep_getattr(self, name)
            isFaust = isinstance(stat, series.FAUSt)
            stat[(k, ko, sub) if isFaust else ko] = val

    def summarize_marginals(self, now):
        """Compute Mean-field and RMS values."""
        formulae = {**self.field_summaries, **self.sector_summaries}

        with np.errstate(divide='ignore', invalid='ignore'):
            for stat in list(now):
                field = now[stat]
                for suffix, formula in formulae.items():
                    statpath = stat+'.'+suffix
                    if struct_tools.deep_hasattr(self, statpath):
                        now[statpath] = formula(field)

    def derivative_stats(self, now):
        """Stats that derive from others, and are not specific for `_ens` or `_ext`)."""
        try:
            now.gscore = 2*np.log(now.spread) + (now.err/now.spread)**2
        except AttributeError:
            # happens in case rc.comps['error_only']
            pass

    def assess_ens(self, now, x, E, w):
        """Ensemble and Particle filter (weighted/importance) assessment."""
        N, Nx = E.shape

        # weights
        if w is None:
            w = np.ones(N)/N  # All equal. Also, rm attr from stats:
            if hasattr(self, 'w'):
                delattr(self, 'w')
            # Use non-weight formula (since w=None) for mu computations.
            # The savings are noticeable when rc.comps['error_only'] is noticeable.
            now.mu = E.mean(0)
        else:
            now.w = w
            if abs(w.sum()-1) > 1e-5:
                raise RuntimeError("Weights did not sum to one.")
            now.mu = w @ E

        # Crash checks
        if not np.all(np.isfinite(E)):
            raise RuntimeError("Ensemble not finite.")
        if not np.all(np.isreal(E)):
            raise RuntimeError("Ensemble not Real.")

        # Compute errors
        now.err = now.mu - x
        if rc.comps['error_only']:
            return

        A = E - now.mu
        # While A**2 is approx as fast as A*A,
        # A**3 is 10x slower than A**2 (or A**2.0).
        # => Use A2 = A**2, A3 = A*A2, A4=A*A3.
        # But, to save memory, only use A_pow.
        A_pow = A**2

        # Compute variances
        var  = w @ A_pow
        ub   = unbias_var(w, avoid_pathological=True)
        var *= ub

        # Compute standard deviation ("Spread")
        s = np.sqrt(var)  # NB: biased (even though var is unbiased)
        now.spread = s

        # For simplicity, use naive (biased) formulae, derived
        # from "empirical measure". See doc/unbiased_skew_kurt.jpg.
        # Normalize by var. Compute "excess" kurt, which is 0 for Gaussians.
        A_pow *= A
        now.skew = np.nanmean(w @ A_pow / (s*s*s))
        A_pow *= A
        now.kurt = np.nanmean(w @ A_pow / var**2 - 3)

        now.mad  = np.nanmean(w @ abs(A))

        if self.do_spectral:
            if N <= Nx:
                _, s, UT  = sla.svd((np.sqrt(w)*A.T).T, full_matrices=False)
                s        *= np.sqrt(ub)  # Makes s^2 unbiased
                now.svals = s
                now.umisf = UT @ now.err
            else:
                P         = (A.T * w) @ A
                s2, U     = sla.eigh(P)
                s2       *= ub
                now.svals = np.sqrt(s2.clip(0))[::-1]
                now.umisf = U.T[::-1] @ now.err

            # For each state dim [i], compute rank of truth (x) among the ensemble (E)
            E_x = np.sort(np.vstack((E, x)), axis=0, kind='heapsort')
            now.rh = np.asarray(
                [np.where(E_x[:, i] == x[i])[0][0] for i in range(Nx)])

    def assess_ext(self, now, x, mu, P):
        """Kalman filter (Gaussian) assessment."""
        if not np.all(np.isfinite(mu)):
            raise RuntimeError("Estimates not finite.")
        if not np.all(np.isreal(mu)):
            raise RuntimeError("Estimates not Real.")
        # Don't check the cov (might not be explicitly availble)

        # Compute errors
        now.mu  = mu
        now.err = now.mu - x
        if rc.comps['error_only']:
            return

        # Get diag(P)
        if P is None:
            var = np.zeros_like(mu)
        elif np.isscalar(P):
            var = np.ones_like(mu) * P
        else:
            if isinstance(P, CovMat):
                var = P.diag
                P   = P.full
            else:
                var = np.diag(P)

            if self.do_spectral:
                s2, U     = sla.eigh(P)
                now.svals = np.sqrt(np.maximum(s2, 0.0))[::-1]
                now.umisf = (U.T @ now.err)[::-1]

        # Compute stddev
        now.spread = np.sqrt(var)
        # Here, sqrt(2/pi) is the ratio, of MAD/Spread for Gaussians
        now.mad = np.nanmean(now.spread) * np.sqrt(2/np.pi)

    def average_in_time(self, kk=None, kko=None, free=False):
        """Avarage all univariate (scalar) time series.

        - `kk`    time inds for averaging
        - `kko` time inds for averaging obs
        """
        tseq = self.HMM.tseq
        if kk is None:
            kk     = tseq.mask
        if kko is None:
            kko  = tseq.masko

        def average1(tseries):
            avrgs = Avrgs()

            def average_multivariate(): return avrgs
            # Plain averages of nd-series are rarely interesting.
            # => Shortcircuit => Leave for manual computations

            if isinstance(tseries, series.FAUSt):
                # Average series for each subscript
                if tseries.item_shape != ():
                    return average_multivariate()
                for sub in [ch for ch in 'fas' if hasattr(tseries, ch)]:
                    avrgs[sub] = series.mean_with_conf(tseries[kko, sub])
                if tseries.store_u:
                    avrgs['u'] = series.mean_with_conf(tseries[kk, 'u'])

            elif isinstance(tseries, series.DataSeries):
                if tseries.array.shape[1:] != ():
                    return average_multivariate()
                elif len(tseries.array) == self.Ko+1:
                    avrgs = series.mean_with_conf(tseries[kko])
                elif len(tseries.array) == self.K+1:
                    avrgs = series.mean_with_conf(tseries[kk])
                else:
                    raise ValueError

            elif np.isscalar(tseries):
                avrgs = tseries  # Eg. just copy over "duration" from stats

            else:
                raise TypeError(f"Don't know how to average {tseries}")

            return avrgs

        def recurse_average(stat_parent, avrgs_parent):
            for key in getattr(stat_parent, "stat_register", []):
                try:
                    tseries = getattr(stat_parent, key)
                except AttributeError:
                    continue  # Eg assess_ens() deletes .weights if None
                avrgs = average1(tseries)
                recurse_average(tseries, avrgs)
                avrgs_parent[key] = avrgs

        avrgs = Avrgs()
        recurse_average(self, avrgs)
        self.xp.avrgs = avrgs
        if free:
            delattr(self.xp, 'stats')

    def replay(self, figlist="default", speed=np.inf, t1=0, t2=None, **kwargs):
        """Replay LivePlot with what's been stored in 'self'.

        - t1, t2: time window to plot.
        - 'figlist' and 'speed': See LivePlot's doc.

        .. note:: `store_u` (whether to store non-obs-time stats) must
        have been `True` to have smooth graphs as in the actual LivePlot.

        .. note:: Ensembles are generally not stored in the stats
        and so cannot be replayed.
        """
        # Time settings
        tseq = self.HMM.tseq
        if t2 is None:
            t2 = t1 + tseq.Tplot

        # Ens does not get stored in stats, so we cannot replay that.
        # If the LPs are initialized with P0!=None, then they will avoid ens plotting.
        # TODO 4: This system for switching from Ens to stats must be replaced.
        #       It breaks down when M is very large.
        try:
            P0 = np.full_like(self.HMM.X0.C.full, np.nan)
        except AttributeError:  # e.g. if X0 is defined via sampling func
            P0 = np.eye(self.HMM.Nx)

        LP = liveplotting.LivePlot(self, figlist, P=P0, speed=speed,
                                   Tplot=t2-t1, replay=True, **kwargs)
        plt.pause(.01)  # required when speed=inf

        # Remember: must use progbar to unblock read1.
        # Let's also make a proper description.
        desc = self.xp.da_method + " (replay)"

        # Play through assimilation cycles
        for k, ko, t, _dt in progbar(tseq.ticker, desc):
            if t1 <= t <= t2:
                if ko is not None:
                    LP.update((k, ko, 'f'), None, None)
                    LP.update((k, ko, 'a'), None, None)
                LP.update((k, ko, 'u'), None, None)

        # Pause required when speed=inf.
        # On Mac, it was also necessary to do it for each fig.
        if LP.any_figs:
            for _name, updater in LP.figures.items():
                if plt.fignum_exists(_name) and getattr(updater, 'is_active', 1):
                    plt.figure(_name)
                    plt.pause(0.01)

def register_stat(self, name, value):
    """Do `self.name = value` and register `name` as in self's `stat_register`.

    Note: `self` is not always a `Stats` object, but could be a "child" of it.
    """
    setattr(self, name, value)
    if not hasattr(self, "stat_register"):
        self.stat_register = []
    self.stat_register.append(name)

class Avrgs(series.StatPrint, struct_tools.DotDict):
    """A `dict` specialized for the averages of statistics.

    Embellishments:

    - `dapper.tools.StatPrint`
    - `Avrgs.tabulate`
    - `getattr` that supports abbreviations.
    """

    def tabulate(self, statkeys=(), decimals=None):
        columns = tabulate_avrgs([self], statkeys, decimals=decimals)
        return tabulate(columns, headers="keys").replace('␣', ' ')

    abbrevs = {'rmse': 'err.rms', 'rmss': 'spread.rms', 'rmv': 'spread.rms'}

    # Use getattribute coz it gets called before getattr.
    def __getattribute__(self, key):
        """Support deep and abbreviated lookup."""
        # key = abbrevs[key] # Instead of this, also support rmse.a:
        key = '.'.join(Avrgs.abbrevs.get(seg, seg) for seg in key.split('.'))

        if "." in key:
            return struct_tools.deep_getattr(self, key)
        else:
            return super().__getattribute__(key)

# In case of degeneracy, variance might be 0, causing warnings
# in computing skew/kurt/MGLS (which all normalize by variance).
# This should and will yield nan's, but we don't want mere diagnostics
# computations to cause repetitive warnings, so we only warn once.
#
# I would have expected this (more elegant solution?) to work,
# but it just makes it worse.
# with np.errstate(divide='warn',invalid='warn'), warnings.catch_warnings():
# warnings.simplefilter("once",category=RuntimeWarning)
# ...

@do_once
def warn_zero_variance(err, flag):
    msg = "\n".join(["Numerical error in stat comps.",
                     "Probably caused by a sample variance of 0."])
    warnings.warn(msg)

# Why not do all columns at once using the tabulate module? Coz
#  - Want subcolumns, including fancy formatting (e.g. +/-)
#  - Want separation (using '|') of attr and stats
#  - ...
def align_col(col, pad='␣', missingval='', just=">"):
    r"""Align column.

    Treats `int`s and fixed-point `float`/`str` especially, aligning on the point.

    Example:
    >>> xx = [1, 1., 1.234, 12.34, 123.4, "1.2e-3", None, np.nan, "inf", (1, 2)]
    >>> print(*align_col(xx), sep="\n")
    ␣␣1␣␣␣␣
    ␣␣1.0␣␣
    ␣␣1.234
    ␣12.34␣
    123.4␣␣
    ␣1.2e-3
    ␣␣␣␣␣␣␣
    ␣␣␣␣nan
    ␣␣␣␣inf
    ␣(1, 2)
    """
    def split_decimal(x):
        x = str(x)
        try:
            y = float(x)
        except ValueError:
            pass
        else:
            if np.isfinite(y) and ("e" not in x.lower()):
                a, *b = x.split(".")
                if b == []:
                    b = "int"
                else:
                    b = b[0]
                return a, b
        return x, False

    # Find max nInt, nDec
    nInt = nDec = -1
    for x in col:
        ints, decs = split_decimal(x)
        if decs:
            nInt = max(nInt, len(ints))
            if decs != "int":
                nDec = max(nDec, len(decs))

    # Format entries. Floats get aligned on point.
    def frmt(x):
        if x is None:
            return missingval
        ints, decs = split_decimal(x)
        x = f"{ints.rjust(nInt, pad)}"
        if decs == "int":
            if nDec >= 0:
                x += pad + pad*nDec
        elif decs:
            x += "." + f"{decs.ljust(nDec, pad)}"
        else:
            x = ints
        return x

    # Format
    col = [frmt(x) for x in col]
    # Find max width
    Max = max(len(x) for x in col)
    # Right-justify
    shift = str.rjust if just == ">" else str.ljust
    col = [shift(x, Max, pad) for x in col]
    return col

def unpack_uqs(uq_list, decimals=None):
    """Convert list of `uq`s into dict of lists (of equal-length) of attributes.

    The attributes are obtained by `vars(uq)`,
    and may get formatted somehow (e.g. cast to strings) in the output.

    If `uq` is `None`, then `None` is inserted in each list.
    Else, `uq` must be an instance of `dapper.tools.rounding.UncertainQtty`.

    Parameters
    ----------
    uq_list: list
        List of `uq`s.

    decimals: int
        Desired number of decimals.
        Used for (only) the columns "val" and "prec".
        Default: `None`. In this case, the formatting is left to the `uq`s.
    """
    def frmt(uq):
        if not isinstance(uq, series.UncertainQtty):
            # Presumably uq is just a number
            uq = series.UncertainQtty(uq)

        attrs = vars(uq).copy()

        # val/prec: round
        if decimals is None:
            v, p = str(uq).split(" ±")
        else:
            frmt = "%%.%df" % decimals
            v, p = frmt % uq.val, frmt % uq.prec
        attrs["val"], attrs["prec"] = v, p

        # tuned_coord: convert to tuple
        try:
            attrs["tuned_coord"] = tuple(a for a in uq.tuned_coord)
        except AttributeError:
            pass
        return attrs

    cols = {}
    for i, uq in enumerate(uq_list):
        if uq is not None:
            # Format
            attrs = frmt(uq)
            # Insert attrs as a "row" in the `cols`:
            for k in attrs:
                # Init column
                if k not in cols:
                    cols[k] = [None]*len(uq_list)
                # Insert element
                cols[k][i] = attrs[k]

    return cols

def tabulate_avrgs(avrgs_list, statkeys=(), decimals=None):
    """Tabulate avrgs (val±prec)."""
    if not statkeys:
        statkeys = ['rmse.a', 'rmv.a', 'rmse.f']

    columns = {}
    for stat in statkeys:
        column = [getattr(a, stat, None) for a in avrgs_list]
        column = unpack_uqs(column, decimals)
        if not column:
            raise ValueError(f"The stat. key '{stat}' was not"
                             " found among any of the averages.")
        vals  = align_col([stat] + column["val"])
        precs = align_col(['1σ'] + column["prec"], just="<")
        headr = vals[0]+'  '+precs[0]
        mattr = [f"{v} ±{c}" for v, c in zip(vals, precs)][1:]
        columns[headr] = mattr

    return columns

def center(E, axis=0, rescale=False):
    r"""Center ensemble.

    Makes use of `np` features: keepdims and broadcasting.

    Parameters
    ----------
    E: ndarray
        Ensemble which going to be inflated

    axis: int, optional
        The axis to be centered. Default: 0

    rescale: bool, optional
        If True, inflate to compensate for reduction in the expected variance.
        The inflation factor is \(\sqrt{\frac{N}{N - 1}}\)
        where N is the ensemble size. Default: False

    Returns
    -------
    X: ndarray
        Ensemble anomaly

    x: ndarray
        Mean of the ensemble
    """
    x = np.mean(E, axis=axis, keepdims=True)
    X = E - x

    if rescale:
        N = E.shape[axis]
        X *= np.sqrt(N/(N-1))

    x = x.squeeze(axis=axis)

    return X, x

def mean0(E, axis=0, rescale=True):
    """Like `center`, but only return the anomalies (not the mean).

    Uses `rescale=True` by default, which is beneficial
    when used to center observation perturbations.
    """
    return center(E, axis=axis, rescale=rescale)[0]

def inflate_ens(E, factor):
    """Inflate the ensemble (center, inflate, re-combine).

    Parameters
    ----------
    E : ndarray
        Ensemble which going to be inflated

    factor: `float`
        Inflation factor

    Returns
    -------
    ndarray
        Inflated ensemble
    """
    if factor == 1:
        return E
    X, x = center(E)
    return x + X*factor

def weight_degeneracy(w, prec=1e-10):
    """Check if the weights are degenerate.

    If it is degenerate, the maximum weight
    should be nearly one since sum(w) = 1

    Parameters
    ----------
    w: ndarray
        Importance weights. Must sum to 1.

    prec: float, optional
        Tolerance of the distance between w and one. Default:1e-10

    Returns
    -------
    bool
        If weight is degenerate True, else False
    """
    return (1-w.max()) < prec

def unbias_var(w=None, N_eff=None, avoid_pathological=False):
    """Compute unbias-ing factor for variance estimation.

    Parameters
    ----------
    w: ndarray, optional
        Importance weights. Must sum to 1.
        Only one of `w` and `N_eff` can be `None`. Default: `None`

    N_eff: float, optional
        The "effective" size of the weighted ensemble.
        If not provided, it is computed from the weights.
        The unbiasing factor is $$ N_{eff} / (N_{eff} - 1) $$.

    avoid_pathological: bool, optional
        Avoid weight collapse. Default: `False`

    Returns
    -------
    ub: float
        factor used to unbiasing variance

    Reference
    --------
    [Wikipedia](https://wikipedia.org/wiki/Weighted_arithmetic_mean#Reliability_weights)
    """
    if N_eff is None:
        N_eff = 1/(w@w)

    if avoid_pathological and weight_degeneracy(w):
        ub = 1  # Don't do in case of weights collapse
    else:
        ub = 1/(1 - 1/N_eff)  # =N/(N-1) if w==ones(N)/N.
    return ub


text:
<?php

namespace Tests;

use \JsonConfigLoader\Config;

class ConfigTest extends \PHPUnit_Framework_TestCase
{
	public function testLoadValidConfig()
	{
		$config = Config::getInstance();
		$config->loadConfig($this->_getDataFilePath('valid_config.json'));
		$this->assertNotNull($config->getValue('database'));
		$config->reset();
	}

	public function testLoadInvalidConfig()
	{
		$this->setExpectedException('Exception');
		$config = Config::getInstance();
		$config->loadConfig($this->_getDataFilePath('invalid_config.json'));
		$config->reset();
	}

	public function testGetConfig()
	{
		$config = Config::getInstance();
		$config->loadConfig($this->_getDataFilePath('valid_config.json'));
		$this->assertEquals('localhost', $config->getValue('database.host'));
		$this->assertNull($config->getValue('test'));
		$this->assertEquals('test data', $config->getValue('test', 'test data'));
		$config->reset();
	}

	public function testSetConfig()
	{
		$config = Config::getInstance();
		$config->loadConfig($this->_getDataFilePath('valid_config.json'));
		$config->setValue('database.host', 'testhost');
		$this->assertEquals('testhost', $config->getValue('database.host'));
		$config->setValue('database.test_data.test_arr.test_key', 'test value');
		$this->assertEquals('test value', $config->getValue('database.test_data.test_arr.test_key'));
		$config->reset();
	}

	private function _getDataFilePath($filename)
	{
		return __DIR__ . '/data/' . $filename;
	}
}


text:
<?php
/**
 * Twig extension for Country and Contact Number
 * @author Chaztine Blance
 */
namespace HealthCareAbroad\HelperBundle\Twig;

class AddressTextTwigExtension extends \Twig_Extension
{
    public function getName()
    {
        return 'convert_json_text';
    }

    public function getFunctions()
    {
        return array(
            'getAddress' => new \Twig_Function_Method($this, 'getAddressText'),
            'getContactText' => new \Twig_Function_Method($this, 'getContactText'),
        );
     }

     public function getAddressText($address)
     {
         if($address){
             $returnValue = "";
             $json_value = \json_decode($address, true);
             $returnValue .= $json_value['room_number'];
             $returnValue .= " " .$json_value['building'];
             $returnValue .= " " . $json_value['street'];

         }else{
             $returnValue = "";
         }

         return $returnValue;
     }

     public function getContactText($contact){

         $defaultValue = array('phone_number' => array ( 'number' => '', 'abbr' => ''), 'contact_number' => array ( 'number' => '', 'abbr' => ''));

         if($contact){
             $returnValue = "";
             $json_value = \json_decode($contact, true);
             $returnValue .= "+" .$json_value['country_code'];
             $returnValue .= " " .$json_value['area_code'];
             $returnValue .= " " . $json_value['number'];

         }else{
             $returnValue = "";
         }

         return $returnValue;
     }
}


text:
import helpers from '@/utils/helpers/base'

export default helpers.keyMirror({
  GET_ARTICLES: null,
  GET_ARTICLE: null
})


text:
#if !defined( VCOS_CFG_H )
#define VCOS_CFG_H

#ifdef __cplusplus
extern "C" {
#endif

#include "vcos_types.h"
#include "vcos_platform.h"

typedef struct opaque_vcos_cfg_buf_t    *VCOS_CFG_BUF_T;
typedef struct opaque_vcos_cfg_entry_t  *VCOS_CFG_ENTRY_T;

/** \file vcos_file.h
  *
  * API for accessing configuration/statistics information. This
  * is loosely modelled on the linux proc entries.
  */

typedef void (*VCOS_CFG_SHOW_FPTR)( VCOS_CFG_BUF_T buf, void *data );
typedef void (*VCOS_CFG_PARSE_FPTR)( VCOS_CFG_BUF_T buf, void *data );

/** Create a configuration directory.
  *
  * @param entry        Place to store the created config entry.
  * @param parent       Parent entry (for directory like config
  *                     options).
  * @param entryName    Name of the directory.
  */

VCOS_STATUS_T vcos_cfg_mkdir( VCOS_CFG_ENTRY_T *entry,
                              VCOS_CFG_ENTRY_T *parent,
                              const char *dirName );

/** Create a configuration entry.
  *
  * @param entry        Place to store the created config entry.
  * @param parent       Parent entry (for directory like config
  *                     options).
  * @param entryName    Name of the configuration entry.
  * @param showFunc     Function pointer to show configuration
  *                     data.
  * @param parseFunc    Function pointer to parse new data.
  */

VCOS_STATUS_T vcos_cfg_create_entry( VCOS_CFG_ENTRY_T *entry,
                                     VCOS_CFG_ENTRY_T *parent,
                                     const char *entryName,
                                     VCOS_CFG_SHOW_FPTR showFunc,
                                     VCOS_CFG_PARSE_FPTR parseFunc,
                                     void *data );

/** Determines if a configuration entry has been created or not.
  *
  * @param entry        Configuration entry to query.
  */

int vcos_cfg_is_entry_created( VCOS_CFG_ENTRY_T entry );

/** Returns the name of a configuration entry.
  *
  * @param entry        Configuration entry to query.
  */

const char *vcos_cfg_get_entry_name( VCOS_CFG_ENTRY_T entry );

/** Removes a configuration entry.
  *
  * @param entry        Configuration entry to remove.
  */

VCOS_STATUS_T vcos_cfg_remove_entry( VCOS_CFG_ENTRY_T *entry );

/** Writes data into a configuration buffer. Only valid inside
  * the show function.
  *
  * @param buf      Buffer to write data into.
  * @param fmt      printf style format string.
  */

void vcos_cfg_buf_printf( VCOS_CFG_BUF_T buf, const char *fmt, ... );

/** Retrieves a null terminated string of the data associated
  * with the buffer. Only valid inside the parse function.
  *
  * @param buf      Buffer to get data from.
  * @param fmt      printf style format string.
  */

char *vcos_cfg_buf_get_str( VCOS_CFG_BUF_T buf );

void *vcos_cfg_get_proc_entry( VCOS_CFG_ENTRY_T entry );

#ifdef __cplusplus
}
#endif
#endif


text:
![Swift Support](https://img.shields.io/badge/Swift-5.3-orange.svg) [![Platform](https://img.shields.io/badge/Platforms-iOS%20%7c%20tvOS-lightgray.svg?style=flat)](http://cocoadocs.org/docsets/Zephyr) [![CocoaPods](https://img.shields.io/cocoapods/v/Zephyr.svg)]() [![SwiftPM Compatible](https://img.shields.io/badge/SwiftPM-Compatible-brightgreen.svg)](https://swift.org/package-manager/)

---
### About

Zephyr synchronizes specific keys and/or all of your [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) over iCloud using [NSUbiquitousKeyValueStore](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUbiquitousKeyValueStore_class/).

Zephyr has built in monitoring, allowing it to sync specific keys in the background as they change.

For the latest updates, refer to the [Releases](https://github.com/ArtSabintsev/Zephyr/releases) tab.

### Features
- [x] CocoaPods and SwiftPM Support
- [x] Syncs specific `UserDefaults` keys or all of your `UserDefaults`.
- [x] Background monitoring and synchronization between `UserDefaults` and `NSUbiquitousKeyValueStore`
- [x] Detailed Logging

### Installation Instructions

| Swift Version |  Branch Name  | Will Continue to Receive Updates?
| ------------- | ------------- |  -------------
| 5.1+ | master | **Yes**
| 5.0 | swift5.0 | No
| 4.2 | swift4.2 | No
| 4.1 | swift4.1 | No
| 3.2 | swift3.2 | No
| 3.1 | swift3.1 | No

#### CocoaPods
```ruby
pod 'Zephyr' # Swift 5.1+
pod 'Zephyr', :git => 'https://github.com/ArtSabintsev/Zephyr.git', :branch => 'swift5.0' # Swift 5.0
pod 'Zephyr', :git => 'https://github.com/ArtSabintsev/Zephyr.git', :branch => 'swift4.2' # Swift 4.2
pod 'Zephyr', :git => 'https://github.com/ArtSabintsev/Zephyr.git', :branch => 'swift4.1' # Swift 4.1
pod 'Zephyr', :git => 'https://github.com/ArtSabintsev/Zephyr.git', :branch => 'swift3.2' # Swift 3.2
pod 'Zephyr', :git => 'https://github.com/ArtSabintsev/Zephyr.git', :branch => 'swift3.1' # Swift 3.1
```

### Swift Package Manager
``` swift
.Package(url: "https://github.com/ArtSabintsev/Zephyr.git", majorVersion: 3)
```

#### Manual

1. [Download Zephyr](http://github.com/ArtSabintsev/Zephyr/archive/master.zip)
2. Copy `Zephyr.swift` into your project.

### Setup

#### Turn on iCloud Sync in Xcode
In Xcode, open your app's project/workspace file:
- Click on your Project
- Click on one of your Targets
- Click on Capabilities
- Turn on iCloud syncing
- Under Services, make sure to check `Key-value storage`
- Repeat for all Targets (if necessary)

![How to turn on iCloud Key Value Store Syncing](https://github.com/ArtSabintsev/Zephyr/blob/master/Assets/XcodeSettings.png?raw=true "How to turn on iCloud Key Value Store Syncing")

#### Integrate Zephyr into your App

Before performing each sync, Zephyr automatically checks to see if the data in UserDefaults or NSUbiquitousKeyValueStore is newer. To make sure there's no overwriting going on in a fresh installation of your app on a new device that's connected to the same iCloud account, make sure that your UserDefaults are registered ***BEFORE*** calling any of the Zephyr methods. One way to easily achieve this is by using the [UserDefaults Register API](https://developer.apple.com/documentation/foundation/userdefaults/1417065-register).

**Sync all UserDefaults**
```Swift
Zephyr.sync()
```

**Sync a specific key or keys (Variadic Option)**
```Swift
Zephyr.sync(keys: "MyFirstKey", "MySecondKey", ...)
```

**Sync a specific key or keys (Array Option)**
```Swift
Zephyr.sync(keys: ["MyFirstKey", "MySecondKey"])
```

**Add/Remove Keys for Background Monitoring (Variadic Option)**

```Swift
Zephyr.addKeysToBeMonitored(keys: "MyFirstKey", "MySecondKey", ...)
Zephyr.removeKeysFromBeingMonitored(keys: "MyFirstKey", "MySecondKey", ...)
```

**Add/Remove Keys for Background Monitoring (Array Option)**
```Swift
Zephyr.addKeysToBeMonitored(keys: ["MyFirstKey", "MySecondKey"])
Zephyr.removeKeysFromBeingMonitored(keys: ["MyFirstKey", "MySecondKey"])
```
**Toggle Automatic Calling of NSUbiquitousKeyValueStore's Synchronization method**
```
Zephyr.syncUbiquitousKeyValueStoreOnChange = true // Default
Zephyr.syncUbiquitousKeyValueStoreOnChange = false // Turns off instantaneous synchronization
```

**Debug Logging**
```Swift
Zephyr.debugEnabled = true // Must be called before sync(_:)
Zephyr.sync()
```

### Sample App

Please ignore the Sample App as I did not add any demo code in the Sample App. It's only in this repo to add support for Carthage.

### Created and maintained by
[Arthur Ariel Sabintsev](http://www.sabintsev.com/)


text:
class TypeController < ApplicationController

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @types = Type.where("deleted = 0").order("type_section, display_order1").page(params[:page]).per(100)
  end

  def show
    @type = Type.find(params[:id], :conditions => "deleted = 0 ")
  end

  def new
    @type = Type.new
  end

  def create
    @type = Type.new(params[:type])
    if @type.save
      flash[:notice] = 'Type was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @type = Type.find(params[:id], :conditions => "deleted = 0 ")
  end

  def update
    @type = Type.find(params[:id], :conditions => "deleted = 0 ")
    if @type.update_attributes(params[:type])
      flash[:notice] = 'Type was successfully updated.'
      redirect_to :action => 'show', :id => @type
    else
      render :action => 'edit'
    end
  end

  def destroy
    #Type.find(params[:id]).destroy
    type = Type.find(params[:id], :conditions => "deleted = 0 ")
    type.deleted = 9
    type.save!
    redirect_to :action => 'list'
  end
end


text:
# Hello NW.js

Quick n dirty base for creating a desktop app based on [NWJS](http://nwjs.io/).

## Requirements

Installed by the install script in the Development section below.

* nwjs -- builds against v0.12.3

## Development

### Commands

npm is the build tool.

#### Initial setup (install dev dependencies)

> npm install

#### Run the app in development mode

> npm start

#### Package for Windows 64

See the Hacks section below for what to do before you can successfully package

> npm run package:win

Runs:

> node_modules\.bin\nwbuild.cmd -p win64 -v 0.12.3 -o ./dist "./**/**,!./node_modules/**/**,!./dist/**"

#### Package for OSX 64

See the Hacks section below for what to do before you can successfully package

> npm run package:mac

#### See all available build commands

> npm run

## Hacks *#$!

nwbuild cli does not currently support glob patterns for `files` param. I need in order to have a simple project dir but ignore certain dirs on build.

Until I commit this upstream...

Edit
\node_modules\nw-builder\bin\nwbuild Ln:56

replace

```
// Error if there are no files
var files = argv._[0];
if(!files) {
    optimist.showHelp();
    process.exit(0);
}

var options = {
    files: path.resolve(process.cwd(), files) + '/**/*',
    platforms: argv.platforms.split(','),
    version: argv.version,
    macIcns: argv.macIcns || false,
    winIco: argv.winIco || false,
    cacheDir: path.resolve(__dirname, '..', 'cache'),
    buildDir: path.resolve(process.cwd(), argv.buildDir),
    forceDownload: argv.forceDownload
};
```

with

```
// Error if there are no files
var files = argv._[0];
if(!files) {
    optimist.showHelp();
    process.exit(0);
}

if(files.indexOf(',') > -1) {
    files = files.split(',');
}

var options = {
    // files: path.resolve(process.cwd(), files) + '/**/*',
    files: files,
    platforms: argv.platforms.split(','),
    version: argv.version,
    macIcns: argv.macIcns || false,
    winIco: argv.winIco || false,
    cacheDir: path.resolve(__dirname, '..', 'cache'),
    buildDir: path.resolve(process.cwd(), argv.buildDir),
    forceDownload: argv.forceDownload
};
```

it essentially enables user to pass in comma separated list of paths

```
if(files.indexOf(',') > -1) {
    files = files.split(',');
}
```

then passes the file paths in to be globbed later -- no attempts to resolve them

```
  files: files,
```


text:
Logparser
=========

A simple Log4J parser - useful throw-away code

It was started for two reasons:

1) I had the need in production to filter LOG4J logs with something easier than simply grep

2) I started learning python. So it was a first "real world" attempt to make something more useful beyond "hello world"

Though it was for personal use only - I hope someone finds it usefull or improves it.


text:
package com.google.ddex.convertercli;

import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

class ConverterOptions {
  private File outputDirectory = null;
  private File inputFile = null;
  private List<File> inputFileList = new ArrayList<>();
  private boolean inputIsDirectory = false;
  private String inputType = null;
  private CommandLine commandLineInput;

  private static final ImmutableSet<String> VALID_INPUT_TYPES =
      ImmutableSet.of("message", "schema", "schema_set");
  private static final Options DEFAULT_COMMAND_OPTIONS =
      new Options()
          .addOption(
              Option.builder("o")
                  .longOpt("outputDirectory")
                  .hasArg()
                  .argName("path")
                  .required(false)
                  .desc("the output directory of the serialized protobuf message(s)")
                  .build())
          .addOption(
              Option.builder("d")
                  .longOpt("directory")
                  .desc("specify this option if the input argument is a directory of input_files")
                  .build())
          .addOption(
              Option.builder()
                  .longOpt("inputType")
                  .hasArg()
                  .argName("type")
                  .required(true)
                  .desc("message | schema | schema_set")
                  .build());

  public static void showCommandUsage() {
    final String helpCmdSyntax = "ConverterCli [OPTIONS] input_file";
    final String helpHeader = "Convert input DDEX XML formats to Protobuf";

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(helpCmdSyntax, helpHeader, DEFAULT_COMMAND_OPTIONS, null);
  }

  public ConverterOptions(String[] args) throws InvalidOptionsException {
    setCommandLineInput(args);
    populateOptions();
    validateOptions();
  }

  File getOutputDirectory() {
    return outputDirectory;
  }

  File getInputFile() {
    return inputFile;
  }

  List<File> getInputFileList() {
    return inputFileList;
  }

  boolean isInputIsDirectory() {
    return inputIsDirectory;
  }

  String getInputType() {
    return inputType;
  }

  private void setCommandLineInput(String[] args) throws InvalidOptionsException {
    try {
      CommandLineParser commandParser = new DefaultParser();
      commandLineInput = commandParser.parse(DEFAULT_COMMAND_OPTIONS, args);
    } catch (ParseException e) {
      throw new InvalidOptionsException("Error trying to parse command input.", e);
    }
  }

  private File getFile(String pathName) throws InvalidOptionsException {
    File ddexFile = new File(pathName);
    if (ddexFile.exists()) {
      return ddexFile;
    } else {
      throw new InvalidOptionsException("XML file input does not exist.");
    }
  }

  private void populateOptions() throws InvalidOptionsException {
    if (commandLineInput.hasOption("outputDirectory")) {
      outputDirectory = new File(commandLineInput.getOptionValue("outputDirectory"));
    }
    if (commandLineInput.hasOption("directory")) {
      inputIsDirectory = true;
    }
    if (commandLineInput.hasOption("inputType")) {
      inputType = commandLineInput.getOptionValue("inputType");
    }

    String[] args = commandLineInput.getArgs();
    if (args.length == 1) {
      File ddexFile = getFile(args[0]);
      inputFile = ddexFile;
      inputFileList.add(ddexFile);
    } else if (args.length > 1) {
      for (String arg : args) {
        File ddexFile = getFile(arg);
        inputFileList.add(ddexFile);
      }
    } else {
      throw new InvalidOptionsException("Missing arguments.");
    }
  }

  private void validateOptions() throws InvalidOptionsException {
    if (!VALID_INPUT_TYPES.contains(inputType)) {
      throw new InvalidOptionsException("Invalid inputType specified: " + inputType);
    }
  }
}


text:
    By default, Dependency-Check will use the temp directory defined by java.io.tmpdir, however, this behavior
    may optionally be changed by specifying an alternate temporary directory location.


text:
namespace vespalib {
    class nbostream;
    class DataBuffer;
}
namespace vespalib::alloc { class Alloc; }

namespace search {

class ChunkFormat;

class ChunkMeta {
public:
    ChunkMeta() :
        _offset(0),
        _lastSerial(0),
        _size(0),
        _numEntries(0)
    { }
    ChunkMeta(uint64_t offset, uint32_t size, uint64_t lastSerial, uint32_t numEntries) :
        _offset(offset),
        _lastSerial(lastSerial),
        _size(size),
        _numEntries(numEntries)
    { }
    uint32_t getNumEntries() const { return _numEntries; }
    uint32_t getSize() const { return _size; }
    uint64_t getLastSerial() const { return _lastSerial; }
    uint64_t getOffset() const { return _offset; }
    vespalib::nbostream & deserialize(vespalib::nbostream & is);
    vespalib::nbostream & serialize(vespalib::nbostream & os) const;
    bool operator < (const ChunkMeta & b) const { return _lastSerial < b._lastSerial; }
private:
    uint64_t _offset;
    uint64_t _lastSerial;
    uint32_t _size;
    uint32_t _numEntries;
};

class LidMeta {
public:
    LidMeta() noexcept : _lid(0), _size(0) { }
    LidMeta(uint32_t lid, uint32_t sz) : _lid(lid), _size(sz) { }
    uint32_t     getLid() const { return _lid; }
    uint32_t       size() const { return _size; }
    vespalib::nbostream & deserialize(vespalib::nbostream & is);
    vespalib::nbostream & serialize(vespalib::nbostream & os) const;
private:
    uint32_t _lid;
    uint32_t _size;
};

class Chunk {
public:
    using UP = std::unique_ptr<Chunk>;
    using CompressionConfig = vespalib::compression::CompressionConfig;
    class Config {
    public:
        Config(size_t maxBytes) : _maxBytes(maxBytes) { }
        size_t getMaxBytes() const { return _maxBytes; }
    private:
      size_t _maxBytes;
    };
    class Entry {
    public:
        Entry() : _lid(0), _sz(0), _offset(0) { }
        Entry(uint32_t lid, uint32_t sz, uint32_t offset) : _lid(lid), _sz(sz), _offset(offset) { }
        uint32_t       getLid() const { return _lid; }
        uint32_t         size() const { return _sz + 2*4; }
        uint32_t      netSize() const { return _sz; }
        uint32_t getNetOffset() const { return _offset + 2*4; }
        uint32_t    getOffset() const { return _offset; }
    private:
        uint32_t _lid;
        uint32_t _sz;
        uint32_t _offset;
    };
    typedef std::vector<Entry> LidList;
    Chunk(uint32_t id, const Config & config);
    Chunk(uint32_t id, const void * buffer, size_t len, bool skipcrc=false);
    ~Chunk();
    LidMeta append(uint32_t lid, const void * buffer, size_t len);
    ssize_t read(uint32_t lid, vespalib::DataBuffer & buffer) const;
    std::pair<size_t, vespalib::alloc::Alloc> read(uint32_t lid) const;
    size_t count() const { return _lids.size(); }
    bool empty() const { return count() == 0; }
    size_t size() const;
    const LidList & getLids() const { return _lids; }
    LidList getUniqueLids() const;
    size_t getMaxPackSize(const CompressionConfig & compression) const;
    void pack(uint64_t lastSerial, vespalib::DataBuffer & buffer, const CompressionConfig & compression);
    uint64_t getLastSerial() const { return _lastSerial; }
    uint32_t getId() const { return _id; }
    bool validSerial() const { return getLastSerial() != static_cast<uint64_t>(-1l); }
    vespalib::ConstBufferRef getLid(uint32_t lid) const;
    const vespalib::nbostream & getData() const;
    bool hasRoom(size_t len) const;
    vespalib::MemoryUsage getMemoryUsage() const;
private:
    vespalib::nbostream & getData();

    uint32_t                      _id;
    uint64_t                      _lastSerial;
    std::unique_ptr<ChunkFormat>  _format;
    LidList                       _lids;
    mutable std::mutex            _lock;
};

typedef std::vector<ChunkMeta> ChunkMetaV;

} // namespace search


text:
#ifndef WEBRTC_VOICE_ENGINE_SHARED_DATA_H
#define WEBRTC_VOICE_ENGINE_SHARED_DATA_H

#include "voice_engine_defines.h"

#include "channel_manager.h"
#include "statistics.h"
#include "process_thread.h"

#include "audio_device.h"
#include "audio_processing.h"

class ProcessThread;

namespace webrtc {
class CriticalSectionWrapper;

namespace voe {

class TransmitMixer;
class OutputMixer;

class SharedData
{
public:
    // Public accessors.
    WebRtc_UWord32 instance_id() const { return _instanceId; }
    Statistics& statistics() { return _engineStatistics; }
    ChannelManager& channel_manager() { return _channelManager; }
    AudioDeviceModule* audio_device() { return _audioDevicePtr; }
    void set_audio_device(AudioDeviceModule* audio_device);
    AudioProcessing* audio_processing() { return _audioProcessingModulePtr; }
    void set_audio_processing(AudioProcessing* audio_processing);
    TransmitMixer* transmit_mixer() { return _transmitMixerPtr; }
    OutputMixer* output_mixer() { return _outputMixerPtr; }
    CriticalSectionWrapper* crit_sec() { return _apiCritPtr; }
    bool ext_recording() const { return _externalRecording; }
    void set_ext_recording(bool value) { _externalRecording = value; }
    bool ext_playout() const { return _externalPlayout; }
    void set_ext_playout(bool value) { _externalPlayout = value; }
    ProcessThread* process_thread() { return _moduleProcessThreadPtr; }
    AudioDeviceModule::AudioLayer audio_device_layer() const {
      return _audioDeviceLayer;
    }
    void set_audio_device_layer(AudioDeviceModule::AudioLayer layer) {
      _audioDeviceLayer = layer;
    }

    WebRtc_UWord16 NumOfSendingChannels();

    // Convenience methods for calling statistics().SetLastError().
    void SetLastError(const WebRtc_Word32 error) const;
    void SetLastError(const WebRtc_Word32 error, const TraceLevel level) const;
    void SetLastError(const WebRtc_Word32 error, const TraceLevel level,
                      const char* msg) const;

protected:
    const WebRtc_UWord32 _instanceId;
    CriticalSectionWrapper* _apiCritPtr;
    ChannelManager _channelManager;
    Statistics _engineStatistics;
    AudioDeviceModule* _audioDevicePtr;
    OutputMixer* _outputMixerPtr;
    TransmitMixer* _transmitMixerPtr;
    AudioProcessing* _audioProcessingModulePtr;
    ProcessThread* _moduleProcessThreadPtr;

    bool _externalRecording;
    bool _externalPlayout;

    AudioDeviceModule::AudioLayer _audioDeviceLayer;

    SharedData();
    virtual ~SharedData();
};

} //  namespace voe

} //  namespace webrtc
#endif // WEBRTC_VOICE_ENGINE_SHARED_DATA_H


text:
struct eval_dispatcher : public dispatcher<std::string, std::unique_ptr<eval_visitor>>
{
    eval_dispatcher(rpl_environment& env) {
        add(par::servicetime    ,  std::unique_ptr<eval_visitor>(new servicetime(env)));
        add(par::latency        ,  std::unique_ptr<eval_visitor>(new latencytime(env)));
        add(par::compltime      ,  std::unique_ptr<eval_visitor>(new completiontime(env)));
        add(par::pardegree      ,  std::unique_ptr<eval_visitor>(new pardegree(env)));
        add(par::resources      ,  std::unique_ptr<eval_visitor>(new resources(env)));
    }
};

#endif


text:
"""Test xoinvader.utils module."""

import pytest

from xoinvader.utils import (
    InfiniteList,
    Point,
    clamp,
    dotdict,
    setup_logger,
)

# pylint: disable=invalid-name,protected-access,missing-docstring
def test_setup_logger():
    logger = setup_logger("test", True)
    assert logger

def test_dotdict_setattr():
    settings = dotdict()
    settings.test_entry = 42
    assert settings["test_entry"] == 42
    assert settings.test_entry == 42

    settings["test_entry_2"] = 42
    assert settings.test_entry == 42

    assert pytest.raises(AttributeError, lambda: settings.bad_key)

@pytest.mark.parametrize(
    ("val", "min_val", "max_val", "expected"),
    (
        (-10, -5, 5, -5),
        (-10, -10, -8, -10),
        (-10, -5, -2, -5),
        (0, -1, 1, 0),
        (20, 0, 100, 20),
        (120, 0, 100, 100),
    ),
)
def test_clamp(val, min_val, max_val, expected):
    """xoinvader.utils.clamp"""

    assert clamp(val, min_val, max_val) == expected

def test_infinite_list_operations():

    # Test one element behaviour
    data = "test1"
    inf_list = InfiniteList([data])

    assert len(inf_list) == 1
    assert inf_list[0] == data
    assert inf_list.select(0) == data
    assert inf_list.current() == data
    assert inf_list.next() == data
    assert inf_list.prev() == data

    # TODO: Test many elements behaviour

def test_infinite_list_operations_negative():

    # Test empty InfiniteList behaviour
    inf_list = InfiniteList()
    for func in [
        inf_list.current,
        inf_list.next,
        inf_list.prev,
    ]:
        with pytest.raises(IndexError):
            func()

    # Negative tests for one element behaviour

    inf_list.append("test")

    with pytest.raises(IndexError):
        inf_list.select(-1)
    with pytest.raises(IndexError):
        inf_list.select(1)


text:
import Vue from 'vue';

import ActivityHeatmap from '../components/ActivityHeatmap.vue';

export default async function initUserHeatmap() {
  const el = document.getElementById('user-heatmap');
  if (!el) return;
  const View = Vue.extend(ActivityHeatmap);
  new View().$mount(el);
}


text:
<?php
declare(strict_types=1);

/**
 * WARNING
 * This file has been generated automatically by Xcore Generator.
 * Manual changes to this file will not be maintained.
 */

namespace Xcore\Generator\Tests\Data\AssertMapping\Type;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ContentTrait
 *
 */
trait ContentTrait
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="godlikeProperty", type="string", nullable=false)
     * @Assert\Type(type="array")
     * @Assert\Type(type="bool")
     * @Assert\Type(type="callable")
     * @Assert\Type(type="float")
     * @Assert\Type(type="double")
     * @Assert\Type(type="int")
     * @Assert\Type(type="integer")
     * @Assert\Type(type="long")
     * @Assert\Type(type="null")
     * @Assert\Type(type="numeric")
     * @Assert\Type(type="object")
     * @Assert\Type(type="real")
     * @Assert\Type(type="resource")
     * @Assert\Type(type="scalar")
     * @Assert\Type(type="string")
     * @Assert\Type(type="alnum")
     * @Assert\Type(type="alpha")
     * @Assert\Type(type="cntrl")
     * @Assert\Type(type="digit")
     * @Assert\Type(type="graph")
     * @Assert\Type(type="lower")
     * @Assert\Type(type="print")
     * @Assert\Type(type="punct")
     * @Assert\Type(type="space")
     * @Assert\Type(type="upper")
     * @Assert\Type(type="xdigit")
     */
    private $godlikeProperty;

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

    /**
     * Set godlikeProperty
     *
     * @param string $godlikeProperty
     */
    public function setGodlikeProperty(string $godlikeProperty): void
    {
        $this->godlikeProperty = $godlikeProperty;
    }

    /**
     * Get godlikeProperty
     *
     * @return string
     */
    public function getGodlikeProperty(): string
    {
        return $this->godlikeProperty;
    }
}


text:
package com.lovelysystems.hive.udf;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.Future;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.MemcachedClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

@UDFType(deterministic = false)
@Description(name = "memcached",
        value = "_FUNC_(servers, key, value) - Sets the given key in Memcached")
public class MemcachedUDF extends UDF {

    static final Log LOG = LogFactory.getLog(MemcachedUDF.class.getName());

    protected final HashMap<Text, MemcachedClient> clients = new HashMap<Text, MemcachedClient>();
    private final IntWritable result = new IntWritable(-1);
    private static final DefaultConnectionFactory defaultConnFactory = new DefaultConnectionFactory(
            DefaultConnectionFactory.DEFAULT_OP_QUEUE_LEN,
            DefaultConnectionFactory.DEFAULT_READ_BUFFER_SIZE,
            HashAlgorithm.CRC32_HASH);

    private MemcachedClient getClient(Text servers) throws IOException {
        if (!clients.containsKey(servers)) {
            MemcachedClient client = new MemcachedClient(defaultConnFactory,
                    AddrUtil.getAddresses(servers.toString()));
            clients.put(servers, client);
            return client;
        } else {
            return clients.get(servers);
        }
    }

    public IntWritable evaluate(Text servers, Text key, Text value) {
        if (key == null || servers == null) {
            result.set(-1);
            return result;
        }
        MemcachedClient client;
        try {
            client = getClient(servers);
        } catch (IOException e) {
            LOG.error("failed to get client: servers=" + servers + " key="
                    + key + " value=" + value, e);
            result.set(-1);
            return result;
        }
        Future<Boolean> f;
        if (value == null) {
            f = client.delete(key.toString());
            result.set(2);
        } else {

            f = client.set(key.toString(), 0, value.toString());
            result.set(1);
        }
        try {
            f.get();
        } catch (Exception e) {
            LOG.error("failed to set value: servers=" + servers + " key=" + key
                    + " value=" + value, e);
            result.set(-2);
        }
        return result;
    }

}


text:
import { ContextModule, Intent } from "@artsy/cohesion"
import {
  Box,
  Button,
  Flex,
  FlexProps,
  Radio,
  RadioGroup,
  Separator,
  Spacer,
  Text,
} from "@artsy/palette"
import { ArtworkSidebarCommercial_artwork } from "v2/__generated__/ArtworkSidebarCommercial_artwork.graphql"
import { ArtworkSidebarCommercialOfferOrderMutation } from "v2/__generated__/ArtworkSidebarCommercialOfferOrderMutation.graphql"
import { ArtworkSidebarCommercialOrderMutation } from "v2/__generated__/ArtworkSidebarCommercialOrderMutation.graphql"
import { SystemContext } from "v2/System"
import { track } from "v2/System/Analytics"
import * as Schema from "v2/System/Analytics/Schema"
import { ModalType } from "v2/Components/Authentication/Types"
import { ErrorModal } from "v2/Components/Modal/ErrorModal"
import currency from "currency.js"
import { Router } from "found"
import React, { FC, useContext } from "react"
import {
  RelayProp,
  commitMutation,
  createFragmentContainer,
  graphql,
} from "react-relay"
import { ErrorWithMetadata } from "v2/Utils/errors"
import { get } from "v2/Utils/get"
import createLogger from "v2/Utils/logger"
import { openAuthModal } from "v2/Utils/openAuthModal"
import { ArtworkSidebarSizeInfoFragmentContainer as SizeInfo } from "./ArtworkSidebarSizeInfo"
import { Mediator } from "lib/mediator"

// @ts-expect-error STRICT_NULL_CHECK
type EditionSet = ArtworkSidebarCommercial_artwork["edition_sets"][0]

export interface ArtworkSidebarCommercialContainerProps
  extends ArtworkSidebarCommercialProps {
  mediator: Mediator
  router?: Router
  user: User
}

export interface ArtworkSidebarCommercialContainerState {
  isCommittingCreateOrderMutation: boolean
  isCommittingCreateOfferOrderMutation: boolean
  isErrorModalOpen: boolean
  selectedEditionSet: EditionSet
}

const Row: React.FC<FlexProps> = ({ children, ...others }) => (
  <Flex justifyContent="left" {...others}>
    {children}
  </Flex>
)

const logger = createLogger(
  "Artwork/Components/ArtworkSidebar/ArtworkSidebarCommercial.tsx"
)

@track()
export class ArtworkSidebarCommercialContainer extends React.Component<
  ArtworkSidebarCommercialContainerProps,
  ArtworkSidebarCommercialContainerState
> {
  state: ArtworkSidebarCommercialContainerState = {
    isCommittingCreateOrderMutation: false,
    isCommittingCreateOfferOrderMutation: false,
    isErrorModalOpen: false,
    selectedEditionSet: this.firstAvailableEcommerceEditionSet(),
  }

  firstAvailableEcommerceEditionSet(): EditionSet {
    const editionSets = this.props.artwork.edition_sets

    // @ts-expect-error STRICT_NULL_CHECK
    return editionSets.find(editionSet => {
      // @ts-expect-error STRICT_NULL_CHECK
      return editionSet.is_acquireable || editionSet.is_offerable
    })
  }

  renderSaleMessage(saleMessage: string) {
    return (
      <Text variant="lg" data-test="SaleMessage">
        {saleMessage === "Contact For Price"
          ? "Contact for Price"
          : saleMessage}
      </Text>
    )
  }

  renderEditionSet(editionSet: EditionSet, includeSelectOption: boolean) {
    const editionEcommerceAvailable =
      editionSet.is_acquireable || editionSet.is_offerable

    const editionFragment = (
      <Flex justifyContent="space-between" flex={1}>
        <SizeInfo piece={editionSet} />

        <Text ml={1} variant="xs" data-test="SaleMessage">
          {editionSet.sale_message}
        </Text>
      </Flex>
    )
    if (includeSelectOption) {
      return (
        <Row>
          <Radio
            flex={1}
            onSelect={e => {
              this.setState({ selectedEditionSet: editionSet })
            }}
            selected={this.state.selectedEditionSet === editionSet}
            disabled={!editionEcommerceAvailable}
            label={editionFragment}
          />
        </Row>
      )
    } else {
      return <Row>{editionFragment}</Row>
    }
  }

  renderEditionSets(includeSelectOption: boolean) {
    const editionSets = this.props.artwork.edition_sets

    // @ts-expect-error STRICT_NULL_CHECK
    const editionSetsFragment = editionSets.map((editionSet, index) => {
      return (
        // @ts-expect-error STRICT_NULL_CHECK
        <React.Fragment key={editionSet.id}>
          <Box py={2}>
            {this.renderEditionSet(editionSet, includeSelectOption)}
          </Box>
          {/* @ts-expect-error STRICT_NULL_CHECK */}
          {index !== editionSets.length - 1 && <Separator />}
        </React.Fragment>
      )
    })

    return <RadioGroup>{editionSetsFragment}</RadioGroup>
  }

  onMutationError = (error: ErrorWithMetadata) => {
    logger.error(error)
    this.setState({
      isCommittingCreateOrderMutation: false,
      isErrorModalOpen: true,
    })
  }

  onCloseModal = () => {
    this.setState({ isErrorModalOpen: false })
  }

  @track<ArtworkSidebarCommercialContainerProps>(props => ({
    context_module: Schema.ContextModule.Sidebar,
    action_type: Schema.ActionType.ClickedContactGallery,
    subject: Schema.Subject.ContactGallery,
    artwork_id: props.artwork.internalID,
    artwork_slug: props.artwork.slug,
  }))
  handleInquiry() {
    get(this.props, props => props.mediator.trigger) &&
      this.props.mediator.trigger("launchInquiryFlow", {
        artworkId: this.props.artwork.internalID,
      })
  }

  @track<ArtworkSidebarCommercialContainerProps>((props, state, args) => ({
    action_type: Schema.ActionType.ClickedBuyNow,
    flow: Schema.Flow.BuyNow,
    type: Schema.Type.Button,
    artwork_id: props.artwork.internalID,
    artwork_slug: props.artwork.slug,
    products: [
      {
        product_id: props.artwork.internalID,
        quantity: 1,
        // @ts-expect-error STRICT_NULL_CHECK
        price: currency(props.artwork.listPrice.display).value,
      },
    ],
  }))
  handleCreateOrder() {
    const { user, mediator } = this.props
    if (user && user.id) {
      this.setState({ isCommittingCreateOrderMutation: true }, () => {
        // @ts-expect-error STRICT_NULL_CHECK
        if (get(this.props, props => props.relay.environment)) {
          commitMutation<ArtworkSidebarCommercialOrderMutation>(
            // @ts-expect-error STRICT_NULL_CHECK
            this.props.relay.environment,
            {
              // TODO: Inputs to the mutation might have changed case of the keys!
              mutation: graphql`
                mutation ArtworkSidebarCommercialOrderMutation(
                  $input: CommerceCreateOrderWithArtworkInput!
                ) {
                  commerceCreateOrderWithArtwork(input: $input) {
                    orderOrError {
                      ... on CommerceOrderWithMutationSuccess {
                        __typename
                        order {
                          internalID
                          mode
                        }
                      }
                      ... on CommerceOrderWithMutationFailure {
                        error {
                          type
                          code
                          data
                        }
                      }
                    }
                  }
                }
              `,
              variables: {
                input: {
                  artworkId: this.props.artwork.internalID,
                  editionSetId: get(
                    this.state,
                    state => state.selectedEditionSet.internalID
                  ),
                },
              },
              onCompleted: data => {
                this.setState(
                  { isCommittingCreateOrderMutation: false },
                  () => {
                    const {
                      // @ts-expect-error STRICT_NULL_CHECK
                      commerceCreateOrderWithArtwork: { orderOrError },
                    } = data
                    if (orderOrError.error) {
                      this.onMutationError(
                        new ErrorWithMetadata(
                          orderOrError.error.code,
                          orderOrError.error
                        )
                      )
                    } else {
                      const url = `/orders/${orderOrError.order.internalID}`
                      // @ts-expect-error STRICT_NULL_CHECK
                      this.props.router.push(url)
                    }
                  }
                )
              },
              onError: this.onMutationError,
            }
          )
        }
      })
    } else {
      openAuthModal(mediator, {
        mode: ModalType.signup,
        redirectTo: location.href,
        contextModule: ContextModule.artworkSidebar,
        intent: Intent.buyNow,
      })
    }
  }

  @track<ArtworkSidebarCommercialContainerProps>((props, state, args) => ({
    action_type: Schema.ActionType.ClickedMakeOffer,
    flow: Schema.Flow.MakeOffer,
    type: Schema.Type.Button,
    artwork_id: props.artwork.internalID,
    artwork_slug: props.artwork.slug,
  }))
  handleCreateOfferOrder() {
    const { user, mediator } = this.props
    if (user && user.id) {
      this.setState({ isCommittingCreateOfferOrderMutation: true }, () => {
        // @ts-expect-error STRICT_NULL_CHECK
        if (get(this.props, props => props.relay.environment)) {
          commitMutation<ArtworkSidebarCommercialOfferOrderMutation>(
            // @ts-expect-error STRICT_NULL_CHECK
            this.props.relay.environment,
            {
              // TODO: Inputs to the mutation might have changed case of the keys!
              mutation: graphql`
                mutation ArtworkSidebarCommercialOfferOrderMutation(
                  $input: CommerceCreateOfferOrderWithArtworkInput!
                ) {
                  commerceCreateOfferOrderWithArtwork(input: $input) {
                    orderOrError {
                      ... on CommerceOrderWithMutationSuccess {
                        __typename
                        order {
                          internalID
                          mode
                        }
                      }
                      ... on CommerceOrderWithMutationFailure {
                        error {
                          type
                          code
                          data
                        }
                      }
                    }
                  }
                }
              `,
              variables: {
                input: {
                  artworkId: this.props.artwork.internalID,
                  editionSetId: get(
                    this.state,
                    state => state.selectedEditionSet.internalID
                  ),
                },
              },
              onCompleted: data => {
                this.setState(
                  { isCommittingCreateOfferOrderMutation: false },
                  () => {
                    const {
                      // @ts-expect-error STRICT_NULL_CHECK
                      commerceCreateOfferOrderWithArtwork: { orderOrError },
                    } = data
                    if (orderOrError.error) {
                      this.onMutationError(
                        new ErrorWithMetadata(
                          orderOrError.error.code,
                          orderOrError.error
                        )
                      )
                    } else {
                      const url = `/orders/${orderOrError.order.internalID}/offer`
                      // @ts-expect-error STRICT_NULL_CHECK
                      this.props.router.push(url)
                    }
                  }
                )
              },
              onError: this.onMutationError,
            }
          )
        }
      })
    } else {
      openAuthModal(mediator, {
        mode: ModalType.signup,
        redirectTo: location.href,
        contextModule: ContextModule.artworkSidebar,
        intent: Intent.makeOffer,
      })
    }
  }

  render() {
    const { artwork } = this.props

    const {
      isCommittingCreateOrderMutation,
      isCommittingCreateOfferOrderMutation,
      selectedEditionSet,
    } = this.state

    const artworkEcommerceAvailable = !!(
      artwork.is_acquireable || artwork.is_offerable
    )

    if (!artwork.sale_message && !artwork.is_inquireable) {
      return <Separator />
    }

    return (
      <Box textAlign="left">
        {artwork.sale_message && <Separator />}

        {(artwork.edition_sets?.length ?? 0) < 2 ? (
          artwork.sale_message && (
            <>
              <Spacer mt={2} />
              {this.renderSaleMessage(artwork.sale_message)}
            </>
          )
        ) : (
          <>
            {this.renderEditionSets(artworkEcommerceAvailable)}

            {selectedEditionSet && (
              <>
                <Separator mb={2} />
                {this.renderSaleMessage(selectedEditionSet.sale_message)}
              </>
            )}
          </>
        )}

        {artworkEcommerceAvailable &&
          (artwork.shippingOrigin || artwork.shippingInfo) && <Spacer mt={1} />}

        {artworkEcommerceAvailable && artwork.shippingOrigin && (
          <Text variant="xs" color="black60">
            Ships from {artwork.shippingOrigin}
          </Text>
        )}

        {artworkEcommerceAvailable && artwork.shippingInfo && (
          <Text variant="xs" color="black60">
            {artwork.shippingInfo}
          </Text>
        )}

        {artworkEcommerceAvailable && artwork.priceIncludesTaxDisplay && (
          <Text variant="xs" color="black60">
            {artwork.priceIncludesTaxDisplay}
          </Text>
        )}

        {artwork.is_inquireable ||
        artwork.is_acquireable ||
        artwork.is_offerable ? (
          artwork.sale_message && <Spacer mt={2} />
        ) : (
          <Separator my={2} />
        )}

        {artwork.is_acquireable && (
          <Button
            width="100%"
            size="medium"
            loading={isCommittingCreateOrderMutation}
            onClick={this.handleCreateOrder.bind(this)}
          >
            Buy now
          </Button>
        )}
        {artwork.is_offerable && (
          <>
            <Spacer mt={2} />
            <Button
              variant={
                artwork.is_acquireable ? "secondaryOutline" : "primaryBlack"
              }
              width="100%"
              size="medium"
              loading={isCommittingCreateOfferOrderMutation}
              onClick={this.handleCreateOfferOrder.bind(this)}
            >
              Make offer
            </Button>
          </>
        )}
        {artwork.is_inquireable &&
          !artwork.is_acquireable &&
          !artwork.is_offerable && (
            <Button
              width="100%"
              size="medium"
              onClick={this.handleInquiry.bind(this)}
            >
              Contact Gallery
            </Button>
          )}

        <ErrorModal
          onClose={this.onCloseModal}
          show={this.state.isErrorModalOpen}
          contactEmail="orders@artsy.net"
        />
      </Box>
    )
  }
}

interface ArtworkSidebarCommercialProps {
  artwork: ArtworkSidebarCommercial_artwork
  relay?: RelayProp
}

export const ArtworkSidebarCommercial: FC<ArtworkSidebarCommercialProps> = props => {
  const { mediator, router, user } = useContext(SystemContext)

  return (
    // @ts-expect-error STRICT_NULL_CHECK
    <ArtworkSidebarCommercialContainer
      {...props}
      mediator={mediator}
      router={router}
      user={user}
    />
  )
}

export const ArtworkSidebarCommercialFragmentContainer = createFragmentContainer(
  ArtworkSidebarCommercial,
  {
    artwork: graphql`
      fragment ArtworkSidebarCommercial_artwork on Artwork {
        slug
        internalID
        is_for_sale: isForSale
        is_acquireable: isAcquireable
        is_inquireable: isInquireable
        is_offerable: isOfferable
        listPrice {
          ... on PriceRange {
            display
          }
          ... on Money {
            display
          }
        }
        priceIncludesTaxDisplay
        sale_message: saleMessage
        shippingInfo
        shippingOrigin
        edition_sets: editionSets {
          internalID
          id
          is_acquireable: isAcquireable
          is_offerable: isOfferable
          sale_message: saleMessage
          ...ArtworkSidebarSizeInfo_piece
        }
      }
    `,
  }
)