text:
package timeusage

import java.nio.file.Paths

import org.apache.spark.sql._
import org.apache.spark.sql.types._

/** Main class */
object TimeUsage {

  import org.apache.spark.sql.SparkSession
  import org.apache.spark.sql.functions._

  val spark: SparkSession =
    SparkSession
      .builder()
      .appName("Time Usage")
      .config("spark.master", "local")
      .getOrCreate()

  // For implicit conversions like converting RDDs to DataFrames
  import spark.implicits._

  /** Main function */
  def main(args: Array[String]): Unit = {
    timeUsageByLifePeriod()
  }

  def timeUsageByLifePeriod(): Unit = {
    val (columns, initDf) = read("/timeusage/atussum.csv")
    val (primaryNeedsColumns, workColumns, otherColumns) = classifiedColumns(columns)
    val summaryDf = timeUsageSummary(primaryNeedsColumns, workColumns, otherColumns, initDf)
    val finalDf = timeUsageGrouped(summaryDf)
    finalDf.show()
  }

  /** @return The read DataFrame along with its column names. */
  def read(resource: String): (List[String], DataFrame) = {
    val rdd = spark.sparkContext.textFile(fsPath(resource))

    val headerColumns = rdd.first().split(",").to[List]
    // Compute the schema based on the first line of the CSV file
    val schema = dfSchema(headerColumns)

    val data =
      rdd
        .mapPartitionsWithIndex((i, it) => if (i == 0) it.drop(1) else it) // skip the header line
        .map(_.split(",").to[List])
        .map(row)

    val dataFrame =
      spark.createDataFrame(data, schema)

    (headerColumns, dataFrame)
  }

  /** @return The filesystem path of the given resource */
  def fsPath(resource: String): String = {
    "src/main/resources" + resource
    // Paths.get(getClass.getResource(resource).toURI).toString
  }

  /** @return The schema of the DataFrame, assuming that the first given column has type String and all the others
    *         have type Double. None of the fields are nullable.
    * @param columnNames Column names of the DataFrame
    */
  def dfSchema(columnNames: List[String]): StructType = StructType (
    StructField(columnNames.head, StringType, nullable = false) ::
    columnNames.tail.map(name => StructField(name, DoubleType, nullable = false))
  )

  /** @return An RDD Row compatible with the schema produced by `dfSchema`
    * @param line Raw fields
    */
  def row(line: List[String]): Row =
    Row.fromSeq(line.head :: line.tail.map(_.trim.toDouble))

  /** @return The initial data frame columns partitioned in three groups: primary needs (sleeping, eating, etc.),
    *         work and other (leisure activities)
    *
    * @see https://www.kaggle.com/bls/american-time-use-survey
    *
    * The dataset contains the daily time (in minutes) people spent in various activities. For instance, the column
    * "t010101" contains the time spent sleeping, the column "t110101" contains the time spent eating and drinking, etc.
    *
    * This method groups related columns together:
    * 1. "primary needs" activities (sleeping, eating, etc.). These are the columns starting with "t01", "t03", "t11",
    *    "t1801" and "t1803".
    * 2. working activities. These are the columns starting with "t05" and "t1805".
    * 3. other activities (leisure). These are the columns starting with "t02", "t04", "t06", "t07", "t08", "t09",
    *    "t10", "t12", "t13", "t14", "t15", "t16" and "t18" (those which are not part of the previous groups only).
    */
  def classifiedColumns(columnNames: List[String]): (List[Column], List[Column], List[Column]) = {
    columnNames.reverse.foldLeft((List[Column](), List[Column](), List[Column]()))((acc, name) => name match {
      case s if (s.startsWith("t01") ||
                 s.startsWith("t03") ||
                 s.startsWith("t11") ||
                 s.startsWith("t1801") ||
                 s.startsWith("t1803")) => (col(s) :: acc._1, acc._2, acc._3)
      case s if (s.startsWith("t05") ||
                 s.startsWith("t1805")) => (acc._1, col(s) :: acc._2, acc._3)
      case s if (s.startsWith("t02") || s.startsWith("t04") ||
                 s.startsWith("t06") || s.startsWith("t07") ||
                 s.startsWith("t08") || s.startsWith("t09") ||
                 s.startsWith("t10") || s.startsWith("t12") ||
                 s.startsWith("t13") || s.startsWith("t14") ||
                 s.startsWith("t15") || s.startsWith("t16") ||
                 s.startsWith("t18")) => (acc._1, acc._2, col(s) :: acc._3)
      case _ => acc
    })
  }

  /** @return a projection of the initial DataFrame such that all columns containing hours spent on primary needs
    *         are summed together in a single column (and same for work and leisure). The "teage" column is also
    *         projected to three values: "young", "active", "elder".
    *
    * @param primaryNeedsColumns List of columns containing time spent on "primary needs"
    * @param workColumns List of columns containing time spent working
    * @param otherColumns List of columns containing time spent doing other activities
    * @param df DataFrame whose schema matches the given column lists
    *
    * This methods builds an intermediate DataFrame that sums up all the columns of each group of activity into
    * a single column.
    *
    * The resulting DataFrame should have the following columns:
    * - working: value computed from the "telfs" column of the given DataFrame:
    *   - "working" if 1 <= telfs < 3
    *   - "not working" otherwise
    * - sex: value computed from the "tesex" column of the given DataFrame:
    *   - "male" if tesex = 1, "female" otherwise
    * - age: value computed from the "teage" column of the given DataFrame:
    *   - "young" if 15 <= teage <= 22,
    *   - "active" if 23 <= teage <= 55,
    *   - "elder" otherwise
    * - primaryNeeds: sum of all the `primaryNeedsColumns`, in hours
    * - work: sum of all the `workColumns`, in hours
    * - other: sum of all the `otherColumns`, in hours
    *
    * Finally, the resulting DataFrame should exclude people that are not employable (ie telfs = 5).
    *
    * Note that the initial DataFrame contains time in ''minutes''. You have to convert it into ''hours''.
    */
  def timeUsageSummary(
    primaryNeedsColumns: List[Column],
    workColumns: List[Column],
    otherColumns: List[Column],
    df: DataFrame
  ): DataFrame = {
    val workingStatusProjection: Column = when($"telfs" >= 1 && $"telfs" < 3, "working").
                                          otherwise("not working") as "working"
    val sexProjection: Column = when($"tesex" === 1, "male").
                                otherwise("female") as "sex"
    val ageProjection: Column = when($"teage" >= 15 && $"teage" <= 22, "young").
                                when($"teage" >= 23 && $"teage" <= 55, "active").
                                otherwise("elder") as "age"

    val primaryNeedsProjection: Column = primaryNeedsColumns.reduce(_ + _) / 60.0d as "primaryNeeds"
    val workProjection: Column = workColumns.reduce(_ + _) / 60.0d as "work"
    val otherProjection: Column = otherColumns.reduce(_ + _) / 60.0d as "other"
    df
      .select(workingStatusProjection, sexProjection, ageProjection, primaryNeedsProjection, workProjection, otherProjection)
      .where($"telfs" <= 4) // Discard people who are not in labor force
  }

  /** @return the average daily time (in hours) spent in primary needs, working or leisure, grouped by the different
    *         ages of life (young, active or elder), sex and working status.
    * @param summed DataFrame returned by `timeUsageSumByClass`
    *
    * The resulting DataFrame should have the following columns:
    * - working: the "working" column of the `summed` DataFrame,
    * - sex: the "sex" column of the `summed` DataFrame,
    * - age: the "age" column of the `summed` DataFrame,
    * - primaryNeeds: the average value of the "primaryNeeds" columns of all the people that have the same working
    *   status, sex and age, rounded with a scale of 1 (using the `round` function),
    * - work: the average value of the "work" columns of all the people that have the same working status, sex
    *   and age, rounded with a scale of 1 (using the `round` function),
    * - other: the average value of the "other" columns all the people that have the same working status, sex and
    *   age, rounded with a scale of 1 (using the `round` function).
    *
    * Finally, the resulting DataFrame should be sorted by working status, sex and age.
    */
  def timeUsageGrouped(summed: DataFrame): DataFrame = {
    summed.groupBy($"working", $"sex", $"age")
          .agg(round(avg($"primaryNeeds"), 1) as "primaryNeeds",
               round(avg($"work"), 1) as "work",
               round(avg($"other"), 1) as "other")
          .orderBy($"working", $"sex", $"age")
  }

  /**
    * @return Same as `timeUsageGrouped`, but using a plain SQL query instead
    * @param summed DataFrame returned by `timeUsageSumByClass`
    */
  def timeUsageGroupedSql(summed: DataFrame): DataFrame = {
    val viewName = s"summed"
    summed.createOrReplaceTempView(viewName)
    spark.sql(timeUsageGroupedSqlQuery(viewName))
  }

  /** @return SQL query equivalent to the transformation implemented in `timeUsageGrouped`
    * @param viewName Name of the SQL view to use
    */
  def timeUsageGroupedSqlQuery(viewName: String): String = """
    SELECT working, sex, age,
           ROUND(AVG(primaryNeeds), 1) AS primaryNeeds,
           ROUND(AVG(work), 1) AS work,
           ROUND(AVG(other), 1) AS other
    FROM """ + viewName + """
    GROUP By working, sex, age
    ORDER BY working, sex, age
  """

  /**
    * @return A `Dataset[TimeUsageRow]` from the "untyped" `DataFrame`
    * @param timeUsageSummaryDf `DataFrame` returned by the `timeUsageSummary` method
    *
    * Hint: you should use the `getAs` method of `Row` to look up columns and
    * cast them at the same time.
    */
  def timeUsageSummaryTyped(timeUsageSummaryDf: DataFrame): Dataset[TimeUsageRow] =
    timeUsageSummaryDf.map { r => TimeUsageRow(
      r.getAs("working"),
      r.getAs("sex"),
      r.getAs("age"),
      r.getAs("primaryNeeds"),
      r.getAs("work"),
      r.getAs("other")
    )}

  /**
    * @return Same as `timeUsageGrouped`, but using the typed API when possible
    * @param summed Dataset returned by the `timeUsageSummaryTyped` method
    *
    * Note that, though they have the same type (`Dataset[TimeUsageRow]`), the input
    * dataset contains one element per respondent, whereas the resulting dataset
    * contains one element per group (whose time spent on each activity kind has
    * been aggregated).
    *
    * Hint: you should use the `groupByKey` and `typed.avg` methods.
    */
  def timeUsageGroupedTyped(summed: Dataset[TimeUsageRow]): Dataset[TimeUsageRow] = {
    import org.apache.spark.sql.expressions.scalalang.typed
    summed.groupByKey(u => (u.working, u.sex, u.age))
          .agg(round(typed.avg[TimeUsageRow](_.primaryNeeds), 1).as(Encoders.DOUBLE),
               round(typed.avg[TimeUsageRow](_.work), 1).as(Encoders.DOUBLE),
               round(typed.avg[TimeUsageRow](_.other), 1).as(Encoders.DOUBLE))
          .map { u => TimeUsageRow(u._1._1, u._1._2, u._1._3, u._2, u._3, u._4) }
          .sort ($"working", $"sex", $"age")
  }
}

/**
  * Models a row of the summarized data set
  * @param working Working status (either "working" or "not working")
  * @param sex Sex (either "male" or "female")
  * @param age Age (either "young", "active" or "elder")
  * @param primaryNeeds Number of daily hours spent on primary needs
  * @param work Number of daily hours spent on work
  * @param other Number of daily hours spent on other activities
  */
case class TimeUsageRow(
  working: String,
  sex: String,
  age: String,
  primaryNeeds: Double,
  work: Double,
  other: Double
)


text:
package golang

import (
	"path"

	log "github.com/Sirupsen/logrus"

	"github.com/Jumpscale/go-raml/codegen/commons"
	"github.com/Jumpscale/go-raml/codegen/security"
	"github.com/Jumpscale/go-raml/raml"
)

type goSecurity struct {
	*security.Security
}

// generate Go representation of a security scheme
// it implemented as struct based middleware
func (gs *goSecurity) generate(dir string) error {
	fileName := path.Join(dir, "oauth2_"+gs.Name+"_middleware.go")
	return commons.GenerateFile(gs, "./templates/golang/oauth2_middleware.tmpl", "oauth2_middleware", fileName, true)
}

func generateSecurity(schemes map[string]raml.SecurityScheme, dir, packageName string) error {
	var err error

	// generate oauth2 middleware
	for k, ss := range schemes {
		if ss.Type != security.Oauth2 {
			continue
		}

		sd := security.New(ss, k, packageName)

		gss := goSecurity{Security: &sd}
		err = gss.generate(dir)

		if err != nil {
			log.Errorf("generateSecurity() failed to generate %v, err=%v", k, err)
			return err
		}
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-release/frameworks/support/v7/mediarouter/res/values-fa/strings.xml -->
    <eat-comment/>
    <string msgid="8327680881775995150" name="mr_media_route_button_content_description">"فرستادن"</string>
    <string msgid="7553005460920830010" name="mr_media_route_chooser_searching">"در حال جستجو برای دستگاه‌ها..."</string>
    <string msgid="7106830097177242655" name="mr_media_route_chooser_title">"برقراری ارتباط با دستگاه"</string>
    <string msgid="109793632378378069" name="mr_media_route_controller_disconnect">"قطع ارتباط"</string>
    <string msgid="3641544772007543920" name="mr_media_route_controller_no_info_available">"اطلاعات دردسترس نیست"</string>
    <string msgid="8315773974194466049" name="mr_media_route_controller_pause">"توقف موقت"</string>
    <string msgid="5214423499524760404" name="mr_media_route_controller_play">"پخش"</string>
    <string msgid="379358765881274425" name="mr_media_route_controller_settings_description">"تنظیمات مسیر"</string>
    <string msgid="5398645111664294430" name="mr_media_route_controller_stop">"توقف فرستادن"</string>
    <string msgid="5441529851481176817" name="mr_system_route_name">"سیستم"</string>
    <string msgid="7498112907524977311" name="mr_user_route_category_name">"دستگاه‌ها"</string>
</resources>


text:
namespace Microsoft.Zelig.Configuration.Environment.Abstractions
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Zelig.Runtime.TypeSystem;

    using Microsoft.Zelig.TargetModel.ArmProcessor;

    using ZeligIR = Microsoft.Zelig.CodeGeneration.IR;

    public class ArmCallingConvention : ZeligIR.Abstractions.CallingConvention
    {
        class ArmCallState : ZeligIR.Abstractions.CallingConvention.CallState
        {
            //
            // State
            //

            internal int  m_numberOfWordsPassedInRegistersForIntegers;
            internal int  m_numberOfWordsPassedInRegistersForFloatingPoints;
            internal int  m_numberOfWordsPerArgument;

            internal uint m_nextRegForArgumentsInteger;
            internal uint m_nextRegForArgumentsFloatingPoint;
            internal uint m_nextRegForResultValueInteger;
            internal uint m_nextRegForResultValueFloatingPoint;

            internal uint m_nextStackIn;
            internal uint m_nextStackLocal;
            internal uint m_nextStackOut;

            //
            // Constructor Methods
            //

            internal ArmCallState() // Default constructor required by TypeSystemSerializer.
            {
            }

            internal ArmCallState( Direction direction                                       ,
                                   int       numberOfWordsPassedInRegistersForIntegers       ,
                                   int       numberOfWordsPassedInRegistersForFloatingPoints ,
                                   int       numberOfWordsPerArgument                        ) : base( direction )
            {
                m_numberOfWordsPassedInRegistersForIntegers       = numberOfWordsPassedInRegistersForIntegers;
                m_numberOfWordsPassedInRegistersForFloatingPoints = numberOfWordsPassedInRegistersForFloatingPoints;
                m_numberOfWordsPerArgument                        = numberOfWordsPerArgument;
            }

            //
            // Helper Methods
            //

            public override void ApplyTransformation( TransformationContext context )
            {
                ZeligIR.TransformationContextForCodeTransformation context2 = (ZeligIR.TransformationContextForCodeTransformation)context;

                context2.Push( this );

                base.ApplyTransformation( context2 );

                context2.Transform( ref m_numberOfWordsPassedInRegistersForIntegers       );
                context2.Transform( ref m_numberOfWordsPassedInRegistersForFloatingPoints );
                context2.Transform( ref m_numberOfWordsPerArgument                        );

                context2.Transform( ref m_nextRegForArgumentsInteger                      );
                context2.Transform( ref m_nextRegForArgumentsFloatingPoint                );
                context2.Transform( ref m_nextRegForResultValueInteger                    );
                context2.Transform( ref m_nextRegForResultValueFloatingPoint              );

                context2.Transform( ref m_nextStackIn                                     );
                context2.Transform( ref m_nextStackLocal                                  );
                context2.Transform( ref m_nextStackOut                                    );

                context2.Pop();
            }

            public override ZeligIR.Abstractions.RegisterDescriptor GetNextRegister( ZeligIR.Abstractions.Platform                                     platform   ,
                                                                                TypeRepresentation                                                sourceTd   ,
                                                                                TypeRepresentation                                                fragmentTd ,
                                                                                ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind       )
            {
                switch(kind)
                {
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister:
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument:
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue:
                        int idx = GetNextIndex( platform, sourceTd, fragmentTd, kind );

                        return platform.GetRegisters()[idx];
                }

                throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind );
            }

            public override int GetNextIndex( ZeligIR.Abstractions.Platform                                     platform   ,
                                              TypeRepresentation                                                sourceTd   ,
                                              TypeRepresentation                                                fragmentTd ,
                                              ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind       )
            {
                switch(kind)
                {
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister:
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument:
                        return GetNextIndex( platform, fragmentTd, ref m_nextRegForArgumentsInteger, ref m_nextRegForArgumentsFloatingPoint );

                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue:
                        return GetNextIndex( platform, fragmentTd, ref m_nextRegForResultValueInteger, ref m_nextRegForResultValueFloatingPoint );

                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister:
                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation:
                        return (int)m_nextStackIn++;

                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackLocalLocation:
                        return (int)m_nextStackLocal++;

                    case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation:
                        return (int)m_nextStackOut++;
                }

                throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind );
            }

            public override bool CanMapToRegister( ZeligIR.Abstractions.Platform platform ,
                                                   TypeRepresentation            td       )
            {
                uint requiredRegisters = td.SizeOfHoldingVariableInWords;

                if(ShouldUseFloatingPointRegister( platform, td ))
                {
                    uint nextReg = m_nextRegForArgumentsFloatingPoint;

                    if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary.

                    return (          requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints &&
                            nextReg + requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints  );
                }
                else
                {
                    return (                               requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers &&
                            m_nextRegForArgumentsInteger + requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers  );
                }
            }

            public override bool CanMapResultToRegister( ZeligIR.Abstractions.Platform platform ,
                                                         TypeRepresentation            td       )
            {
                uint requiredRegisters = td.SizeOfHoldingVariableInWords;

                return (requiredRegisters <= m_numberOfWordsPerArgument);
            }

            //--//

            private static bool ShouldUseFloatingPointRegister( ZeligIR.Abstractions.Platform platform ,
                                                                TypeRepresentation            td       )
            {
                if(td.IsFloatingPoint)
                {
                    ArmPlatform paArm = (ArmPlatform)platform;

                    if(paArm.HasVFPv2)
                    {
                        return true;
                    }
                }

                return false;
            }

            private static int GetNextIndex(     ZeligIR.Abstractions.Platform platform             ,
                                                 TypeRepresentation            td                   ,
                                             ref uint                          nextRegInteger       ,
                                             ref uint                          nextRegFloatingPoint )
            {
                uint encoding;

                if(ShouldUseFloatingPointRegister( platform, td ))
                {
                    uint requiredRegisters = td.SizeOfHoldingVariableInWords;
                    uint nextReg           = nextRegFloatingPoint;

                    if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary.

                    nextRegFloatingPoint = nextReg + requiredRegisters;

                    if(requiredRegisters == 2)
                    {
                        encoding = EncodingDefinition_VFP.c_register_d0 + (nextReg / 2);
                    }
                    else
                    {
                        encoding = EncodingDefinition_VFP.c_register_s0 + nextReg;
                    }
                }
                else
                {
                    uint nextReg = nextRegInteger++;

                    encoding = EncodingDefinition.c_register_r0 + nextReg;
                }

                foreach(var regDesc in platform.GetRegisters())
                {
                    if(regDesc.Encoding == encoding)
                    {
                        return regDesc.Index;
                    }
                }

                throw TypeConsistencyErrorException.Create( "Failed to find register with encoding {0}", encoding );
            }
        }

        //
        // State
        //

        internal int m_numberOfWordsPassedInRegistersForIntegers       = 4;
        internal int m_numberOfWordsPassedInRegistersForFloatingPoints = 4;
        internal int m_numberOfWordsPerArgument                        = 2;

        //
        // Constructor Methods
        //

        public ArmCallingConvention() // Default constructor required by TypeSystemSerializer.
        {
        }

        public ArmCallingConvention( ZeligIR.TypeSystemForCodeTransformation typeSystem ) : base( typeSystem )
        {
        }

        //
        // Helper Methods
        //

        public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation  ts    ,
                                                       ZeligIR.CompilationSteps.DelegationCache cache )
        {
        }

        //--//

        public override CallState CreateCallState( Direction direction )
        {
            ArmPlatform paArm = (ArmPlatform)m_typeSystem.PlatformAbstraction;

            if(paArm.HasVFPv2)
            {
                return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, m_numberOfWordsPassedInRegistersForFloatingPoints, m_numberOfWordsPerArgument );
            }
            else
            {
                return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, 0, m_numberOfWordsPerArgument );
            }
        }

        public override ZeligIR.Expression[] AssignArgument( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg         ,
                                                             ZeligIR.Operator                                   insertionOp ,
                                                             ZeligIR.Expression                                 ex          ,
                                                             TypeRepresentation                                 td          ,
                                                             ZeligIR.Abstractions.CallingConvention.CallState   callState   )
        {
            ZeligIR.VariableExpression                                        sourceVar = ex as ZeligIR.VariableExpression;
            ZeligIR.VariableExpression.DebugInfo                              debugInfo;
            ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind;

            if(callState.Direction == Direction.Caller)
            {
                //
                // On the caller side, we don't associate the fragments with the original expression,
                // since the same fragments will be used for multiple expressions, on different method calls.
                //
                sourceVar = null;
                debugInfo = null;
            }
            else
            {
                debugInfo = sourceVar.DebugName;
            }

            if(callState.CanMapToRegister( cfg.TypeSystem.PlatformAbstraction, td ))
            {
                if(callState.Direction == Direction.Callee)
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister;
                }
                else
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument;
                }

                return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind );
            }
            else
            {
                if(callState.Direction == Direction.Callee)
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister;
                }
                else
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation;
                }

                return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind );
            }
        }

        public override ZeligIR.Expression[] AssignReturnValue( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg           ,
                                                                ZeligIR.Operator                                   insertionOp   ,
                                                                ZeligIR.VariableExpression                         exReturnValue ,
                                                                TypeRepresentation                                 tdReturnValue ,
                                                                ZeligIR.Abstractions.CallingConvention.CallState   callState     )
        {
            ZeligIR.VariableExpression.DebugInfo debugInfo;

            if(exReturnValue != null)
            {
                debugInfo = exReturnValue.DebugName;
            }
            else
            {
                debugInfo = null;
            }

            if(callState.Direction == Direction.Caller)
            {
                //
                // On the caller side, we don't associate the fragments with the original expression,
                // since the same fragments will be used for multiple expressions, on different method calls.
                //
                exReturnValue = null;
                debugInfo     = null;
            }

            if(callState.CanMapResultToRegister( cfg.TypeSystem.PlatformAbstraction, tdReturnValue ))
            {
                return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue );
            }
            else
            {
                ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind;

                if(callState.Direction == Direction.Callee)
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation;
                }
                else
                {
                    kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation;
                }

                //
                // For methods whose return value is too big, share the return value variable as the first slot on the stack.
                //
                return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, kind );
            }
        }

        public override ZeligIR.VariableExpression[] CollectExpressionsToInvalidate( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg          ,
                                                                                ZeligIR.CallOperator                               op           ,
                                                                                ZeligIR.Expression[]                               resFragments )
        {
            ZeligIR.VariableExpression[]                     res       = ZeligIR.VariableExpression.SharedEmptyArray;
            ZeligIR.Abstractions.CallingConvention.CallState callState = cfg.TypeSystem.CallingConvention.CreateCallState( Direction.Caller );

            //
            // Because of the aliasing between physical registers, it's important that we add the expressions to invalidate
            // in the right order:
            //
            //  1) Actual return values (first because we need that value after the call)
            //  2) Formal return values
            //  3) Call arguments
            //  4) Registers and stack locations affected by the calling convention.
            //
            res = MergeFragments( res, resFragments );

            if(op != null)
            {
                MethodRepresentation md  = op.TargetMethod;

                {
                    TypeRepresentation tdReturn = md.ReturnType;
                    if(tdReturn != cfg.TypeSystem.WellKnownTypes.System_Void)
                    {
                        ZeligIR.Expression[] resFormalFragments = AssignReturnValue( cfg, null, null, tdReturn, callState );

                        res = MergeFragments( res, resFormalFragments );
                    }
                }

                foreach(TypeRepresentation tdArg in md.ThisPlusArguments)
                {
                    ZeligIR.Expression[] argFragments = AssignArgument( cfg, null, null, tdArg, callState );

                    res = MergeFragments( res, argFragments );
                }
            }

            foreach(ZeligIR.Abstractions.RegisterDescriptor regDesc in m_typeSystem.PlatformAbstraction.GetRegisters())
            {
                bool fAdd = false;

                if(regDesc.InIntegerRegisterFile)
                {
                    //
                    // These registers are part of the calling convention, they can be scratched.
                    //
                    if((regDesc.Encoding -  EncodingDefinition.c_register_r0) < m_numberOfWordsPassedInRegistersForIntegers ||
                        regDesc.Encoding == EncodingDefinition.c_register_r12                                               ||
                        regDesc.Encoding == EncodingDefinition.c_register_lr                                                 )
                    {
                        fAdd = true;
                    }
                }

                if(regDesc.InFloatingPointRegisterFile)
                {
                    //
                    // These registers are part of the calling convention, they can be scratched.
                    //
                    if(regDesc.IsDoublePrecision)
                    {
                        if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
                        {
                            fAdd = true;
                        }
                    }
                    else
                    {
                        if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
                        {
                            fAdd = true;
                        }
                    }
                }

                if(fAdd)
                {
                    res = AddUniqueToFragment( res, cfg.AllocatePhysicalRegister( regDesc ) );
                }
            }

            res = AddUniqueToFragment( res, cfg.AllocateConditionCode() );

            return CollectAddressTakenExpressionsToInvalidate( cfg, res, op );
        }

        public override bool ShouldSaveRegister( ZeligIR.Abstractions.RegisterDescriptor regDesc )
        {
            if(regDesc.IsSpecial)
            {
                return false;
            }

            if(regDesc.IsSystemRegister)
            {
                return false;
            }

            if(regDesc.InIntegerRegisterFile)
            {
                if((regDesc.Encoding -  EncodingDefinition.c_register_r0 ) < m_numberOfWordsPassedInRegistersForIntegers ||
                    regDesc.Encoding == EncodingDefinition.c_register_r12                                                ||
                    regDesc.Encoding == EncodingDefinition.c_register_lr                                                  )
                {
                    //
                    // These registers are part of the calling convention, they can be scratched.
                    //
                    return false;
                }
            }

            if(regDesc.InFloatingPointRegisterFile)
            {
                if(regDesc.IsDoublePrecision)
                {
                    if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
                    {
                        //
                        // These registers are part of the calling convention, they can be scratched.
                        //
                        return false;
                    }
                }
                else
                {
                    if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints)
                    {
                        //
                        // These registers are part of the calling convention, they can be scratched.
                        //
                        return false;
                    }
                }
            }

            return true;
        }
    }
}


text:
echo "                                                                         "
echo "  ___  ___                       _   _        ___  ________ _____ _____  "
echo "  |  \/  |                      | | | |       |  \/  |  _  |_   _|_   _| "
echo "  | .  . | ___   __ _ _   _  ___| |_| |_ ___  | .  . | | | | | |   | |   "
echo "  | |\/| |/ _ \ / _\ | | | |/ _ \ __| __/ _ \ | |\/| | | | | | |   | |   "
echo "  | |  | | (_) | (_| | |_| |  __/ |_| ||  __/ | |  | \ \/' / | |   | |   "
echo "  \_|  |_/\___/ \__, |\__,_|\___|\__|\__\___| \_|  |_/\_/\_\ \_/   \_/   "
echo "                   | |                                                   "
echo "                   |_|                                                   "
echo "                                                                         "
echo "                                               version: 0.16-SNAPSHOT    "

cd "$(dirname "$0")"

# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

# Only set MOQUETTE_HOME if not already set
[ -f "$MOQUETTE_HOME"/bin/moquette.sh ] || MOQUETTE_HOME=`cd "$PRGDIR/.." ; pwd`
export MOQUETTE_HOME

# Set JavaHome if it exists
if [ -f "${JAVA_HOME}/bin/java" ]; then
   JAVA=${JAVA_HOME}/bin/java
else
   JAVA=java
fi
export JAVA

LOG_FILE=$MOQUETTE_HOME/config/moquette-log.properties
MOQUETTE_PATH=$MOQUETTE_HOME/
#LOG_CONSOLE_LEVEL=info
#LOG_FILE_LEVEL=fine
JAVA_OPTS_SCRIPT="-XX:+HeapDumpOnOutOfMemoryError -Djava.awt.headless=true"

## Use the Hotspot garbage-first collector.
JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC"

## Have the JVM do less remembered set work during STW, instead
## preferring concurrent GC. Reduces p99.9 latency.
JAVA_OPTS="$JAVA_OPTS -XX:G1RSetUpdatingPauseTimePercent=5"

## Main G1GC tunable: lowering the pause target will lower throughput and vise versa.
## 200ms is the JVM default and lowest viable setting
## 1000ms increases throughput. Keep it smaller than the timeouts.
JAVA_OPTS="$JAVA_OPTS -XX:MaxGCPauseMillis=500"

## Optional G1 Settings

# Save CPU time on large (>= 16GB) heaps by delaying region scanning
# until the heap is 70% full. The default in Hotspot 8u40 is 40%.
#JAVA_OPTS="$JAVA_OPTS -XX:InitiatingHeapOccupancyPercent=70"

# For systems with > 8 cores, the default ParallelGCThreads is 5/8 the number of logical cores.
# Otherwise equal to the number of cores when 8 or less.
# Machines with > 10 cores should try setting these to <= full cores.
#JAVA_OPTS="$JAVA_OPTS -XX:ParallelGCThreads=16"

# By default, ConcGCThreads is 1/4 of ParallelGCThreads.
# Setting both to the same value can reduce STW durations.
#JAVA_OPTS="$JAVA_OPTS -XX:ConcGCThreads=16"

### GC logging options -- uncomment to enable

JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDateStamps"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintHeapAtGC"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintTenuringDistribution"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCApplicationStoppedTime"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintPromotionFailure"
#JAVA_OPTS="$JAVA_OPTS -XX:PrintFLSStatistics=1"
#JAVA_OPTS="$JAVA_OPTS -Xloggc:/var/log/moquette/gc.log"
JAVA_OPTS="$JAVA_OPTS -Xloggc:$MOQUETTE_HOME/gc.log"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseGCLogFileRotation"
#JAVA_OPTS="$JAVA_OPTS -XX:NumberOfGCLogFiles=10"
#JAVA_OPTS="$JAVA_OPTS -XX:GCLogFileSize=10M"

echo '$JAVA -server $JAVA_OPTS $JAVA_OPTS_SCRIPT -Dlog4j.configuration="file:$LOG_FILE" -Dmoquette.path="$MOQUETTE_PATH" -cp "$MOQUETTE_HOME/lib/*" io.moquette.broker.Server'
$JAVA -server $JAVA_OPTS $JAVA_OPTS_SCRIPT -Dlog4j.configuration="file:$LOG_FILE" -Dmoquette.path="$MOQUETTE_PATH" -cp "$MOQUETTE_HOME/lib/*" io.moquette.broker.Server


text:
var controllers = require('./controllers');

module.exports.init = function(app) {

	app.get('/cache', controllers.Cache.list);
	app.get('/cache/:key', controllers.Cache.read);
	app.post('/cache/:key', controllers.Cache.createOrUpdate);
	app.put('/cache/:key', controllers.Cache.createOrUpdate);
	app.delete('/cache/:key', controllers.Cache.deleteOne);
	app.delete('/cache', controllers.Cache.deleteAll);

};


text:
#pragma once
#include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h>
#include <aws/kinesisanalyticsv2/KinesisAnalyticsV2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/kinesisanalyticsv2/model/ApplicationMaintenanceConfigurationUpdate.h>
#include <utility>

namespace Aws
{
namespace KinesisAnalyticsV2
{
namespace Model
{

  /**
   */
  class AWS_KINESISANALYTICSV2_API UpdateApplicationMaintenanceConfigurationRequest : public KinesisAnalyticsV2Request
  {
  public:
    UpdateApplicationMaintenanceConfigurationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateApplicationMaintenanceConfiguration"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline const Aws::String& GetApplicationName() const{ return m_applicationName; }

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline bool ApplicationNameHasBeenSet() const { return m_applicationNameHasBeenSet; }

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline void SetApplicationName(const Aws::String& value) { m_applicationNameHasBeenSet = true; m_applicationName = value; }

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline void SetApplicationName(Aws::String&& value) { m_applicationNameHasBeenSet = true; m_applicationName = std::move(value); }

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline void SetApplicationName(const char* value) { m_applicationNameHasBeenSet = true; m_applicationName.assign(value); }

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline UpdateApplicationMaintenanceConfigurationRequest& WithApplicationName(const Aws::String& value) { SetApplicationName(value); return *this;}

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline UpdateApplicationMaintenanceConfigurationRequest& WithApplicationName(Aws::String&& value) { SetApplicationName(std::move(value)); return *this;}

    /**
     *
The name of the application for which you want to update the maintenance
     * configuration.

     */
    inline UpdateApplicationMaintenanceConfigurationRequest& WithApplicationName(const char* value) { SetApplicationName(value); return *this;}

    /**
     *
Describes the application maintenance configuration update.

     */
    inline const ApplicationMaintenanceConfigurationUpdate& GetApplicationMaintenanceConfigurationUpdate() const{ return m_applicationMaintenanceConfigurationUpdate; }

    /**
     *
Describes the application maintenance configuration update.

     */
    inline bool ApplicationMaintenanceConfigurationUpdateHasBeenSet() const { return m_applicationMaintenanceConfigurationUpdateHasBeenSet; }

    /**
     *
Describes the application maintenance configuration update.

     */
    inline void SetApplicationMaintenanceConfigurationUpdate(const ApplicationMaintenanceConfigurationUpdate& value) { m_applicationMaintenanceConfigurationUpdateHasBeenSet = true; m_applicationMaintenanceConfigurationUpdate = value; }

    /**
     *
Describes the application maintenance configuration update.

     */
    inline void SetApplicationMaintenanceConfigurationUpdate(ApplicationMaintenanceConfigurationUpdate&& value) { m_applicationMaintenanceConfigurationUpdateHasBeenSet = true; m_applicationMaintenanceConfigurationUpdate = std::move(value); }

    /**
     *
Describes the application maintenance configuration update.

     */
    inline UpdateApplicationMaintenanceConfigurationRequest& WithApplicationMaintenanceConfigurationUpdate(const ApplicationMaintenanceConfigurationUpdate& value) { SetApplicationMaintenanceConfigurationUpdate(value); return *this;}

    /**
     *
Describes the application maintenance configuration update.

     */
    inline UpdateApplicationMaintenanceConfigurationRequest& WithApplicationMaintenanceConfigurationUpdate(ApplicationMaintenanceConfigurationUpdate&& value) { SetApplicationMaintenanceConfigurationUpdate(std::move(value)); return *this;}

  private:

    Aws::String m_applicationName;
    bool m_applicationNameHasBeenSet = false;

    ApplicationMaintenanceConfigurationUpdate m_applicationMaintenanceConfigurationUpdate;
    bool m_applicationMaintenanceConfigurationUpdateHasBeenSet = false;
  };

} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws


text:
{
  graphitePort: 2003
, graphiteHost: "graphite.host.com"
, port: 8125
, saveCounts: true
}


text:
package main.com.pcache.DO.timeseries;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import main.com.pcache.DO.PCacheTimestamp;
import main.com.pcache.exceptions.PCacheException;
import main.com.pcache.utils.Commons;

import com.google.gson.Gson;

/**
 * The central class for storing timeseries
 */
public class VariableTimeseries {

	/**
	 * The main treemap to represent the timeseries.
	 * A treemap is favourable here because of the inbuilt ordering that comes
	 * along with it. This allows the points that are inserted later on to
	 * find the right place. Also treemaps have a neat "submap" feature that
	 * allows to get a subset of a map
	 */
	private Map<PCacheTimestamp, String> _timeseries;

	/**
	 * Constructor. Initialize a time series.
	 * @param timestamps an array of ISO8601 timestamps. The timestamps are to
	 * 			be in ISO8601 format with miliseconds.
	 * 			i.e. YYYY-MM-DDTHH:MM:SS.SSS+Z (2014-03-30T20:13:00.000+05:30)
	 * @param dataPoints the data points associated with the timestamps. They
	 * 			SHOULD have a one to one correlation.
	 * @throws PCacheException thrown if the no. of timestamps do not match
	 * 			the no. of data points
	 */
	public VariableTimeseries (List<String> timestamps,
			List<String> dataPoints) throws PCacheException {

		// Sanity Checks
		_exceptIfLengthUnequal(timestamps, dataPoints);

		// Declare a new tree map
		_timeseries = new TreeMap<PCacheTimestamp, String>();

		_addOrUpdatePoints(timestamps, dataPoints);

	}

	/**
	 * Constructor. Create a variable timeseries out of an existing set
	 * @param timeseries the Long - string mapping to create the
	 * 			variabletimeseries out of
	 */
	public VariableTimeseries(Map<PCacheTimestamp, String> timeseries) {
		this._timeseries = timeseries;
	}

	/**
	 * Get the size of the timeseries
	 * @return the size of the timeseries
	 */
	public int size() {
		return this._timeseries.size();
	}

	/**
	 * Check if a given timestamp exists within the series
	 * @param timestamp the timestamp to check for
	 * @return true/false based on its existance
	 * @throws PCacheException
	 */
	public boolean contains(String timestamp) throws PCacheException {

		return this._timeseries.containsKey(new PCacheTimestamp(timestamp));
	}

	/**
	 * A core procedure. This isn't called from the outside.
	 * Add or Update points inside the timeseries. The nature of the TreeMap
	 * allows us to do both of these things in the same call since the .put()
	 * function will replace an existsing value if it exists
	 * @param timestamps the set of timestamps to add/update
	 * @param dataPoints the associated set of data to the timestamps.
	 * 			Note: there should be a one to one correlation between the
	 * 			timestamps and the data points
	 * @throws PCacheException thrown if there is no one to one correlation
	 * 			between the timestamps and the data points
	 */
	private void _addOrUpdatePoints(List<String> timestamps,
			List<String> dataPoints) throws PCacheException{

		try {

			// Go through all the timestamps
			for (int i=0; i<timestamps.size(); i++) {

				// Pick up the timestamp and the data point
				String timestampISO8601 = timestamps.get(i);
				String dataPoint = dataPoints.get(i);

				// Add or update the timestamp, datapoint
				// Put does updates also. so 2 birds, one stone!
				_timeseries.put(new PCacheTimestamp(timestampISO8601), dataPoint);

			}
		}

		catch (NullPointerException ex) {
			throw new PCacheException("Timestamps and dataPoints should not be " +
					"null", ex);
		}

	}

	/**
	 * Add points to the timeseries
	 * @param timestamps the set of timestamps to add
	 * @param dataPoints the associated set of data points to add
	 * @throws PCacheException thrown if timeseries isn't associated to the
	 * 			datapoints or if the points already exist in the timeseries
	 */
	public void addPoints(List<String> timestamps,
			List<String> dataPoints) throws PCacheException {

		// Sanity checks
		_exceptIfLengthUnequal(timestamps, dataPoints);
		_exceptIfPointsExist(timestamps);

		// Call the core procedure to add points into the timeseries
		_addOrUpdatePoints(timestamps, dataPoints);

	}

	/**
	 * Update points in the timeseries
	 * @param timestamps the set of timestamps to update
	 * @param dataPoints the associated set of data points to update
	 * @throws PCacheException thrown if timeseries isn't associated to the
	 * 			datapoints or if the points don't exist in the timeseries
	 */
	public void updatePoints(List<String> timestamps,
			List<String> dataPoints) throws PCacheException {

		// Sanity checks
		_exceptIfLengthUnequal(timestamps, dataPoints);
		_exceptIfNoPointsExist(timestamps);

		// Call the core procedure to update points in the timeseries
		_addOrUpdatePoints(timestamps, dataPoints);

	}

	/**
	 * Remove a set of points from the timeseries
	 * @param timestamps the set of timestamps to remove
	 * @throws PCacheException thrown if one or more points specified to be
	 * 			deleted, doesn't exist
	 */
	public void removePoints(List<String> timestamps)
			throws PCacheException {

		// Sanity Checks
		_exceptIfNoPointsExist(timestamps);

		for (String timestamp : timestamps) {
			this._timeseries.remove(new PCacheTimestamp(timestamp));
		}

	}

	/**
	 * Get the set of points between 2 given timeseries'
	 * @param timestampFrom the ISO8601 timestamp representing the from
	 * @param timestampTo the ISO8601 timestamp representing the to
	 * @return a map of the timeseries - data representation for the given
	 * 			range
	 * @throws PCacheException
	 */
	public VariableTimeseries getRangeBetween(String timestampFrom,
			String timestampTo) throws PCacheException {

		// Return a timeseries
		return new VariableTimeseries(((TreeMap<PCacheTimestamp, String>) this._timeseries)
				.subMap(new PCacheTimestamp(timestampFrom), true,
						new PCacheTimestamp(timestampTo), true));

	}

	/**
	 * Get the set of points from a given timestamp till the last one
	 * @param timestampFrom the ISO8601 timestamp representing the from
	 * @return a map of the timeseries - data representation for the given
	 * 			range
	 * @throws PCacheException
	 */
	public VariableTimeseries getRangeFrom(String timestampFrom)
			throws PCacheException {

		// Get the last key in the series of timestamps
		PCacheTimestamp lastKey = ((TreeMap<PCacheTimestamp, String>)
				this._timeseries).lastKey();

		try {
			// Return a map
			return new VariableTimeseries(((TreeMap<PCacheTimestamp, String>)
					this._timeseries).subMap(new PCacheTimestamp(timestampFrom),
							true, lastKey, true));
		}

		catch (IllegalArgumentException ex) {
			throw new PCacheException("Timestamp provided exceeds the max " +
					"timestamp stored in the cache.", ex);
		}

	}

	/**
	 * Get the set of points from the first one till a given timestamp
	 * @param timestampFrom the ISO8601 timestamp representing the from
	 * @return a map of the timeseries - data representation for the given
	 * 			range
	 * @throws PCacheException
	 */
	public VariableTimeseries getRangeTo(String timestampTo)
			throws PCacheException {

		// Get the first key in the series of timestamps
		PCacheTimestamp firstKey = ((TreeMap<PCacheTimestamp, String>)
				this._timeseries).firstKey();

		try {
			// Return a map
			return new VariableTimeseries(((TreeMap<PCacheTimestamp, String>)
					this._timeseries).subMap(firstKey, true,
							new PCacheTimestamp(timestampTo), true));
		}

		catch (IllegalArgumentException ex) {
			throw new PCacheException("Timestamp provided preceeds the min " +
					"timestamp stored in the cache.", ex);
		}

	}

	/**
	 * Get the entire timeseries
	 * @return the entire timeseries map
	 */
	public VariableTimeseries getAll() {
		return this;
	}

	/**
	 * Return a particular timestamps value
	 * @param timestamp the timestamp to look for in the map
	 * @return the value for that timestamp, null if the timestamp isn't present
	 * @throws PCacheException thrown if:
	 * 			* timestamp not in ISO8601 format
	 */
	public String getOne(String timestamp) throws PCacheException {

		long milis = Commons.convertISO8601toMilis(timestamp);
		return this._timeseries.get(milis);
	}

	/**
	 * Convert the current timeseries to JSON format with the key as the
	 * ISO8601 formatted timestamp
	 * @return the JSON
	 */
	public String toJson() {

		Map<String, String> jsonMap = new TreeMap<String, String>();

		for (Entry<PCacheTimestamp, String> entry : this._timeseries.entrySet())
		{
			PCacheTimestamp ts = entry.getKey();
			jsonMap.put(ts.toString(), entry.getValue());
		}

		final Gson gson = new Gson();
		return gson.toJson(jsonMap);

	}

	/**
	 * Check if the length of the timeseries is not equal to the length of the
	 * data points that it is associated with
	 * @param timestamps the set of timestamps
	 * @param dataPoints the associated set of data points
	 * @throws PCacheException thrown if the length of both are unequal
	 */
	private void _exceptIfLengthUnequal(List<String> timestamps,
			List<String> dataPoints) throws PCacheException {

		try {
			if (timestamps.size() != dataPoints.size()) {
				throw new PCacheException("Sizes don't match. The number of data " +
						"points should equal the number of timestamps");
			}
		}

		catch (NullPointerException ex) {
			throw new PCacheException("Timestamps and dataPoints should not be " +
					"null", ex);
		}

		catch (IllegalArgumentException ex) {
			throw new PCacheException("One or more of the timestamps isn't in " +
					"ISO8601 format", ex);
		}

	}

	/**
	 * Check if the set of points already exist in the cache
	 * @param timestamps the set of timestamps to check
	 * @throws PCacheException thrown if the set of points already exist in the
	 * 			cache
	 */
	private void _exceptIfPointsExist(List<String> timestamps)
			throws PCacheException {

		try {

			// Go through the timestamps
			for (String timestamp : timestamps) {

				// If timeseries already contains it, except
				if (this._timeseries.containsKey(new PCacheTimestamp(timestamp))) {
					throw new PCacheException("Some point(s) already exist in the "
							+ "timeseries");
				}

			}
		}

		catch (NullPointerException ex) {
			throw new PCacheException("Timestamps and dataPoints should not be " +
					"null", ex);
		}

		catch (IllegalArgumentException ex) {
			throw new PCacheException("One or more of the timestamps isn't in " +
					"ISO8601 format", ex);
		}

	}

	/**
	 * Check if the set of points don't exist in the cache
	 * @param timestamps the set of timestamps to check
	 * @throws PCacheException thrown if the set of points don't exist in the
	 * 			cache
	 */
	private void _exceptIfNoPointsExist(List<String> timestamps)
			throws PCacheException {

		try {
			// Go through the timestamps
			for (String timestamp : timestamps) {

				// If the timeseries doesn't contain it, except
				if (!this._timeseries.containsKey(new PCacheTimestamp(timestamp))) {
					throw new PCacheException("Some point(s) don't exist in the "
							+ "timeseries");
				}

			}
		}

		catch (NullPointerException ex) {
			throw new PCacheException("Timestamps and dataPoints should not be " +
					"null", ex);
		}

		catch (IllegalArgumentException ex) {
			throw new PCacheException("One or more of the timestamps isn't in " +
					"ISO8601 format", ex);
		}

	}

}


text:
package base

import (
	"golang.org/x/net/context"
	"google.golang.org/grpc/balancer"
	"google.golang.org/grpc/connectivity"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/resolver"
)

type baseBuilder struct {
	name          string
	pickerBuilder PickerBuilder
}

func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
	return &baseBalancer{
		cc:            cc,
		pickerBuilder: bb.pickerBuilder,

		subConns: make(map[resolver.Address]balancer.SubConn),
		scStates: make(map[balancer.SubConn]connectivity.State),
		csEvltr:  &connectivityStateEvaluator{},
		// Initialize picker to a picker that always return
		// ErrNoSubConnAvailable, because when state of a SubConn changes, we
		// may call UpdateBalancerState with this picker.
		picker: NewErrPicker(balancer.ErrNoSubConnAvailable),
	}
}

func (bb *baseBuilder) Name() string {
	return bb.name
}

type baseBalancer struct {
	cc            balancer.ClientConn
	pickerBuilder PickerBuilder

	csEvltr *connectivityStateEvaluator
	state   connectivity.State

	subConns map[resolver.Address]balancer.SubConn
	scStates map[balancer.SubConn]connectivity.State
	picker   balancer.Picker
}

func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) {
	if err != nil {
		grpclog.Infof("base.baseBalancer: HandleResolvedAddrs called with error %v", err)
		return
	}
	grpclog.Infoln("base.baseBalancer: got new resolved addresses: ", addrs)
	// addrsSet is the set converted from addrs, it's used for quick lookup of an address.
	addrsSet := make(map[resolver.Address]struct{})
	for _, a := range addrs {
		addrsSet[a] = struct{}{}
		if _, ok := b.subConns[a]; !ok {
			// a is a new address (not existing in b.subConns).
			sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{})
			if err != nil {
				grpclog.Warningf("base.baseBalancer: failed to create new SubConn: %v", err)
				continue
			}
			b.subConns[a] = sc
			b.scStates[sc] = connectivity.Idle
			sc.Connect()
		}
	}
	for a, sc := range b.subConns {
		// a was removed by resolver.
		if _, ok := addrsSet[a]; !ok {
			b.cc.RemoveSubConn(sc)
			delete(b.subConns, a)
			// Keep the state of this sc in b.scStates until sc's state becomes Shutdown.
			// The entry will be deleted in HandleSubConnStateChange.
		}
	}
}

// regeneratePicker takes a snapshot of the balancer, and generates a picker
// from it. The picker is
//  - errPicker with ErrTransientFailure if the balancer is in TransientFailure,
//  - built by the pickerBuilder with all READY SubConns otherwise.
func (b *baseBalancer) regeneratePicker() {
	if b.state == connectivity.TransientFailure {
		b.picker = NewErrPicker(balancer.ErrTransientFailure)
		return
	}
	readySCs := make(map[resolver.Address]balancer.SubConn)

	// Filter out all ready SCs from full subConn map.
	for addr, sc := range b.subConns {
		if st, ok := b.scStates[sc]; ok && st == connectivity.Ready {
			readySCs[addr] = sc
		}
	}
	b.picker = b.pickerBuilder.Build(readySCs)
}

func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
	grpclog.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s)
	oldS, ok := b.scStates[sc]
	if !ok {
		grpclog.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s)
		return
	}
	b.scStates[sc] = s
	switch s {
	case connectivity.Idle:
		sc.Connect()
	case connectivity.Shutdown:
		// When an address was removed by resolver, b called RemoveSubConn but
		// kept the sc's state in scStates. Remove state for this sc here.
		delete(b.scStates, sc)
	}

	oldAggrState := b.state
	b.state = b.csEvltr.recordTransition(oldS, s)

	// Regenerate picker when one of the following happens:
	//  - this sc became ready from not-ready
	//  - this sc became not-ready from ready
	//  - the aggregated state of balancer became TransientFailure from non-TransientFailure
	//  - the aggregated state of balancer became non-TransientFailure from TransientFailure
	if (s == connectivity.Ready) != (oldS == connectivity.Ready) ||
		(b.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) {
		b.regeneratePicker()
	}

	b.cc.UpdateBalancerState(b.state, b.picker)
}

// Close is a nop because base balancer doesn't have internal state to clean up,
// and it doesn't need to call RemoveSubConn for the SubConns.
func (b *baseBalancer) Close() {
}

// NewErrPicker returns a picker that always returns err on Pick().
func NewErrPicker(err error) balancer.Picker {
	return &errPicker{err: err}
}

type errPicker struct {
	err error // Pick() always returns this err.
}

func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
	return nil, nil, p.err
}

// connectivityStateEvaluator gets updated by addrConns when their
// states transition, based on which it evaluates the state of
// ClientConn.
type connectivityStateEvaluator struct {
	numReady            uint64 // Number of addrConns in ready state.
	numConnecting       uint64 // Number of addrConns in connecting state.
	numTransientFailure uint64 // Number of addrConns in transientFailure.
}

// recordTransition records state change happening in every subConn and based on
// that it evaluates what aggregated state should be.
// It can only transition between Ready, Connecting and TransientFailure. Other states,
// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection
// before any subConn is created ClientConn is in idle state. In the end when ClientConn
// closes it is in Shutdown state.
//
// recordTransition should only be called synchronously from the same goroutine.
func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State {
	// Update counters.
	for idx, state := range []connectivity.State{oldState, newState} {
		updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
		switch state {
		case connectivity.Ready:
			cse.numReady += updateVal
		case connectivity.Connecting:
			cse.numConnecting += updateVal
		case connectivity.TransientFailure:
			cse.numTransientFailure += updateVal
		}
	}

	// Evaluate.
	if cse.numReady > 0 {
		return connectivity.Ready
	}
	if cse.numConnecting > 0 {
		return connectivity.Connecting
	}
	return connectivity.TransientFailure
}


text:
package gw.internal.gosu.parser.expressions;

import gw.internal.gosu.parser.Expression;

import gw.util.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import gw.lang.parser.StandardCoercionManager;
import gw.lang.parser.expressions.ICollectionInitializerExpression;
import gw.lang.parser.IExpression;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.java.IJavaType;
import gw.lang.reflect.java.JavaTypes;

/**
 */
public class CollectionInitializerExpression extends Expression implements ICollectionInitializerExpression
{
  private ArrayList<IExpression> _values;

  public boolean isCompileTimeConstant()
  {
    for( IExpression expr : getValues() )
    {
      if( !expr.isCompileTimeConstant() )
      {
        return false;
      }
    }
    return true;
  }

  public Object evaluate()
  {
    if( !isCompileTimeConstant() )
    {
      return super.evaluate();
    }

    // Convert to an array for compile-time constant e.g., {a,b,c} is legal array expr for Annotation args
    Class<?> arrayClass = getArrayClass( getType() );
    List<IExpression> values = getValues();
    Object instance = Array.newInstance( arrayClass.getComponentType(), values.size() );
    for( int i = 0; i < Array.getLength( instance ); i++ )
    {
      IExpression expr = values.get( i );
      Object value = expr.evaluate();
      if( value instanceof BigDecimal || value instanceof BigInteger )
      {
        value = value.toString();
      }
      Array.set( instance, i, value );
    }
    return instance;
  }

  public static Class<?> getArrayClass( IType type )
  {
    if( JavaTypes.COLLECTION().isAssignableFrom( type ) )
    {
      return Array.newInstance(getArrayClass(type.getTypeParameters()[0]), 0).getClass();
    }
    if( StandardCoercionManager.isBoxed( type ) )
    {
      type = TypeSystem.getPrimitiveType( type );
    }
    else if( type == JavaTypes.BIG_DECIMAL() || type == JavaTypes.BIG_INTEGER())
    {
      type = JavaTypes.STRING();
    }
    else if( type.isEnum() )
    {
      // An enum evaluates as the name of the enum constant field (for compile-time constant evaluation)
      type = JavaTypes.STRING();
    }
    if( !type.isPrimitive() && type != JavaTypes.STRING() )
    {
      throw new IllegalStateException( "A compile-time constant expression must be either primitive, String, or Enum" );
    }
    return ((IJavaType)type).getBackingClass();
  }

  @Override
  public String toString()
  {
    StringBuilder sb = new StringBuilder();
    sb.append( "{" );
    if( _values != null )
    {
      for( int i = 0; i < _values.size(); i++ )
      {
        IExpression expression = _values.get( i );
        sb.append( expression.toString() );
        if( i < _values.size() - 1 )
        {
          sb.append( ", " );
        }
      }
    }
    sb.append( "}" );
    return sb.toString();
  }

  public void initialize( Object newObject )
  {
    if( _values != null )
    {
      Collection collection = (Collection)newObject;
      for( int i = 0; i < _values.size(); i++ )
      {
        IExpression expression = _values.get( i );
        Object val = expression.evaluate();
        collection.add( val );
      }
    }
  }

  public void add( Expression expression )
  {
    if( _values == null )
    {
      _values = new ArrayList<IExpression>();
    }
    _values.add( expression );
  }

  public void addFirst( Expression expression )
  {
    if( _values == null )
    {
      _values = new ArrayList<IExpression>();
    }
    _values.add( 0, expression );
  }

  public List<IExpression> getValues()
  {
    return _values == null ? Collections.<IExpression>emptyList() : _values;
  }
}


text:
import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { GenericApi } from './genericapi.service';
import { JsonApiData } from '../../models/json/jsonapi-data';
import { StixLabelEnum } from '../../models/stix/stix-label.enum';
import { AttackPattern } from 'stix';
import { StixUrls } from '../../global/enums/stix-urls.enum';
import { StixApiOptions } from '../../global/models/stix-api-options';
import { Constance } from '../../utils/constance';
import { HttpEventType } from '@angular/common/http';
import { GridFSFile } from '../../global/models/grid-fs-file';

describe('GenericApi service', () => {
    let httpMock: HttpTestingController;
    let api: GenericApi;

    interface WhatsIt {
        animal?: any,
        vegetable?: any,
        mineral?: any,
    }

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [GenericApi],
        });
        api = TestBed.get(GenericApi);
        httpMock = TestBed.get(HttpTestingController);
    });

    afterEach(() => {
        httpMock.verify();
    });

    it('should GET', () => {
        api.get('/testdata', 'nao').subscribe((response) => {
            expect(response).toBeDefined();
            expect(response.success).toBeUndefined();
            expect(response.length).toBe(2);
            expect(response[0]['key1']).toEqual('value1');
            expect(response[1]['key2']).toEqual('value2');
        });
        const req = httpMock.expectOne(`/testdata/nao`);
        expect(req.request.method).toBe('GET');
        req.flush({
            success: true,
            data: [
                {'key1': 'value1'},
                {'key2': 'value2'},
            ]
        });
    });

    it('should GET as a type', () => {
        api.getAs<JsonApiData<WhatsIt>>('/isit', 'animal').subscribe((response) => {
            expect(response).toBeDefined();
            expect(response.type).toEqual('animal');
            expect(response.attributes['animal']).toEqual('pangolin');
        });
        const req = httpMock.expectOne(`/isit/animal`);
        expect(req.request.method).toBe('GET');
        req.flush({
            data: {
                type: 'animal',
                attributes: {'animal': 'pangolin'}
            },
        });
    });

    it('should POST', () => {
        api.post('/testdork', {'when': 'nao'}).subscribe((response) => {
            expect(response).toEqual('never');
        });
        const req = httpMock.expectOne(`/testdork`);
        expect(req.request.method).toBe('POST');
        req.flush({
            success: false,
            data: 'never'
        });
    });

    it('should POST as a type', () => {
        const kumquat = {
            'common-name': 'kumquat',
            'scientific-name' : 'fortunella',
        }
        api.postAs<JsonApiData<WhatsIt>>('/guess', kumquat).subscribe((response) => {
            expect(response).toBeDefined();
            expect(response['vegetable']).toBe(kumquat);
        });
        const req = httpMock.expectOne(`/guess`);
        expect(req.request.method).toBe('POST');
        req.flush({ data: {vegetable: kumquat} });
    });

    it('should PATCH', () => {
        api.patch('/testderp', {'question': 'why'}).subscribe((response) => {
            expect(response).toBeDefined();
            expect(response.answer).toEqual('because');
        });
        const req = httpMock.expectOne(`/testderp`);
        expect(req.request.method).toBe('PATCH');
        req.flush({
            success: false,
            data: { answer: 'because' }
        });
    });

    it('should PATCH as a type', () => {
        const fluorite = {
            hardness: 4,
            luster: 'vitreous'
        };
        api.patchAs<JsonApiData<WhatsIt>>('/minerals/fluorite', {'hardness': 4}).subscribe((response) => {
            expect(response).toBeDefined();
            expect(response['mineral']['luster']).toEqual('vitreous');
        });
        const req = httpMock.expectOne(`/minerals/fluorite`);
        expect(req.request.method).toBe('PATCH');
        req.flush({ data: {mineral: fluorite} });
    });

    it('should DELETE', () => {
        api.delete('/marbles', 'all').subscribe((response) => {
            expect(response).toBeDefined();
            expect(response.marbles).toBeDefined();
            expect(response.marbles.length).toBe(0);
        });
        const req = httpMock.expectOne(`/marbles/all`);
        expect(req.request.method).toBe('DELETE');
        req.flush({
            data: { marbles: [] }
        });
    });

    it('should get latest by type', () => {
        api.getLatestByType(StixLabelEnum.IDENTITY).subscribe(ids => {
            expect(ids).toBeDefined();
            expect(ids.length).toEqual(3);
            expect(ids[0].id).toEqual('THX-1138');
        });
        const req = httpMock.expectOne(`/latest/type/${StixLabelEnum.IDENTITY}`);
        expect(req.request.method).toBe('GET');
        req.flush({
            data: [
                {id: 'THX-1138', name: 'Robert Duvall', type: 'drama', modified: '1971'},
                {id: 'R2D2', name: 'Kenny Baker', type: 'sci-fi', modified: '1977'},
                {id: 'V', name: 'Hugo Weaving', type: 'thriller', modified: '2005'},
            ]
        });
    });

    it('should get latest by type for a creator', () => {
        api.getLatestByTypeAndCreatorId(StixLabelEnum.SENSOR, 'RFC').subscribe(ids => {
            expect(ids).toBeDefined();
            expect(ids.length).toEqual(2);
            expect(ids[1].modified).toEqual('1988');
        });
        const req = httpMock.expectOne(`/latest/type/${StixLabelEnum.SENSOR}/creator/RFC`);
        expect(req.request.method).toBe('GET');
        req.flush({
            data: [
                {
                    id: 'SMTP',
                    type: 'mail',
                    name: 'Simple Mail Transfer Protocol',
                    modified: '1982',
                    created_by_ref: 'RFC 821'
                },
                {
                    id: 'POP3',
                    type: 'mail',
                    name: 'Post Office Protocol',
                    modified: '1988',
                    created_by_ref: 'RFC 1081'
                },
            ]
        });
    });

    describe('getStix', () => {

        it('should GET attack patterns, and unwrap JSON api', () => {
            const mockAttackPatterns = [
                {
                    type: 'attack-pattern',
                    id: 'attack-pattern--1234',
                    attributes: {
                        type: 'attack-pattern',
                        id: 'attack-pattern--1234',
                        name: 'bob'
                    }
                },
                {
                    type: 'attack-pattern',
                    id: 'attack-pattern--5678',
                    attributes: {
                        type: 'attack-pattern',
                        id: 'attack-pattern--5678',
                        name: 'jim'
                    }
                },
            ];
            api.getStix<AttackPattern[]>(StixUrls.ATTACK_PATTERN).subscribe((response) => {
                expect(response).toBeDefined();
                expect(response[0].name).toBe('bob');
                expect(response[1].name).toBe('jim');
                expect((response[0] as any).attributes).toBeUndefined();
                expect((response[1] as any).attributes).toBeUndefined();
            });
            const req = httpMock.expectOne(StixUrls.ATTACK_PATTERN);
            expect(req.request.method).toBe('GET');
            req.flush({
                data: mockAttackPatterns
            });
        });

        it('should GET an attack pattern by ID, and unwrap JSON api', () => {
            const mockAttackPattern = {
                type: 'attack-pattern',
                id: 'attack-pattern--1234',
                attributes: {
                    type: 'attack-pattern',
                    id: 'attack-pattern--1234',
                    name: 'bob'
                }
            };
            api.getStix<AttackPattern>(StixUrls.ATTACK_PATTERN, 'attack-pattern--1234').subscribe((response) => {
                expect(response).toBeDefined();
                expect(response.name).toBe('bob');
                expect((response as any).attributes).toBeUndefined();
            });
            const req = httpMock.expectOne(`${StixUrls.ATTACK_PATTERN}/attack-pattern--1234`);
            expect(req.request.method).toBe('GET');
            req.flush({
                data: mockAttackPattern
            });
        });

        it('should place options on parameters', () => {
            const options: StixApiOptions = {
                filter: { 'stix.name': 'bob' },
                skip: 1,
                limit: 3
            };
            api.getStix<AttackPattern>(StixUrls.ATTACK_PATTERN, null, options).subscribe();
            const req = httpMock.expectOne(`${StixUrls.ATTACK_PATTERN}?filter=${encodeURI(JSON.stringify(options.filter))}&skip=1&limit=3&`);
            expect(req.request.method).toBe('GET');
        });

    });

    describe('uploadAttachments', () => {
        const mockFilelist: any = [
            {
                name: 'foo'
            },
            {
                name: 'bar'
            }
        ];

        it('should update progress', (done) => {
            let count = 0;
            const mockGridFS: GridFSFile = {
                _id: '123',
                filename: 'foo.txt',
                contentType: 'application/foo',
                length: 4567,
                chunkSize: 123,
                uploadDate: '2018-07-17T17:48:18.057Z'
            };
            api.uploadAttachments(mockFilelist, () => count++)
                .subscribe(
                    (res) => {
                        expect(count).toBe(3);
                        expect(res).toEqual([mockGridFS]);
                        done();
                    }
                );
            const req = httpMock.expectOne(`${Constance.UPLOAD_URL}/files`);
            expect(req.request.method).toBe('POST');
            req.event({ loaded: 2, total: 10, type: HttpEventType.UploadProgress } as any);
            req.event({ loaded: 5, total: 10, type: HttpEventType.UploadProgress } as any);
            req.event({ loaded: 10, total: 10, type: HttpEventType.UploadProgress } as any);
            req.flush({ data: [{ attributes: mockGridFS }] });
        });

    });

});


text:
angular.module('gale.filters')

.filter('template', function ($log,$interpolate) {
	return function (template, context) {

            var exp = $interpolate(template);
            var content = exp(context);

           return content;
	};
});


text:
package com.distelli.europa.pipeline;

import com.distelli.europa.EuropaConfiguration;
import com.distelli.europa.guice.EuropaInjectorModule;
import com.distelli.europa.models.ContainerRepo;
import com.distelli.europa.models.PipelineComponent;
import com.distelli.objectStore.impl.ObjectStoreModule;
import com.distelli.persistence.impl.PersistenceModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.junit.Before;
import org.junit.Test;

import javax.inject.Inject;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

public class TestRunPipeline {
    private static Injector INJECTOR = createInjector();

    @Inject
    private RunPipeline _runPipeline;

    private static Injector createInjector() {
        String path = System.getenv("EUROPA_CONFIG");
        EuropaConfiguration config = null;
         if (path != null) {
            File file = new File(path);
             if (!file.exists())
                 throw (new IllegalStateException("Invalid value for EUROPA_CONFIG env var: " + path));
            config = EuropaConfiguration.fromFile(file);

        } else {
            config = EuropaConfiguration.fromEnvironment();

        }
         return Guice.createInjector(
            new PersistenceModule(),
            new ObjectStoreModule(),
            new EuropaInjectorModule(
                config));
    }

    @Before
    public void before() throws Exception {
         if (null == INJECTOR) {
             throw new RuntimeException("EUROPA_CONFIG environment variable must point to valid file");

        }
        INJECTOR.injectMembers(this);

    }

    @Test
    public void testRunPipeline_simple() {
        List<PCTestComponent> components = getComponents(true, true, true);
        PipelineComponent.PromotedImage image = new PipelineComponent.PromotedImage(new ContainerRepo(),
                                                                                "dummy",
                                                                                "dummy");
        _runPipeline.runPipeline(components,
                                 image.getRepo(),
                                 image.getTag(),
                                 image.getManifestDigestSha());
        for (int i = 0; i < components.size(); i++) {
            int actualCallCount = components.get(i).getCalls().size();
            int expectedCallCount = 1;
            assertThat(String.format("Component %d was called %d times, expected %d time(s)", i, actualCallCount, expectedCallCount),
                       actualCallCount, equalTo(expectedCallCount));
        }
    }

    @Test
    public void testRunPipeline_failure() {
        List<PCTestComponent> components = getComponents(true, true, false, true);
        List<Integer> callCounts = Arrays.asList(1, 1, 1, 0);
        PipelineComponent.PromotedImage image = new PipelineComponent.PromotedImage(new ContainerRepo(),
                                                                                "dummy",
                                                                                "dummy");
        _runPipeline.runPipeline(components,
                                 image.getRepo(),
                                 image.getTag(),
                                 image.getManifestDigestSha());
        for (int i = 0; i < components.size(); i++) {
            int actualCallCount = components.get(i).getCalls().size();
            int expectedCallCount = callCounts.get(i);
            assertThat(String.format("Component %d was called %d times, expected %d time(s)", i, actualCallCount, expectedCallCount),
                       actualCallCount, equalTo(expectedCallCount));
        }
    }

    @Test
    public void testRunPipeline_changeTag() {
        List<PCTestComponent> components = getComponents(true, true, true);
        components.get(1).setTag("overridden");
        PipelineComponent.PromotedImage image = new PipelineComponent.PromotedImage(new ContainerRepo(),
                                                                                "dummy",
                                                                                "dummy");
        _runPipeline.runPipeline(components,
                                 image.getRepo(),
                                 image.getTag(),
                                 image.getManifestDigestSha());
        for (int i = 0; i < components.size(); i++) {
            int actualCallCount = components.get(i).getCalls().size();
            int expectedCallCount = 1;
            assertThat(String.format("Component %d was called %d times, expected %d time(s)", i, actualCallCount, expectedCallCount),
                       actualCallCount, equalTo(expectedCallCount));
        }
        assertComponentCalledWithTag(components.get(0), 0, "dummy");
        assertComponentCalledWithTag(components.get(1), 1, "dummy");
        assertComponentCalledWithTag(components.get(2), 2, "overridden");
    }

    private void assertComponentCalledWithTag(PCTestComponent component, int componentIndex, String tag) {
        String actualTag = component.getCalls().get(0).getTag();
        String message = String.format("Component %d was called with tag '%s', expected tag '%s'", componentIndex, actualTag, tag);
        assertThat(message, actualTag, equalTo(tag));
    }

    @Data
    @RequiredArgsConstructor
    public static class PCTestComponent extends PipelineComponent {
        private final boolean succeed;
        private String tag;
        private List<PromotedImage> calls = new ArrayList<>();

        /**
         * Run the pipeline stage
         *
         * @param promotedImage the metadata about the previous image
         * @return the input if {@code succeed} is true, or an empty Optional if not
         * @throws Exception
         */
        @Override
        public Optional<PromotedImage> execute(PromotedImage promotedImage) throws Exception {
            calls.add(promotedImage);
            if (succeed) {
                return Optional.of(new PromotedImage(promotedImage.getRepo(),
                                                     (tag == null) ? promotedImage.getTag() : tag,
                                                     promotedImage.getManifestDigestSha()));
            } else {
                return Optional.empty();
            }
        }
    }

    /**
     * Generate a list of dummy components
     *
     * @param values any number of booleans representing whether the component at that position should succeed ({@code true}) or fail ({@code false})
     * @return a list of components which will succeed or fail based on the input
     */
    private List<PCTestComponent> getComponents(boolean... values) {
        List<PCTestComponent> components = new ArrayList<>(values.length);
        for (boolean success : values) {
            components.add(new PCTestComponent(success));
        }
        return components;
    }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { OlmService } from './services/olm.service'

const routes: Routes = [
	{ path: '', redirectTo: 'dashboard', pathMatch: 'full', canActivate: [OlmService] },
	{ path: '**', redirectTo: 'dashboard', pathMatch: 'full', canActivate: [OlmService] },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Mag. , Tokyo 25: 69 (1911)

#### Original name
Lophodermium chamaecyparidis Shirai & Hara

### Remarks
null


text:
/**
 * @class Oskari.mapframework.service.base.Bundle
 *
 */
Oskari.clazz.define("Oskari.mapframework.service.base.Bundle",
/**
 * @constructor
 *
 * Bundle's constructor is called when bundle is created. At
 * this stage bundle sources have been loaded, if bundle is
 * loaded dynamically.
 *
 */
function() {

	/*
	 * Any bundle specific classes may be declared within
	 * constructor to enable stealth mode
	 *
	 * When running within map application framework - Bundle
	 * may refer classes declared with Oskari.clazz.define() -
	 * Bundle may refer classes declared with Ext.define -
	 * Bundle may refer classes declared within OpenLayers
	 * libary
	 *
	 *
	 */
}, {
	/*
	 * @method create
	 *
	 * called when a bundle instance will be created
	 *
	 */
	"create" : function() {

		return null;
	},
	/**
	 * @method update
	 *
	 * Called by Bundle Manager to provide state information to
	 * bundle
	 *
	 */
	"update" : function(manager, bundle, bi, info) {

	}
},

/**
 * metadata
 */
{

	"protocol" : ["Oskari.bundle.Bundle"],
	"source" : {

		"scripts" : [{
			"type" : "text/javascript",
			"src" : "../../../../sources/framework/service/service.js"
		} /*, {
			"type" : "text/javascript",
			"src" : "../../../../sources/framework/service/language-service.js"
		}*/],
		"resources" : []
	},
	"bundle" : {
		"manifest" : {
			"Bundle-Identifier" : "service-base",
			"Bundle-Name" : "mapframework.service.base.Bundle",
			"Bundle-Tag" : {
				"mapframework" : true
			},

			"Bundle-Author" : [{
				"Name" : "jjk",
				"Organisation" : "nls.fi",
				"Temporal" : {
					"Start" : "2009",
					"End" : "2011"
				},
				"Copyleft" : {
					"License" : {
						"License-Name" : "EUPL",
						"License-Online-Resource" : "http://www.paikkatietoikkuna.fi/license"
					}
				}
			}],
			"Bundle-Name-Locale" : {
				"fi" : {
					"Name" : " mapframework.service.Bundle",
					"Title" : " mapframework.service.Bundle"
				},
				"en" : {}
			},
			"Bundle-Version" : "1.0.0",
			"Import-Namespace" : ["Oskari"],
			"Import-Bundle" : {}
		}
	}
});

/**
 * Install this bundle by instantating the Bundle Class
 *
 */
Oskari.bundle_manager.installBundleClass("service-base", "Oskari.mapframework.service.base.Bundle");


text:
import deep_architect.utils as ut
import deep_architect.search_logging as sl

# NOTE: this code is very experimental and it is here only with the purpose of
# that it might be useful and save you the trouble of writing it yourself
# at the time that you are considering your particular use-case. APIs are
# likely to change in future versions.

# can likely be later improved, e.g., the condition for checking that the
# worker as completed the work.
class LocalWorker:
    """Simple local worker that runs a Python process locally with or without a GPU.

    Relaying a job is achieved through a DeepArchitect log folder.
    The master, where the searcher lies, writes a config file and refers
    the worker to it; the worker reads it from disk and writes the results file,
    once  the job is done; having the results written is interpreted as having the
    resources used by the worker free once again.

    .. note::
        This class assumes that the results for the job are written once to
        disk and that determines the job having been completed and the resources
        being again available.

        Currently, this class does not work properly if the worker terminates
        without writing a results file, as it will simply assume that it is
        still working. This can be addressed by making sure that the worker
        code address potential exceptions and never terminates with an error.
    """

    def __init__(self,
                 main_filepath,
                 config_filepath,
                 logs_folderpath,
                 search_name,
                 gpu_id=None):
        self.main_filepath = main_filepath
        self.config_filepath = config_filepath
        self.logs_folderpath = logs_folderpath
        self.search_name = search_name
        self.gpu_id = gpu_id

    def submit_job(self, evaluation_id):
        # NOTE: assumes a specific form for the command that does the evaluation.
        cmd = "export CUDA_VISIBLE_DEVICES=%d && python %s --config_filepath %s --evaluation_id %d &" % (
            self.gpu_id if self.gpu_id is not None else '', self.main_filepath,
            self.config_filepath, evaluation_id)
        ut.run_bash_command(cmd)

    def is_job_done(self, evaluation_id):
        p = sl.get_evaluation_folderpath(self.logs_folderpath, self.search_name,
                                         evaluation_id)
        return ut.file_exists(ut.join_paths([p, 'results.json']))

class LocalWorkerPool:
    """Aggregates many local workers into a pool and manages it.

    A worker only becomes available after the results generated by its job have
    been consumed.
    """

    def __init__(self, worker_lst, query_every_k_seconds):
        self.worker_lst = worker_lst
        self.available_worker_ids = set(range(len(worker_lst)))
        self.running_evaluation_ids = [None] * len(worker_lst)
        self.consumable_evaluation_ids = []
        self.query_every_k_seconds = query_every_k_seconds

        self.timer = ut.TimerManager()
        self.timer.create_timer("pool")
        self.timer.tick_timer("pool")

    def get_num_available_workers(self):
        if (self.timer.get_time_since_last_tick('pool', units="seconds") >=
                self.query_every_k_seconds):
            avail_ids = []
            for worker_id, worker in enumerate(self.worker_lst):
                if worker_id not in self.available_worker_ids:
                    # check completion of the job that the worker was running
                    eval_id = self.running_evaluation_ids[worker_id]
                    if worker.is_job_done(eval_id):
                        self.consumable_evaluation_ids.append(eval_id)
                        self.available_worker_ids.add(worker_id)

        return len(self.available_worker_ids)

    def get_num_consumable_evaluation_ids(self):
        return len(self.consumable_evaluation_ids)

    def consume_evaluation_ids(self):
        ids = self.consumable_evaluation_ids
        self.consumable_evaluation_ids = []
        return ids

    def submit_job(self, evaluation_id):
        assert len(self.available_worker_ids) > 0

        worker_id = self.available_worker_ids.pop()
        worker = self.worker_lst[worker_id]
        worker.submit_job(evaluation_id)
        self.running_evaluation_ids[worker_id] = evaluation_id

# TODO: I need to use a worker to make sure that it works the way I believe
# that it can work, e.g., by using slurm directly. another possibility is
# to login to the server to do what I want.

# script='#!/bin/bash'"
# SBATCH --nodes=1
# SBATCH --partition=GPU-shared
# SBATCH --gres=gpu:k80:$4
# SBATCH --cpus-per-task=$3
# SBATCH --mem=$5MB
# SBATCH --time=$6
# SBATCH --job-name=\"$2\"
# $1" && echo \"$script\" > _run.sh && chmod +x _run.sh && sbatch _run.sh && rm _run.sh;
# }

# # # TODO: this is supposed to be tools that should help running architecture
# # # search experiments at scale.

# import multiprocessing

# # def run_parallel_experiment(experiment_fn, iter_args):
# #     ps = []
# #     for args in iter_args:
# #         p = multiprocessing.Process(target=experiment_fn, args=args)
# #         p.start()
# #         ps.append(p)

# #     for p in ps:
# #         p.join()