text:
package editor.serialization;

import java.awt.Color;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import editor.collection.deck.Category;
import editor.database.attributes.CardAttribute;
import editor.database.card.CardLayout;
import editor.database.version.DatabaseVersion;
import editor.database.version.UpdateFrequency;
import editor.gui.settings.Settings;
import editor.gui.settings.SettingsBuilder;

/**
 * Type adapter for serializing and deserializing the {@link Settings} structure to and from JSON format, since Gson isn't compatible with
 * Java 16 records yet.
 *
 * @author Alec Roelke
 *
 * @see Settings
 */
public class SettingsAdapter implements JsonSerializer<Settings>, JsonDeserializer<Settings>
{
    @Override
    public Settings deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
    {
        SettingsBuilder builder = new SettingsBuilder().defaults();
        JsonObject obj = json.getAsJsonObject();

        if (obj.has("inventory"))
        {
            JsonObject inventory = obj.get("inventory").getAsJsonObject();

            if (inventory.has("source"))
                builder = builder.inventorySource(inventory.get("source").getAsString());
            if (inventory.has("file"))
                builder = builder.inventoryFile(inventory.get("file").getAsString());
            if (inventory.has("versionFile"))
                builder = builder.inventoryVersionFile(inventory.get("versionFile").getAsString());
            if (inventory.has("version"))
                builder = builder.inventoryVersion(context.deserialize(inventory.get("version"), DatabaseVersion.class));
            if (inventory.has("location"))
                builder = builder.inventoryLocation(inventory.get("location").getAsString());
            if (inventory.has("scans"))
                builder = builder.inventoryScans(inventory.get("scans").getAsString());
            if (inventory.has("imageSource"))
                builder = builder.imageSource(inventory.get("imageSource").getAsString());
            if (inventory.has("imageLimitEnable"))
                builder = builder.imageLimitEnable(inventory.get("imageLimitEnable").getAsBoolean());
            if (inventory.has("imageLimit"))
                builder = builder.imageLimit(inventory.get("imageLimit").getAsInt());
            if (inventory.has("tags"))
                builder = builder.inventoryTags(inventory.get("tags").getAsString());
            if (inventory.has("update"))
                builder = builder.inventoryUpdate(context.deserialize(inventory.get("update"), UpdateFrequency.class));
            if (inventory.has("columns"))
            {
                JsonArray inventoryColumnsJson = inventory.get("columns").getAsJsonArray();
                var inventoryColumns = new ArrayList<CardAttribute>(inventoryColumnsJson.size());
                for (var column : inventoryColumnsJson)
                    inventoryColumns.add(context.deserialize(column, CardAttribute.class));
                builder = builder.inventoryColumns(inventoryColumns);
            }
            if (inventory.has("background"))
                builder = builder.inventoryBackground(context.deserialize(inventory.get("background"), Color.class));
            if (inventory.has("stripe"))
                builder = builder.inventoryStripe(context.deserialize(inventory.get("stripe"), Color.class));
            if (inventory.has("warn"))
                builder = builder.inventoryWarn(inventory.get("warn").getAsBoolean());
        }

        if (obj.has("editor"))
        {
            JsonObject editor = obj.get("editor").getAsJsonObject();

            if (editor.has("recents"))
            {
                JsonObject recents = editor.get("recents").getAsJsonObject();

                if (recents.has("count"))
                    builder = builder.recentsCount(recents.get("count").getAsInt());
                if (recents.has("files"))
                {
                    JsonArray recentsJson = recents.get("files").getAsJsonArray();
                    var recentsFiles = new ArrayList<String>(recentsJson.size());
                    for (var file : recentsJson)
                        recentsFiles.add(file.getAsString());
                    builder = builder.recentsFiles(recentsFiles);
                }
            }

            if (editor.has("categories"))
            {
                JsonObject categories = editor.get("categories").getAsJsonObject();

                if (categories.has("presets"))
                {
                    JsonArray presetsJson = categories.get("presets").getAsJsonArray();
                    var presets = new ArrayList<Category>(presetsJson.size());
                    for (var preset : presetsJson)
                        presets.add(context.deserialize(preset, Category.class));
                    builder = builder.presetCategories(presets);
                }
                if (categories.has("rows"))
                    builder = builder.categoryRows(categories.get("rows").getAsInt());
                if (categories.has("explicits"))
                    builder = builder.explicits(categories.get("explicits").getAsInt());
            }

            if (editor.has("hand"))
            {
                JsonObject hand = editor.get("hand").getAsJsonObject();

                if (hand.has("size"))
                    builder = builder.handSize(hand.get("size").getAsInt());
                if (hand.has("rounding"))
                    builder = builder.handRounding(hand.get("rounding").getAsString());
                if (hand.has("background"))
                    builder = builder.handBackground(context.deserialize(hand.get("background"), Color.class));
            }

            if (editor.has("legality"))
            {
                JsonObject legality = editor.get("legality").getAsJsonObject();

                if (legality.has("searchForCommander"))
                    builder = builder.searchForCommander(legality.get("searchForCommander").getAsBoolean());
                if (legality.has("main"))
                    builder = builder.commanderInMain(legality.get("main").getAsBoolean());
                if (legality.has("all"))
                    builder = builder.commanderInAll(legality.get("all").getAsBoolean());
                if (legality.has("list"))
                    builder = builder.commanderInList(legality.get("list").getAsString());
                if (legality.has("sideboard"))
                    builder = builder.sideboardName(legality.get("sideboard").getAsString());
            }

            if (editor.has("columns"))
            {
                JsonArray editorColumnsJson = editor.get("columns").getAsJsonArray();
                var editorColumns = new ArrayList<CardAttribute>(editorColumnsJson.size());
                for (var column : editorColumnsJson)
                    editorColumns.add(context.deserialize(column, CardAttribute.class));
                builder = builder.editorColumns(editorColumns);
            }
            if (editor.has("stripe"))
                builder = builder.editorStripe(context.deserialize(editor.get("stripe"), Color.class));
            if (editor.has("manaValue"))
                builder = builder.manaValue(editor.get("manaValue").getAsString());
            if (editor.has("backFaceLands"))
            {
                JsonArray backFaceLandsJson = editor.get("backFaceLands").getAsJsonArray();
                var backFaceLands = new HashSet<CardLayout>(backFaceLandsJson.size());
                for (var layout : backFaceLandsJson)
                    backFaceLands.add(Arrays.stream(CardLayout.values()).filter((l) -> l.toString().equals(layout.getAsString())).findAny().get());
                builder = builder.backFaceLands(backFaceLands);
            }
            if (editor.has("manaAnalysis"))
            {
                JsonObject manaAnalysis = editor.get("manaAnalysis").getAsJsonObject();
                builder = builder.none(context.deserialize(manaAnalysis.get("none"), Color.class))
                                 .colorless(context.deserialize(manaAnalysis.get("colorless"), Color.class))
                                 .white(context.deserialize(manaAnalysis.get("white"), Color.class))
                                 .blue(context.deserialize(manaAnalysis.get("blue"), Color.class))
                                 .black(context.deserialize(manaAnalysis.get("black"), Color.class))
                                 .red(context.deserialize(manaAnalysis.get("red"), Color.class))
                                 .green(context.deserialize(manaAnalysis.get("green"), Color.class))
                                 .multi(context.deserialize(manaAnalysis.get("multi"), Color.class))
                                 .creature(context.deserialize(manaAnalysis.get("creature"), Color.class))
                                 .artifact(context.deserialize(manaAnalysis.get("artifact"), Color.class))
                                 .enchantment(context.deserialize(manaAnalysis.get("enchantment"), Color.class))
                                 .planeswalker(context.deserialize(manaAnalysis.get("planeswalker"), Color.class))
                                 .instant(context.deserialize(manaAnalysis.get("instant"), Color.class))
                                 .sorcery(context.deserialize(manaAnalysis.get("sorcery"), Color.class))
                                 .line(context.deserialize(manaAnalysis.get("line"), Color.class));

            }
        }

        if (obj.has("cwd"))
            builder = builder.cwd(obj.get("cwd").getAsString());

        return builder.build();
    }

    @Override
    public JsonElement serialize(Settings src, Type typeOfSrc, JsonSerializationContext context)
    {
        JsonObject settings = new JsonObject();

        JsonObject inventory = new JsonObject();
        inventory.addProperty("source", src.inventory().source());
        inventory.addProperty("file", src.inventory().file());
        inventory.addProperty("versionFile", src.inventory().versionFile());
        inventory.add("version", context.serialize(src.inventory().version()));
        inventory.addProperty("location", src.inventory().location());
        inventory.addProperty("scans", src.inventory().scans());
        inventory.addProperty("imageSource", src.inventory().imageSource());
        inventory.addProperty("imageLimitEnable", src.inventory().imageLimitEnable());
        inventory.addProperty("imageLimit", src.inventory().imageLimit());
        inventory.addProperty("tags", src.inventory().tags());
        inventory.add("update", context.serialize(src.inventory().update()));
        JsonArray inventoryColumns = new JsonArray();
        for (CardAttribute column : src.inventory().columns())
            inventoryColumns.add(context.serialize(column));
        inventory.add("columns", inventoryColumns);
        inventory.add("background", context.serialize(src.inventory().background()));
        inventory.add("stripe", context.serialize(src.inventory().stripe()));
        inventory.addProperty("warn", src.inventory().warn());

        JsonObject editor = new JsonObject();
        JsonObject recents = new JsonObject();
        recents.addProperty("count", src.editor().recents().count());
        JsonArray recentFiles = new JsonArray();
        for (String file : src.editor().recents().files())
            recentFiles.add(file);
        recents.add("files", recentFiles);
        editor.add("recents", recents);
        JsonObject categories = new JsonObject();
        JsonArray presetCategories = new JsonArray();
        for (Category category : src.editor().categories().presets())
            presetCategories.add(context.serialize(category));
        categories.add("presets", presetCategories);
        categories.addProperty("rows", src.editor().categories().rows());
        categories.addProperty("explicits", src.editor().categories().explicits());
        editor.add("categories", categories);
        JsonArray editorColumns = new JsonArray();
        for (CardAttribute column : src.editor().columns())
            editorColumns.add(context.serialize(column));
        editor.add("columns", editorColumns);
        editor.add("stripe", context.serialize(src.editor().stripe()));
        JsonObject hand = new JsonObject();
        hand.addProperty("size", src.editor().hand().size());
        hand.addProperty("rounding", src.editor().hand().rounding());
        hand.add("background", context.serialize(src.editor().hand().background()));
        editor.add("hand", hand);
        JsonObject legality = new JsonObject();
        legality.addProperty("searchForCommander", src.editor().legality().searchForCommander());
        legality.addProperty("main", src.editor().legality().main());
        legality.addProperty("all", src.editor().legality().all());
        legality.addProperty("list", src.editor().legality().list());
        legality.addProperty("sideboard", src.editor().legality().sideboard());
        editor.add("legality", legality);
        editor.addProperty("manaValue", src.editor().manaValue());
        JsonArray backFaceLands = new JsonArray();
        for (CardLayout layout : src.editor().backFaceLands())
            backFaceLands.add(layout.toString());
        editor.add("backFaceLands", backFaceLands);
        JsonObject manaAnalysis = new JsonObject();
        manaAnalysis.add("none", context.serialize(src.editor().manaAnalysis().none()));
        manaAnalysis.add("colorless", context.serialize(src.editor().manaAnalysis().colorless()));
        manaAnalysis.add("white", context.serialize(src.editor().manaAnalysis().white()));
        manaAnalysis.add("blue", context.serialize(src.editor().manaAnalysis().blue()));
        manaAnalysis.add("black", context.serialize(src.editor().manaAnalysis().black()));
        manaAnalysis.add("red", context.serialize(src.editor().manaAnalysis().red()));
        manaAnalysis.add("green", context.serialize(src.editor().manaAnalysis().green()));
        manaAnalysis.add("multi", context.serialize(src.editor().manaAnalysis().multi()));
        manaAnalysis.add("creature", context.serialize(src.editor().manaAnalysis().creature()));
        manaAnalysis.add("artifact", context.serialize(src.editor().manaAnalysis().artifact()));
        manaAnalysis.add("enchantment", context.serialize(src.editor().manaAnalysis().enchantment()));
        manaAnalysis.add("planeswalker", context.serialize(src.editor().manaAnalysis().planeswalker()));
        manaAnalysis.add("instant", context.serialize(src.editor().manaAnalysis().instant()));
        manaAnalysis.add("sorcery", context.serialize(src.editor().manaAnalysis().sorcery()));
        manaAnalysis.add("line", context.serialize(src.editor().manaAnalysis().line()));
        editor.add("manaAnalysis", manaAnalysis);

        settings.add("inventory", inventory);
        settings.add("editor", editor);
        settings.addProperty("cwd", src.cwd());

        return settings;
    }
}


text:
package play.api.mvc

import javax.inject.Inject

import play.api.http.HttpConfiguration
import play.api.http.SecretConfiguration
import play.api.http.SessionConfiguration
import play.api.libs.crypto.CookieSigner
import play.api.libs.crypto.CookieSignerProvider
import play.mvc.Http

import scala.annotation.varargs

/**
 * HTTP Session.
 *
 * Session data are encoded into an HTTP cookie, and can only contain simple `String` values.
 */
case class Session(data: Map[String, String] = Map.empty) {

  /**
   * Optionally returns the session value associated with a key.
   */
  def get(key: String): Option[String] = data.get(key)

  /**
   * Retrieves the session value associated with the given key.
   *
   * @throws NoSuchElementException if no value exists for the key.
   */
  def apply(key: String): String = data(key)

  /**
   * Returns `true` if this session is empty.
   */
  def isEmpty: Boolean = data.isEmpty

  /**
   * Returns a new session with the given key-value pair added.
   *
   * For example:
   * {{{
   * session + ("username" -> "bob")
   * }}}
   *
   * @param kv the key-value pair to add
   * @return the modified session
   */
  def +(kv: (String, String)): Session = {
    require(kv._2 != null, s"Session value for ${kv._1} cannot be null")
    copy(data + kv)
  }

  /**
   * Returns a new session with elements added from the given `Iterable`.
   *
   * @param kvs an `Iterable` containing key-value pairs to add.
   */
  def ++(kvs: Iterable[(String, String)]): Session = {
    for ((k, v) <- kvs) require(v != null, s"Session value for $k cannot be null")
    copy(data ++ kvs)
  }

  /**
   * Returns a new session with the given key removed.
   *
   * For example:
   * {{{
   * session - "username"
   * }}}
   *
   * @param key the key to remove
   * @return the modified session
   */
  def -(key: String): Session = copy(data - key)

  /**
   * Returns a new session with the given keys removed.
   *
   * For example:
   * {{{
   * session -- Seq("username", "name")
   * }}}
   *
   * @param keys the keys to remove
   * @return the modified session
   */
  def --(keys: Iterable[String]): Session = copy(data -- keys)

  lazy val asJava: Http.Session = new Http.Session(this)
}

/**
 * Helper utilities to manage the Session cookie.
 */
trait SessionCookieBaker extends CookieBaker[Session] with CookieDataCodec {
  def config: SessionConfiguration

  def COOKIE_NAME: String = config.cookieName

  lazy val emptyCookie = new Session

  override val isSigned               = true
  override def secure: Boolean        = config.secure
  override def maxAge: Option[Int]    = config.maxAge.map(_.toSeconds.toInt)
  override def httpOnly: Boolean      = config.httpOnly
  override def path: String           = config.path
  override def domain: Option[String] = config.domain
  override def sameSite               = config.sameSite

  def deserialize(data: Map[String, String]) = new Session(data)

  def serialize(session: Session): Map[String, String] = session.data
}

/**
 * A session cookie that reads in both signed and JWT cookies, and writes out JWT cookies.
 */
class DefaultSessionCookieBaker @Inject() (
    val config: SessionConfiguration,
    val secretConfiguration: SecretConfiguration,
    cookieSigner: CookieSigner
) extends SessionCookieBaker
    with FallbackCookieDataCodec {
  override val jwtCodec: JWTCookieDataCodec           = DefaultJWTCookieDataCodec(secretConfiguration, config.jwt)
  override val signedCodec: UrlEncodedCookieDataCodec = DefaultUrlEncodedCookieDataCodec(isSigned, cookieSigner)

  def this() = this(SessionConfiguration(), SecretConfiguration(), new CookieSignerProvider(SecretConfiguration()).get)
}

/**
 * A session cookie baker that signs the session cookie in the Play 2.5.x style.
 *
 * @param config session configuration
 * @param cookieSigner the cookie signer, typically HMAC-SHA1
 */
class LegacySessionCookieBaker @Inject() (val config: SessionConfiguration, val cookieSigner: CookieSigner)
    extends SessionCookieBaker
    with UrlEncodedCookieDataCodec {
  def this() = this(SessionConfiguration(), new CookieSignerProvider(SecretConfiguration()).get)
}

object Session {
  lazy val emptyCookie = new Session

  def fromJavaSession(javaSession: play.mvc.Http.Session): Session = javaSession.asScala
}

redpajama_set_name: RedPajamaGithub


text:
import * as Lint from 'tslint';
import * as ts from 'typescript';
export declare class Rule extends Lint.Rules.AbstractRule {
    static metadata: Lint.IRuleMetadata;
    static COMPLEXITY_FAILURE_STRING: string;
    static COMPLEXITY_MAX: number;
    apply(sourceFile: ts.SourceFile): Lint.RuleFailure[];
}


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

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListRecommendedIntentsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The unique identifier of the bot associated with the recommended intent.
     *

     */
    private String botId;
    /**
     *

     * The version of the bot that contains the intent.
     *

     */
    private String botVersion;
    /**
     *

     * The identifier of the language and locale of the intents to list. The string must match one of the supported
     * locales. For more information, see Supported languages.
     *

     */
    private String localeId;
    /**
     *

     * The identifier of the bot recommendation that contains the recommended intent.
     *

     */
    private String botRecommendationId;
    /**
     *

     * Summary information for the intents that meet the filter criteria specified in the request. The length of the
     * list is specified in the maxResults parameter of the request. If there are more intents available, the nextToken
     * field contains a token to get the next page of results.
     *

     */
    private java.util.List<RecommendedIntentSummary> summaryList;
    /**
     *

     * A token that indicates whether there are more results to return in a response to the ListRecommendedIntents
     * operation. If the nextToken field is present, you send the contents as the nextToken parameter of a
     * ListRecommendedIntents operation request to get the next page of results.
     *

     */
    private String nextToken;

    /**
     *

     * The unique identifier of the bot associated with the recommended intent.
     *

     *
     * @param botId
     *        The unique identifier of the bot associated with the recommended intent.
     */

    public void setBotId(String botId) {
        this.botId = botId;
    }

    /**
     *

     * The unique identifier of the bot associated with the recommended intent.
     *

     *
     * @return The unique identifier of the bot associated with the recommended intent.
     */

    public String getBotId() {
        return this.botId;
    }

    /**
     *

     * The unique identifier of the bot associated with the recommended intent.
     *

     *
     * @param botId
     *        The unique identifier of the bot associated with the recommended intent.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withBotId(String botId) {
        setBotId(botId);
        return this;
    }

    /**
     *

     * The version of the bot that contains the intent.
     *

     *
     * @param botVersion
     *        The version of the bot that contains the intent.
     */

    public void setBotVersion(String botVersion) {
        this.botVersion = botVersion;
    }

    /**
     *

     * The version of the bot that contains the intent.
     *

     *
     * @return The version of the bot that contains the intent.
     */

    public String getBotVersion() {
        return this.botVersion;
    }

    /**
     *

     * The version of the bot that contains the intent.
     *

     *
     * @param botVersion
     *        The version of the bot that contains the intent.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withBotVersion(String botVersion) {
        setBotVersion(botVersion);
        return this;
    }

    /**
     *

     * The identifier of the language and locale of the intents to list. The string must match one of the supported
     * locales. For more information, see Supported languages.
     *

     *
     * @param localeId
     *        The identifier of the language and locale of the intents to list. The string must match one of the
     *        supported locales. For more information, see Supported languages.
     */

    public void setLocaleId(String localeId) {
        this.localeId = localeId;
    }

    /**
     *

     * The identifier of the language and locale of the intents to list. The string must match one of the supported
     * locales. For more information, see Supported languages.
     *

     *
     * @return The identifier of the language and locale of the intents to list. The string must match one of the
     *         supported locales. For more information, see Supported languages.
     */

    public String getLocaleId() {
        return this.localeId;
    }

    /**
     *

     * The identifier of the language and locale of the intents to list. The string must match one of the supported
     * locales. For more information, see Supported languages.
     *

     *
     * @param localeId
     *        The identifier of the language and locale of the intents to list. The string must match one of the
     *        supported locales. For more information, see Supported languages.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withLocaleId(String localeId) {
        setLocaleId(localeId);
        return this;
    }

    /**
     *

     * The identifier of the bot recommendation that contains the recommended intent.
     *

     *
     * @param botRecommendationId
     *        The identifier of the bot recommendation that contains the recommended intent.
     */

    public void setBotRecommendationId(String botRecommendationId) {
        this.botRecommendationId = botRecommendationId;
    }

    /**
     *

     * The identifier of the bot recommendation that contains the recommended intent.
     *

     *
     * @return The identifier of the bot recommendation that contains the recommended intent.
     */

    public String getBotRecommendationId() {
        return this.botRecommendationId;
    }

    /**
     *

     * The identifier of the bot recommendation that contains the recommended intent.
     *

     *
     * @param botRecommendationId
     *        The identifier of the bot recommendation that contains the recommended intent.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withBotRecommendationId(String botRecommendationId) {
        setBotRecommendationId(botRecommendationId);
        return this;
    }

    /**
     *

     * Summary information for the intents that meet the filter criteria specified in the request. The length of the
     * list is specified in the maxResults parameter of the request. If there are more intents available, the nextToken
     * field contains a token to get the next page of results.
     *

     *
     * @return Summary information for the intents that meet the filter criteria specified in the request. The length of
     *         the list is specified in the maxResults parameter of the request. If there are more intents available,
     *         the nextToken field contains a token to get the next page of results.
     */

    public java.util.List<RecommendedIntentSummary> getSummaryList() {
        return summaryList;
    }

    /**
     *

     * Summary information for the intents that meet the filter criteria specified in the request. The length of the
     * list is specified in the maxResults parameter of the request. If there are more intents available, the nextToken
     * field contains a token to get the next page of results.
     *

     *
     * @param summaryList
     *        Summary information for the intents that meet the filter criteria specified in the request. The length of
     *        the list is specified in the maxResults parameter of the request. If there are more intents available, the
     *        nextToken field contains a token to get the next page of results.
     */

    public void setSummaryList(java.util.Collection<RecommendedIntentSummary> summaryList) {
        if (summaryList == null) {
            this.summaryList = null;
            return;
        }

        this.summaryList = new java.util.ArrayList<RecommendedIntentSummary>(summaryList);
    }

    /**
     *

     * Summary information for the intents that meet the filter criteria specified in the request. The length of the
     * list is specified in the maxResults parameter of the request. If there are more intents available, the nextToken
     * field contains a token to get the next page of results.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setSummaryList(java.util.Collection)} or {@link #withSummaryList(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param summaryList
     *        Summary information for the intents that meet the filter criteria specified in the request. The length of
     *        the list is specified in the maxResults parameter of the request. If there are more intents available, the
     *        nextToken field contains a token to get the next page of results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withSummaryList(RecommendedIntentSummary... summaryList) {
        if (this.summaryList == null) {
            setSummaryList(new java.util.ArrayList<RecommendedIntentSummary>(summaryList.length));
        }
        for (RecommendedIntentSummary ele : summaryList) {
            this.summaryList.add(ele);
        }
        return this;
    }

    /**
     *

     * Summary information for the intents that meet the filter criteria specified in the request. The length of the
     * list is specified in the maxResults parameter of the request. If there are more intents available, the nextToken
     * field contains a token to get the next page of results.
     *

     *
     * @param summaryList
     *        Summary information for the intents that meet the filter criteria specified in the request. The length of
     *        the list is specified in the maxResults parameter of the request. If there are more intents available, the
     *        nextToken field contains a token to get the next page of results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withSummaryList(java.util.Collection<RecommendedIntentSummary> summaryList) {
        setSummaryList(summaryList);
        return this;
    }

    /**
     *

     * A token that indicates whether there are more results to return in a response to the ListRecommendedIntents
     * operation. If the nextToken field is present, you send the contents as the nextToken parameter of a
     * ListRecommendedIntents operation request to get the next page of results.
     *

     *
     * @param nextToken
     *        A token that indicates whether there are more results to return in a response to the
     *        ListRecommendedIntents operation. If the nextToken field is present, you send the contents as the
     *        nextToken parameter of a ListRecommendedIntents operation request to get the next page of results.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * A token that indicates whether there are more results to return in a response to the ListRecommendedIntents
     * operation. If the nextToken field is present, you send the contents as the nextToken parameter of a
     * ListRecommendedIntents operation request to get the next page of results.
     *

     *
     * @return A token that indicates whether there are more results to return in a response to the
     *         ListRecommendedIntents operation. If the nextToken field is present, you send the contents as the
     *         nextToken parameter of a ListRecommendedIntents operation request to get the next page of results.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * A token that indicates whether there are more results to return in a response to the ListRecommendedIntents
     * operation. If the nextToken field is present, you send the contents as the nextToken parameter of a
     * ListRecommendedIntents operation request to get the next page of results.
     *

     *
     * @param nextToken
     *        A token that indicates whether there are more results to return in a response to the
     *        ListRecommendedIntents operation. If the nextToken field is present, you send the contents as the
     *        nextToken parameter of a ListRecommendedIntents operation request to get the next page of results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListRecommendedIntentsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getBotId() != null)
            sb.append("BotId: ").append(getBotId()).append(",");
        if (getBotVersion() != null)
            sb.append("BotVersion: ").append(getBotVersion()).append(",");
        if (getLocaleId() != null)
            sb.append("LocaleId: ").append(getLocaleId()).append(",");
        if (getBotRecommendationId() != null)
            sb.append("BotRecommendationId: ").append(getBotRecommendationId()).append(",");
        if (getSummaryList() != null)
            sb.append("SummaryList: ").append(getSummaryList()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ListRecommendedIntentsResult == false)
            return false;
        ListRecommendedIntentsResult other = (ListRecommendedIntentsResult) obj;
        if (other.getBotId() == null ^ this.getBotId() == null)
            return false;
        if (other.getBotId() != null && other.getBotId().equals(this.getBotId()) == false)
            return false;
        if (other.getBotVersion() == null ^ this.getBotVersion() == null)
            return false;
        if (other.getBotVersion() != null && other.getBotVersion().equals(this.getBotVersion()) == false)
            return false;
        if (other.getLocaleId() == null ^ this.getLocaleId() == null)
            return false;
        if (other.getLocaleId() != null && other.getLocaleId().equals(this.getLocaleId()) == false)
            return false;
        if (other.getBotRecommendationId() == null ^ this.getBotRecommendationId() == null)
            return false;
        if (other.getBotRecommendationId() != null && other.getBotRecommendationId().equals(this.getBotRecommendationId()) == false)
            return false;
        if (other.getSummaryList() == null ^ this.getSummaryList() == null)
            return false;
        if (other.getSummaryList() != null && other.getSummaryList().equals(this.getSummaryList()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getBotId() == null) ? 0 : getBotId().hashCode());
        hashCode = prime * hashCode + ((getBotVersion() == null) ? 0 : getBotVersion().hashCode());
        hashCode = prime * hashCode + ((getLocaleId() == null) ? 0 : getLocaleId().hashCode());
        hashCode = prime * hashCode + ((getBotRecommendationId() == null) ? 0 : getBotRecommendationId().hashCode());
        hashCode = prime * hashCode + ((getSummaryList() == null) ? 0 : getSummaryList().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

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

}


text:
package com.oneops.ops.dao;

import static me.prettyprint.hector.api.factory.HFactory.createKeyspace;
import static me.prettyprint.hector.api.factory.HFactory.createMutator;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.*;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.oneops.cassandra.ClusterBootstrap;
import com.oneops.ops.PerfDataRequest;
import com.oneops.ops.PerfHeader;
import com.oneops.sensor.events.PerfEvent;
import com.oneops.sensor.events.PerfEventPayload;

import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.serializers.BytesArraySerializer;
import me.prettyprint.cassandra.serializers.DoubleSerializer;
import me.prettyprint.cassandra.serializers.LongSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.ThriftCfDef;
import me.prettyprint.cassandra.service.ThriftKsDef;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.*;
import me.prettyprint.hector.api.ddl.ColumnType;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.exceptions.HInvalidRequestException;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.*;

/**
 * PerfDataAccessor - encapsulates cassandra data access for performance.
 * <p>
 * data clients - write: PerfSink uses process() and constructor or  property setters for cassandra connection.
 *                 read: web.PerfController uses getPerfData() getLogData() ;
 */
@Component
public class PerfDataAccessor implements CassandraConstants {

    private String clusterName;
    private String keyspaceName;
    private String hostName;
    private boolean isTestMode = false;

    private static final StringSerializer stringSerializer = StringSerializer.get();
    private static final BytesArraySerializer bytesSerializer = BytesArraySerializer.get();
    private static final LongSerializer longSerializer = LongSerializer.get();
    private static final DoubleSerializer doubleSerializer = DoubleSerializer.get();

    protected Cluster cluster;
    protected Keyspace keyspace;

    private static final String DATA_CF = "data";
    private static final String HEADER_SCF = "header";
    protected static final String CI_METRIC_CF = "ci_metric";
    private static final String CHART_SCF = "chart";
    private static final String[] buckets = {"1m", "5m", "15m", "1h", "6h", "1d"};

    private static Logger logger = Logger.getLogger(PerfDataAccessor.class);
    private static PerfHeaderDao phd = null;
    private ClusterBootstrap cb;

    public static int MAX_EXCEPTION_COUNT = 10;
    // Default time seconds for hector to connect to cassandra.
    private static final int TIMEOUT_IN_SECONDS = Integer.valueOf(System.getProperty("dao.timeToWaitForCassandra", "7"));

    /**
     * Sets the cluster name.
     *
     * @param name the new cluster name
     */
    public void setClusterName(String name) {
        clusterName = name;
    }

    /**
     * Sets the keyspace name.
     *
     * @param name the new keyspace name
     */
    public void setKeyspaceName(String name) {
        keyspaceName = name;
    }

    /**
     * Sets the cluster bootstrap
     *
     * @param cb ClusterBootstrap
     */
    public void setClusterBootstrap(ClusterBootstrap cb) {
        this.cb = cb;
    }

    private String connectToCluster() {
        logger.info("Initializing PerfDataAccessor cluster...");
        // No of connections and timeouts are configured as part of system property
        cluster = cb.getCluster(clusterName);
        logger.info("Connected to cluster : " + clusterName);
        return "Ready!";
    }

    /**
     * Inits the DAOs/connections
     */
    public void init() {
        logger.info("PerfDataAccessor: " + ":" + clusterName + ":" + keyspaceName);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(this::connectToCluster);

        try {
            logger.info("Started connecting.. with timeOut " + TIMEOUT_IN_SECONDS);
            logger.info(future.get(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS));
            logger.info("Finished connecting!");

        } catch (TimeoutException e) {
            logger.error("no cassandra hosts available - shutting down");
            throw new HectorException("TimeOut occured in getting the cassandra connection");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executor.shutdownNow();
        initCluster();
    }

    public void initSync() {
        logger.info("PerfDataAccessor - initSync: " + ":" + clusterName + ":" + keyspaceName);
        connectToCluster();
        initCluster();
    }

    private void initCluster() {
        if (cluster.getConnectionManager().getActivePools().isEmpty()) {
            logger.error("no cassandra hosts available - shutting down");
            throw new HectorException("no cassandra hosts available ");
        } else {
            logger.info("hosts: " + cluster.getConnectionManager().getHosts().toString());
            logger.info("downed hosts: " + cluster.getConnectionManager().getDownedHosts().toString());
        }

        try {
            cluster.addKeyspace(new ThriftKsDef(keyspaceName, "org.apache.cassandra.locator.SimpleStrategy", 1, null));
            logger.info("adding keyspace: " + keyspaceName);
        } catch (HInvalidRequestException e) {
            logger.info(" adding " + keyspaceName + " keyspace: " + e.getMessage());
        }

        ConfigurableConsistencyLevel cl = new ConfigurableConsistencyLevel();
        cl.setDefaultWriteConsistencyLevel(HConsistencyLevel.ONE);
        cl.setDefaultReadConsistencyLevel(HConsistencyLevel.ONE);
        keyspace = createKeyspace(keyspaceName, cluster, cl);

        BasicColumnFamilyDefinition cfo = new BasicColumnFamilyDefinition();

        // Add sharded data cf
        for (String bucket : buckets) {
            cfo = new BasicColumnFamilyDefinition();
            cfo.setColumnType(ColumnType.STANDARD);
            String bucketCf = DATA_CF + "_" + bucket;
            if (isTestMode) bucketCf += "_test";

            cfo.setName(bucketCf);
            cfo.setComparatorType(ComparatorType.BYTESTYPE);
            cfo.setKeyspaceName(keyspaceName);

            try {
                cluster.addColumnFamily(new ThriftCfDef((cfo)));
                logger.info("adding cf: " + bucketCf);
            } catch (HInvalidRequestException e) {
                logger.info("adding " + bucketCf + " " + e.getMessage());
            }
        }

        // header
        cfo = new BasicColumnFamilyDefinition();
        cfo.setColumnType(ColumnType.SUPER);
        String headerCfName = HEADER_SCF;
        if (isTestMode) headerCfName += "_test";
        cfo.setName(headerCfName);
        cfo.setComparatorType(ComparatorType.BYTESTYPE);
        cfo.setSubComparatorType(ComparatorType.BYTESTYPE);
        cfo.setKeyspaceName(keyspaceName);

        try {
            cluster.addColumnFamily(new ThriftCfDef((cfo)));
            logger.info("adding cf: " + headerCfName);
        } catch (HInvalidRequestException e) {
            logger.info("adding " + headerCfName + " " + e.getMessage());
        }

        // chart
        cfo = new BasicColumnFamilyDefinition();
        cfo.setColumnType(ColumnType.SUPER);
        cfo.setName(CHART_SCF);
        cfo.setComparatorType(ComparatorType.ASCIITYPE);
        cfo.setSubComparatorType(ComparatorType.ASCIITYPE);
        cfo.setKeyspaceName(keyspaceName);

        try {
            cluster.addColumnFamily(new ThriftCfDef((cfo)));
            logger.info("adding cf: " + CHART_SCF);
        } catch (HInvalidRequestException e) {
            logger.info("adding " + CHART_SCF + " " + e.getMessage());
        }

        phd = new PerfHeaderDao();
        phd.setClusterBootstrap(cb);
        phd.setClusterName(clusterName);
        phd.setKeyspaceName(keyspaceName);
        phd.init();

        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            try {
                hostName = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e1) {
                logger.error("could not get hostname or ip...fail");
                //Wrapping it with Hector exception as it causes Cassandra Connection Failures
                throw new HectorException("could not get hostname or ip...fail");
            }
        }
    }

    private String getRraByStat(String stat, int reqStep) {
        return stat + "-" + getShard(reqStep);
    }

    private String getShard(int reqStep) {
        String rra = null;
        if (reqStep < 300)
            rra = "1m";
        else if (reqStep < 900)
            rra = "5m";
        else if (reqStep < 3600)
            rra = "15m";
        else if (reqStep < 21600)
            rra = "1h";
        else if (reqStep < 86000)
            rra = "6h";
        else
            rra = "1d";
        return rra;
    }

    private int alignRraStep(int reqStep) {
        int step = 60;
        // 1 day
        if (reqStep > 86000) {
            step = 86400;
            // 6hr
        } else if (reqStep > 21599) {
            step = 21600;
            // 1hr
        } else if (reqStep > 3599) {
            step = 3600;
            // 15min
        } else if (reqStep > 899) {
            step = 900;
            // 5min
        } else if (reqStep > 299) {
            step = 300;
        }
        return step;
    }

    /**
     * Gets the perf data series. Contains tmp code for conversion of data cf to sharded data cfs
     *
     * @param req the request object
     * @return the perf data series
     */
    public String getPerfDataSeries(PerfDataRequest req) {

        Long start = Long.valueOf(req.getStart());
        Long end = Long.valueOf(req.getEnd());
        int maxColumns = (int) (end - start);
        StringBuilder jsonOut = new StringBuilder("");

        try {
            long startTime = System.currentTimeMillis();
            String stat = "rra-average";
            if (req.getStat_function() != null) {
                stat = "rra-" + req.getStat_function();
            }

            String rra = getRraByStat(stat, req.getStep());
            int step = alignRraStep(req.getStep());
            List<byte[]> keys = new ArrayList<byte[]>();
            StringBuilder sb = new StringBuilder("");
            long adjustedStart = start - start % step;
            String dataCF = DATA_CF + "_" + getShard(step);
            if (isTestMode) dataCF += "_test";

            MultigetSliceQuery<byte[], Long, Double> multigetSliceQuery = HFactory.createMultigetSliceQuery(keyspace, bytesSerializer, longSerializer, doubleSerializer);
            multigetSliceQuery.setColumnFamily(dataCF);
            keys = new ArrayList<>();
            sb = new StringBuilder("");
            for (int i = 0; i < req.getMetrics().length; i++) {
                String metricDs = req.getMetrics()[i];
                String key = Long.valueOf(req.getCi_id()).toString() + ":" + metricDs + ":" + rra;
                keys.add(key.getBytes());
                sb.append(" " + key);
            }
            multigetSliceQuery.setKeys(keys);
            multigetSliceQuery.setRange(adjustedStart, end, false, maxColumns);

            logger.info("start:" + start + " end:" + end + " for: " + sb);
            long cassStart = System.currentTimeMillis();

            QueryResult<Rows<byte[], Long, Double>> result = multigetSliceQuery.execute();
            Rows<byte[], Long, Double> rows = result.get();

            long cassEnd = System.currentTimeMillis();
            long cassDuration = cassEnd - cassStart;

            // put the by-metric results into 1 csv-like table
            // (time,metric1,metric2,etc)
            // ... should find faster way to do this, but still 10x faster than
            // gwt DataTable serialization
            int rowCount = 0;
            int totalSampleCount = 0;
            HashMap<String, HashMap<Long, Double>> resultMap = new HashMap<String, HashMap<Long, Double>>();

            for (Row<byte[], Long, Double> row : rows) {

                String rowKey = new String(row.getKey());
                HashMap<Long, Double> results = null;
                if (resultMap.containsKey(rowKey)) {
                    results = resultMap.get(rowKey);
                } else {
                    results = new HashMap<>();
                    resultMap.put(rowKey, results);
                }

                List<HColumn<Long, Double>> cols = row.getColumnSlice().getColumns();
                Iterator<HColumn<Long, Double>> listIter = cols.listIterator();

                while (listIter.hasNext()) {
                    HColumn<Long, Double> c = (HColumn<Long, Double>) listIter.next();
                    results.put(c.getName(), c.getValue());
                }
            }

            for (String rowKey : resultMap.keySet()) {

                HashMap<Long, Double> results = resultMap.get(rowKey);

                if (rowCount > 0) {
                    jsonOut.append(",\n");
                }

                String[] keyParts = rowKey.split(":");
                String ciId = keyParts[0];
                String metric = keyParts[1] + ":" + keyParts[2];

                jsonOut.append("{ \"header\":{\"ci_id\":" + ciId
                        + ", \"metric\":\"" + metric + "\", \"step\":" + step
                        + ", \"start\":" + adjustedStart + "},\n ");
                jsonOut.append("\"data\":[");

                long currentBucket = adjustedStart;
                int sampleCount = 0;
                int emptyCount = 0;

                SortedSet<Long> sortedKeys = new TreeSet<>(results.keySet());

                for (long sampleBucket : sortedKeys) {
                    double value = results.get(sampleBucket);
                    if (sampleBucket != currentBucket) {
                        while (sampleBucket > currentBucket) {
                            if (sampleCount > 0) {
                                jsonOut.append(",");
                            }
                            jsonOut.append("null");
                            currentBucket += step;
                            emptyCount++;
                            sampleCount++;
                        }
                    }

                    if (sampleCount > 0) {
                        jsonOut.append(",");
                    }
                    jsonOut.append((Math.round(value * 1000.0) / 1000.0));

                    currentBucket += step;
                    totalSampleCount++;
                    sampleCount++;
                }

                jsonOut.append("]}");
                rowCount++;
                logger.debug("got samples:" + sampleCount + " gaps:"
                        + emptyCount);
            }
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            logger.debug("getPerfData took: " + duration + " ms (cass query: "
                    + cassDuration + " ms) returning: " + totalSampleCount
                    + " rows of " + rowCount + " metrics");

        } catch (HectorException he) {
            he.printStackTrace();
        }
        return jsonOut.toString();
    }

    public void reportMetricCounts() {
        int rowCount = 0;
        int totalColCount = 0;
        int pageSize = 1000;

        RangeSlicesQuery<String, Long, Double> query = HFactory
                .createRangeSlicesQuery(keyspace, stringSerializer, longSerializer, doubleSerializer)
                .setColumnFamily(DATA_CF).setReturnKeysOnly()
                .setRowCount(pageSize);

        String lastKey = null;

        while (true) {
            query.setKeys(lastKey, null);

            QueryResult<OrderedRows<String, Long, Double>> result = query.execute();
            OrderedRows<String, Long, Double> orderedRows = result.get();
            Iterator<Row<String, Long, Double>> rowsIterator = orderedRows.iterator();

            // we'll skip this first one, since it is the same as the last one
            // from previous time we executed
            if (lastKey != null && rowsIterator != null)
                rowsIterator.next();

            // each row / rra
            while (rowsIterator.hasNext()) {
                Row<String, Long, Double> row = rowsIterator.next();
                // count values
                CountQuery<byte[], Long> cq = HFactory
                        .createCountQuery(keyspace, bytesSerializer, longSerializer).setColumnFamily(DATA_CF)
                        .setKey(row.getKey().getBytes())
                        .setRange(1L, null, Integer.MAX_VALUE);

                QueryResult<Integer> r = cq.execute();
                logger.info(row.getKey() + ": " + r.get());

                rowCount++;
                totalColCount += r.get();
                lastKey = row.getKey();
            }
            logger.info("rows: " + rowCount + " cols: " + totalColCount);

            if (orderedRows.getCount() < pageSize)
                break;

        }

    }

    public void purgeMetrics(long time) {
        purgeMetrics(time, "1m");
    }

    public void purgeMetrics(long time, String bucket) {

        int rowCount = 0;
        int totalColCount = 0;
        int totalColDeleted = 0;

        Long start = 1L;
        Long end = time;

        // safeguard not to delete anything in past week
        long now = System.currentTimeMillis() / 1000;
        logger.info("       now: " + now);
        logger.info("startEpoch: " + time);

        if (time + (60 * 60 * 24 * 7) > now) {
            logger.error("input time too soon - cannot be within past week");
            return;
        }

        int maxColumns = (int) (end - start);
        int pageSize = 1000;
        String lastKey = null;

        Mutator<byte[]> mutator = HFactory.createMutator(keyspace, bytesSerializer);

        RangeSlicesQuery<String, Long, Double> query = HFactory
                .createRangeSlicesQuery(keyspace, stringSerializer, longSerializer, doubleSerializer)
                .setColumnFamily(DATA_CF).setReturnKeysOnly()
                .setRowCount(pageSize);

        while (true) {
            query.setKeys(lastKey, null);

            QueryResult<OrderedRows<String, Long, Double>> result = query.execute();
            OrderedRows<String, Long, Double> orderedRows = result.get();
            Iterator<Row<String, Long, Double>> rowsIterator = orderedRows.iterator();

            // we'll skip this first one, since it is the same as the last one
            // from previous time we executed
            if (lastKey != null && rowsIterator != null)
                rowsIterator.next();

            while (rowsIterator.hasNext()) {
                Row<String, Long, Double> row = rowsIterator.next();

                if (!row.getKey().endsWith("-" + bucket)) {
                    continue;
                }

                rowCount++;
                lastKey = row.getKey();

                List<byte[]> keys = new ArrayList<byte[]>();
                keys.add(row.getKey().getBytes());

                MultigetSliceQuery<byte[], Long, Double> multigetSliceQuery = HFactory
                        .createMultigetSliceQuery(keyspace, bytesSerializer, longSerializer, doubleSerializer)
                        .setColumnFamily(DATA_CF).setKeys(keys)
                        .setRange(start, end, false, maxColumns);

                QueryResult<Rows<byte[], Long, Double>> colResult = multigetSliceQuery.execute();
                Rows<byte[], Long, Double> rows = colResult.get();

                int sampleCount = 0;
                int deletedCount = 0;
                for (Row<byte[], Long, Double> rowResult : rows) {

                    List<HColumn<Long, Double>> cols = rowResult.getColumnSlice().getColumns();
                    Iterator<HColumn<Long, Double>> listIter = cols.listIterator();

                    while (listIter.hasNext()) {
                        HColumn<Long, Double> c = (HColumn<Long, Double>) listIter.next();

                        if (c.getName() < time) {
                            mutator.addDeletion(row.getKey().getBytes(), DATA_CF, c.getName(), longSerializer);
                            deletedCount++;
                        }
                        sampleCount++;
                    }

                    totalColDeleted += deletedCount;
                    totalColCount += sampleCount;

                    mutator.execute();
                }

                logger.info(row.getKey() + ": " + sampleCount + " deleted: " + deletedCount);
                if (rows.getCount() < pageSize)
                    break;

            }
            logger.info("rows: " + rowCount + " cols: " + totalColCount
                    + " deleted: " + totalColDeleted);

            if (orderedRows.getCount() < pageSize)
                break;

        }

    }

    public List<HSuperColumn<String, String, String>> getChart(String key) {
        SuperSliceQuery<String, String, String, String> q = HFactory
                .createSuperSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer, stringSerializer);
        q.setColumnFamily(CHART).setKey(key).setRange(null, null, false, 100);

        // execute query and get result list
        QueryResult<SuperSlice<String, String, String>> result = q.execute();
        return result.get().getSuperColumns();
    }

    public void insert(Mutator<String> mutator, String key,
                       Map<String, String> columnsMap, String columnFamily,
                       String superColumn) {
        List<HColumn<String, String>> columns = new ArrayList<HColumn<String, String>>();
        for (String name : columnsMap.keySet()) {
            HFactory.createStringColumn(name, columnsMap.get(name));
        }
        mutator.insert(key, columnFamily, HFactory.createSuperColumn(superColumn, columns, stringSerializer, stringSerializer, stringSerializer));
    }

    public Mutator<String> newMutator() {
        return createMutator(keyspace, stringSerializer);
    }

    public void execute(Mutator<String> mutator) {
        mutator.execute();
    }

    public void writeSampleToHeaderAndBuckets(String key, long endTime, PerfHeader header, Map<String, Double> data, HashMap<String, PerfEvent> perfEventMap) throws IOException {

        StringBuilder pendingKeys = new StringBuilder("");
        Mutator<byte[]> mutator = createMutator(keyspace, bytesSerializer);

        phd.putHeader(key, header, mutator);
        // write the buckets / archives
        for (String dsRraTime : data.keySet()) {
            // only supporting avg due to volume
            if (!dsRraTime.contains("rra-average"))
                continue;

            String[] dsRraTimeParts = dsRraTime.split("::");
            String dsRra = dsRraTimeParts[0];
            String bucketKey = key + ":" + dsRra;
            long bucketEndTime = Long.parseLong(dsRraTimeParts[1]);

            Double cdpValue = Math.round(data.get(dsRraTime).doubleValue() * 1000.0) / 1000.0;
            if (dsRra.endsWith(LOGBUCKET)) {
                logger.info("write " + bucketKey + " : " + cdpValue);
            }
            String shard = dsRra.substring(dsRra.length() - 3).replace("-", "");
            int ttl = getTTL(shard);
            HColumn<Long, Double> column = createDataColumn(bucketEndTime, cdpValue.doubleValue());
            column.setTtl(ttl);

            String dataCF = DATA_CF + "_" + shard;
            if (isTestMode)
                dataCF += "_test";

            mutator.addInsertion(bucketKey.getBytes(), dataCF, column);
            pendingKeys.append(" ," + bucketKey);

            // send the consolidated perf event to sensor
            PerfEvent pe = null;
            String[] rraParts = dsRra.split("-");
            String eventBucket = rraParts[rraParts.length - 1];
            if (perfEventMap.containsKey(eventBucket)) {
                pe = perfEventMap.get(eventBucket);
            } else {
                pe = setEventBucket(perfEventMap, eventBucket);
            }

            String ds = rraParts[0].replace(":rra", "");
            String rraType = rraParts[1];

            if (rraType.equalsIgnoreCase(AVERAGE)) {
                pe.getMetrics().addAvg(ds, cdpValue);
            } else if (rraType.equalsIgnoreCase(COUNT)) {
                pe.getMetrics().addCount(ds, cdpValue);
            } else if (rraType.equalsIgnoreCase(MAX)) {
                pe.getMetrics().addMax(ds, cdpValue);
            } else if (rraType.equalsIgnoreCase(MIN)) {
                pe.getMetrics().addMin(ds, cdpValue);
            } else if (rraType.equalsIgnoreCase(SUM)) {
                pe.getMetrics().addSum(ds, cdpValue);
            }

        }

        logger.debug("write keys:" + pendingKeys);

        // perform the insert/updates
        mutator.execute();
    }

    private String translateBucket(String bucket) {
        String parts[] = bucket.split("-");
        if (parts[1].equals("avg"))
            return "rra-average-" + parts[0];
        else if (parts[1].equals("min"))
            return "rra-min-" + parts[0];
        else if (parts[1].equals("max"))
            return "rra-max-" + parts[0];

        return "";
    }

    public void writeBucket(PerfEvent perfEvent) throws IOException {
        Mutator<byte[]> mutator = createMutator(keyspace, bytesSerializer);

        String columnKey = perfEvent.getCiId() + ":" + perfEvent.getGrouping();
        String aggregate = translateBucket(perfEvent.getBucket());
        String shard = aggregate.substring(aggregate.length() - 3).replace("-", "");
        int ttl = getTTL(shard);
        String dataCF = DATA_CF + "_" + shard;
        if (isTestMode)
            dataCF += "_test";

        if (perfEvent.getMetrics().getAvg() != null) {
            for (String key : perfEvent.getMetrics().getAvg().keySet()) {
                Double value = perfEvent.getMetrics().getAvg().get(key);
                String bucketKey = columnKey + ":" + key + ":" + aggregate;
                long bucketEndTime = perfEvent.getTimestamp();

                logger.debug("write " + dataCF + ' ' + bucketKey + " " + bucketEndTime + ":" + value);
                HColumn<Long, Double> column = createDataColumn(bucketEndTime, value.doubleValue());
                column.setTtl(ttl);
                mutator.addInsertion(bucketKey.getBytes(), dataCF, column);
            }
        }

        if (perfEvent.getMetrics().getMin() != null) {
            for (String key : perfEvent.getMetrics().getMin().keySet()) {
                Double value = perfEvent.getMetrics().getMin().get(key);
                String bucketKey = columnKey + ":" + key + ":" + aggregate;
                long bucketEndTime = perfEvent.getTimestamp();

                logger.debug("write " + dataCF + ' ' + bucketKey + " " + bucketEndTime + ":" + value);
                HColumn<Long, Double> column = createDataColumn(bucketEndTime, value.doubleValue());
                column.setTtl(ttl);
                mutator.addInsertion(bucketKey.getBytes(), dataCF, column);
            }
        }

        if (perfEvent.getMetrics().getMax() != null) {
            for (String key : perfEvent.getMetrics().getMax().keySet()) {
                Double value = perfEvent.getMetrics().getMax().get(key);
                String bucketKey = columnKey + ":" + key + ":" + aggregate;
                long bucketEndTime = perfEvent.getTimestamp();

                logger.debug("write " + dataCF + ' ' + bucketKey + " " + bucketEndTime + ":" + value);
                HColumn<Long, Double> column = createDataColumn(bucketEndTime, value.doubleValue());
                column.setTtl(ttl);
                mutator.addInsertion(bucketKey.getBytes(), dataCF, column);
            }
        }

        // perform the insert/updates
        mutator.execute();
    }

    private int getTTL(String dsRra) {
        // 1m - 2d
        // 5m - 10d
        // 15m- 30d
        // 1h - 120d
        // 6h - 720d
        // 1d - 2880d
        int ttl = 86400 * 2;
        if (dsRra.equals("1m")) {
            return ttl;
        } else if (dsRra.equals("5m")) {
            ttl = 86400 * 10;
        } else if (dsRra.equals("15m")) {
            ttl = 86400 * 30;
        } else if (dsRra.equals("1h")) {
            ttl = 86400 * 120;
        } else if (dsRra.equals("6h")) {
            ttl = 86400 * 720;
        } else {
            ttl = 86400 * 2880;
        }
        return ttl;
    }

    private PerfEvent setEventBucket(HashMap<String, PerfEvent> perfEventMap,
                                     String bucketName) {
        PerfEvent pe = new PerfEvent();
        PerfEvent base = perfEventMap.get("1m");
        pe.setBucket(bucketName);

        pe.setCiId(base.getCiId());
        pe.setGrouping(base.getGrouping());
        pe.setManifestId(base.getManifestId());
        pe.setSource(base.getSource());
        pe.setTimestamp(base.getTimestamp());

        PerfEventPayload load = new PerfEventPayload();
        load.setAvg(new HashMap<>());
        load.setMax(new HashMap<>());
        load.setMin(new HashMap<>());
        load.setSum(new HashMap<>());
        load.setCount(new HashMap<>());
        pe.setMetrics(load);
        perfEventMap.put(bucketName, pe);
        return pe;
    }

    /**
     * sets the long timestamp, double value of a given metric-instance:rra
     */
    private HColumn<Long, Double> createDataColumn(long name, double value) {
        return HFactory.createColumn(name, value, longSerializer,
                doubleSerializer);
    }

    /**
     * Gets the perf data table.
     *
     * @param req the req
     * @return the perf data table
     */
    @SuppressWarnings("unchecked")
    public String getPerfDataTable(PerfDataRequest req) {

        Long start = Long.valueOf(req.getStart());
        Long end = Long.valueOf(req.getEnd());
        int maxColumns = (int) (end - start);
        String jsonOut = "";

        try {
            long startTime = System.currentTimeMillis();
            String stat = "rra-average";
            if (req.getStat_function() != null) {
                stat = "rra-" + req.getStat_function();
            }

            String rra = getRraByStat(stat, req.getStep());
            int step = alignRraStep(req.getStep());

            MultigetSliceQuery<byte[], Long, Double> multigetSliceQuery = HFactory
                    .createMultigetSliceQuery(keyspace, bytesSerializer, longSerializer, doubleSerializer);
            multigetSliceQuery.setColumnFamily(DATA_CF);
            List<byte[]> keys = new ArrayList<>();
            StringBuilder keyString = new StringBuilder("");
            for (int i = 0; i < req.getMetrics().length; i++) {
                String metricDs = req.getMetrics()[i];
                String key = Long.valueOf(req.getCi_id()).toString() + ":" + metricDs + ":" + rra;
                keys.add(key.getBytes());
                keyString.append(" ").append(key);
            }
            multigetSliceQuery.setKeys(keys);
            long adjustedStart = bucketize(start, step);
            multigetSliceQuery.setRange(adjustedStart, end, false, maxColumns);

            multigetSliceQuery.setRange(start, end, false, maxColumns);

            logger.debug("start:" + start + " end:" + end + " for: "
                    + keyString);
            long cassStart = System.currentTimeMillis();

            QueryResult<Rows<byte[], Long, Double>> result = multigetSliceQuery.execute();
            Rows<byte[], Long, Double> rows = result.get();

            long cassEnd = System.currentTimeMillis();
            long cassDuration = cassEnd - cassStart;

            Map<String, Object> valMap = new HashMap<>();
            Map<Long, Integer> timeMap = new TreeMap<>();
            List<String> rowKeys = new ArrayList<>();

            // put the by-metric results into 1 csv-like table
            // (time,metric1,metric2,etc)
            // ... should find faster way to do this, but still 10x faster than
            // gwt DataTable serialization
            int rowCount = 0;
            for (Row<byte[], Long, Double> row : rows) {

                String rowKey = new String(row.getKey());
                Map<Long, Double> colMap = new HashMap<>();
                valMap.put(rowKey, colMap);
                rowKeys.add(rowKey);
                jsonOut += ",\"" + rowKey + "\"";

                List<HColumn<Long, Double>> cols = row.getColumnSlice().getColumns();
                Iterator<HColumn<Long, Double>> listIter = cols.listIterator();
                while (listIter.hasNext()) {
                    HColumn<Long, Double> c = (HColumn<Long, Double>) listIter.next();
                    colMap.put(c.getName(), c.getValue());
                    timeMap.put(c.getName(), 1);
                }
                rowCount++;
            }
            jsonOut += "]\n";

            int resultRowCount = 0;
            for (Long time : timeMap.keySet()) {
                jsonOut += ",[" + time;

                for (int i = 0; i < rowCount; i++) {
                    String rowKey = rowKeys.get(i);
                    Map<Long, Double> colMap = (Map<Long, Double>) valMap.get(rowKey);
                    Double val = colMap.get(time);
                    jsonOut += ",";
                    // round to 1000ths ; client doesn't need to process all the
                    // 10 decimal point resolution
                    if (val != null) {
                        jsonOut += Math.round(val * 1000.0) / 1000.0;
                    }
                }
                jsonOut += "]\n";
                resultRowCount++;
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            logger.info("getPerfData took: " + duration + " ms (cass query: "
                    + cassDuration + " ms) returning: " + resultRowCount
                    + " rows of " + rowCount + " metrics");

        } catch (HectorException he) {
            he.printStackTrace();
        }

        return jsonOut;
    }

    /**
     * Bucketize.
     *
     * @param timestamp the timestamp
     * @param step      the step
     * @return the long
     */
    public static long bucketize(long timestamp, long step) {
        return timestamp - timestamp % step;
    }

    public PerfHeader getHeader(String columnKey) {
        return phd.getHeader(columnKey);
    }

    public String getHostName() {
        return hostName;
    }

    public boolean isTestMode() {
        return isTestMode;
    }

    public void setTestMode(boolean isTestMode) {
        this.isTestMode = isTestMode;
    }

}


text:
class ChangeColumnItemsMarkedFromInvoiceModerations < ActiveRecord::Migration
  def change
    remove_column :invoice_moderations, :items_marked
    add_column :invoice_moderations, :items_marked, :integer, default: 0
  end
end


text:
using namespace ouroboros;

plugin_manager::plugin_manager(ouroboros_server& aServer)
:mServer(aServer)
{}

plugin_manager::~plugin_manager()
{
	typedef std::map<std::string, void*>::const_iterator citerator;
	for (citerator itr = mPlugins.begin(); itr != mPlugins.end(); itr++)
	{
		unload(itr->first);
	}
}

bool plugin_manager::unload(const std::string& aPath)
{
	if (mPlugins.count(aPath))
	{
		dlclose(mPlugins[aPath]);
		return true;
	}
	return false;
}

bool plugin_manager::load(const std::string& aPath)
{
	typedef void* library_t;
	std::string fullPath(aPath);

	library_t lib = dlopen(fullPath.c_str(), RTLD_NOW);

	const char *err = dlerror();
	if (err)
	{
		return false;
	}

	//HACK:
	//This is a hackish way to ward off undefined behavior caused by dlsym.
	//In short, POSIX requires conversions between object pointers and
	//function pointers to be possible, while the C and C++ ISO standards
	//do not. As a result, a simple cast is insuficcient. On the plus side,
	//newer POSIX standard require that this conversion be supported in order
	//for a system to be POSIX compliant, so any systems that can use dlsym
	//support this conversion.
	plugin_entry_function plugin;
	*(void **) (&plugin) = dlsym(lib, "plugin_entry");
	if ((err = dlerror()))
	{
		return false;
	}

	mPlugins[fullPath] = lib;
	return plugin(mServer);
}

static std::set<std::string> list_files(const std::string& aDir)
{
	std::set<std::string> results;
	char abs_path[PATH_MAX];

	realpath(aDir.c_str(), abs_path);
	std::string directory(abs_path);
	directory += '/';

	DIR *d = opendir(abs_path);

	if (d)
	{
		dirent *dir;
		while ((dir = readdir(d)) != NULL)
		{
			if (realpath((directory + dir->d_name).c_str(), abs_path))
			{
				results.insert(abs_path);
			}
		}
		closedir(d);
	}
	return results;
}

//TODO document the fact that loading will only load one plugin per absolute
//Path, so symlinks to the same place will not be counted twice

std::size_t plugin_manager::load_directory(const std::string& aDirectory)
{
	std::size_t number_loaded = 0;
	std::set<std::string> files(list_files(aDirectory));

	if (!files.empty())
	{
		typedef std::set<std::string>::const_iterator citerator;
		for (citerator itr = files.begin(); itr != files.end(); ++itr)
		{
			number_loaded += load(*itr);
		}
	}
	return number_loaded;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/search_hint_penerima"
        android:layout_gravity="center"
        android:inputType="text"/>

</LinearLayout>


text:
try:
    import collections.abc as collections_abc
except ImportError:
    import collections as collections_abc

from . import stage
from . import numpy_utils
from .dataset_ops import \
    ReadOpTable, ReadScalarOpTable, ReadOpArray, ReadScalarOpArray, \
    IndexOp, ColOp, CoordOp, SortOp, WhereOp, \
    _is_simple_slice, _is_coords

class DatasetBase(object):
    """ Base class type for proxying pytables datasets. """

    def __init__(self, reader, path, dtype, shape):
        self._reader = reader
        self._path = path

        self.dtype = dtype
        self.shape = shape

    def create_stage_natoms(self, size_natoms):
        """
        Create a stage that has a size in bytes of size_natoms * (atom size in bytes).
        :param size_natoms: The resulting stage will have
        """
        return stage.Stage(self.dtype.itemsize*size_natoms)

class Dataset(DatasetBase):
    """ Base class type for proxying pytables Arrays and Tables. """

    def _fill_shape(self, shape):
        """
        Given a desired partial shape, fill the rest of the shape dimensions with the dimensions of the dataset.

        :param shape: The partial shape, can be an integer or tuple.
        :return: The completed shape.
        """
        if not isinstance(shape, (collections_abc.Iterable, collections_abc.Sequence)):
            shape = [shape]
        shape = list(shape)
        if len(shape) < len(self.shape):
            shape = shape + [-1]*(len(self.shape) - len(shape))
        for i in range(len(shape)):
            if shape[i] is None or shape[i] == -1:
                shape[i] = self.shape[i]
        return shape

    def create_stage(self, shape):
        """
        Create a stage that can host requests with a size equal to the given shape.

        :param shape: A shape that specifies the size of the stage. It may be incomplete, where the remaining
            dimensions will be filled with the dimensions of this dataset.
        :return: A new stage with the requested size.
        """
        return stage.Stage(numpy_utils._calc_nbytes(self.dtype, self._fill_shape(shape)))

    def create_stage_pool(self, shape, num_stages):
        """
        Create a pool of stages. Each stage in the pool will be initialised with the given shape.

        :param shape: A shape that specifies the size of the stages in this pool. It may be incomplete, where
            the remaining dimensions will be filled with the dimensions of this dataset.
        :return: A stage pool, from which stages can be retrieved.
        """
        return stage.StagePool(self, shape, num_stages)

class TableDataset(Dataset):
    """ Proxy for dataset operations on pytables Tables. """

    def col(self, name):
        """
        Proxy a column retrieval operation. The interface for this method is equivalent to the pytables method
        of the same name.
        """
        return ColOp(self._path, name)

    def read(self, start=None, stop=None, step=None, field=None):
        """
        Proxy a read operation. The interface for this method is equivalent to the pytables method of the same
        name.
        """
        return ReadOpTable(self._path, field, start, stop, step)

    def read_coordinates(self, coords, field=None):
        """
        Proxy a coordinate read operation. The interface for this method is equivalent to the pytables method
        of the same name.
        """
        return CoordOp(self._path, field, coords)

    def read_sorted(self, sortby, checkCSI=False, field=None, start=None, stop=None, step=None):
        """
        Proxy a sorted read operation. The interface and requirements for this method are equivalent to the
        pytables method of the same name.
        """
        return SortOp(self._path, sortby, checkCSI, field, start, stop, step)

    def where(self, condition, condvars=None, start=None, stop=None, step=None):
        """
        Proxy a conditional selection operations. The interface for this method are equivalent to the pytables
        method of the same name.
        """
        if condvars is None:
            condvars = {}
        return WhereOp(self._path, condition, condvars, start, stop, step)

    def __getitem__(self, key):
        """
        Proxy an indexing operation on this dataset. The dataset indexing interface is equivalent to the pytables
        dataset indexing interface.
        """
        if key is Ellipsis:
            raise IndexError("Pytables does not support a single ellipsis index.")
        elif isinstance(key, str):
            return self.col(key)
        elif isinstance(key, int):
            return ReadScalarOpTable(self._path, None, key)
        elif isinstance(key, slice):
            return ReadOpTable(self._path, None, key.start, key.stop, key.step)
        elif _is_simple_slice(key):
            key = key[0]
            return ReadOpTable(self._path, None, key.start, key.stop, key.step)
        elif _is_coords(key):
            return CoordOp(self._path, None, key)
        return IndexOp(self._path, key)

class ArrayDataset(Dataset):

    def read(self, start=None, stop=None, step=None):
        """
        Proxy a read operation. The interface for this method is equivalent to the pytables method of the same
        name.
        """
        return ReadOpArray(self._path, None, start, stop, step)

    def __getitem__(self, key):
        """
        Proxy an indexing operation on this dataset. The dataset indexing interface is equivalent to the pytables
        dataset indexing interface.
        """
        if key is Ellipsis:
            raise IndexError("Pytables does not support a single ellipsis index.")
        elif isinstance(key, int):
            return ReadScalarOpArray(self._path, None, key)
        elif isinstance(key, slice):
            return ReadOpArray(self._path, None, key.start, key.stop, key.step)
        elif _is_simple_slice(key):
            key = key[0]
            return ReadOpArray(self._path, None, key.start, key.stop, key.step)
        return IndexOp(self._path, key)

class VLArrayDataset(DatasetBase):

    def read(self, start=None, stop=None, step=None):
        """
        Proxy a read operation. The interface for this method is equivalent to the pytables method of the same
        name.
        """
        return IndexOp(self._path, slice(start, stop, step))

    def __getitem__(self, key):
        """
        Proxy an indexing operation on this dataset. The dataset indexing interface is equivalent to the pytables
        dataset indexing interface.
        """
        if key is Ellipsis:
            raise IndexError("Pytables does not support a single ellipsis index.")
        return IndexOp(self._path, key)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using SharpDX;
using Fusion;
using Fusion.Mathematics;

using System.Xml.Serialization;

namespace Fusion.UserInterface {
	public class Config {
		public bool		ShowFrames			{ get; set; }
		public bool		SkipUserInterface	{ get; set; }
		public bool		ShowProfilingInfo	{ get; set; }

	}
}


text:
using Dufry.Comissoes.Domain.Entities;
using Dufry.Comissoes.Domain.Interfaces.Service.Common;
using System.Collections.Generic;

namespace Dufry.Comissoes.Domain.Interfaces.Service
{
    public interface IColaboradorService : IService<Colaborador>
    {
        IEnumerable<KeyValuePair<string, string>> All_ID_COMPOSTO();

        IEnumerable<dynamic> All_ID();

        IEnumerable<dynamic> GET_ID(string CodigoEmpresaAlternate, string CodigoFilialAlternate, string CodigoSecundario);
    }
}


text:
/* builder.h */

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

#pragma once

#include "../stdafx.h"
#include <string.h>

namespace mongo {

    class StringBuilder;

    class BufBuilder {
    public:
        BufBuilder(int initsize = 512) : size(initsize) {
            if ( size > 0 ) {
                data = (char *) malloc(size);
                assert(data);
            } else {
                data = 0;
            }
            l = 0;
        }
        ~BufBuilder() {
            kill();
        }

        void kill() {
            if ( data ) {
                free(data);
                data = 0;
            }
        }

        void reset( int maxSize = 0 ){
            l = 0;
            if ( maxSize && size > maxSize ){
                free(data);
                data = (char*)malloc(maxSize);
                size = maxSize;
            }

        }

        /* leave room for some stuff later */
        void skip(int n) {
            grow(n);
        }

        /* note this may be deallocated (realloced) if you keep writing. */
        char* buf() {
            return data;
        }

        /* assume ownership of the buffer - you must then free it */
        void decouple() {
            data = 0;
        }

        template<class T> void append(T j) {
            *((T*)grow(sizeof(T))) = j;
        }
        void append(short j) {
            append<short>(j);
        }
        void append(int j) {
            append<int>(j);
        }
        void append(unsigned j) {
            append<unsigned>(j);
        }
        void append(bool j) {
            append<bool>(j);
        }
        void append(double j) {
            append<double>(j);
        }

        void append(const void *src, size_t len) {
            memcpy(grow(len), src, len);
        }

        void append(const char *str) {
            append((void*) str, strlen(str)+1);
        }

        void append(const string &str) {
            append( (void *)str.c_str(), str.length() + 1 );
        }

        void append( int val , int padding ){

        }

        int len() const {
            return l;
        }

        void setlen( int newLen ){
            l = newLen;
        }

    private:
        /* returns the pre-grow write position */
        char* grow(int by) {
            int oldlen = l;
            l += by;
            if ( l > size ) {
                int a = size * 2;
                if ( a == 0 )
                    a = 512;
                if ( l > a )
                    a = l + 16 * 1024;
                assert( a < 64 * 1024 * 1024 );
                data = (char *) realloc(data, a);
                size= a;
            }
            return data + oldlen;
        }

        char *data;
        int l;
        int size;

        friend class StringBuilder;
    };

    class StringBuilder {
    public:
        StringBuilder( int initsize=256 )
            : _buf( initsize ){
        }

#define SBNUM(val,maxSize,macro) \
            int prev = _buf.l; \
            int z = sprintf( _buf.grow(maxSize) , macro , (val) );  \
            _buf.l = prev + z; \
            return *this;

        StringBuilder& operator<<( double x ){
            SBNUM( x , 25 , "%g" );
        }
        StringBuilder& operator<<( int x ){
            SBNUM( x , 11 , "%d" );
        }
        StringBuilder& operator<<( unsigned x ){
            SBNUM( x , 11 , "%u" );
        }
        StringBuilder& operator<<( long x ){
            SBNUM( x , 22 , "%ld" );
        }
        StringBuilder& operator<<( unsigned long x ){
            SBNUM( x , 22 , "%lu" );
        }
        StringBuilder& operator<<( long long x ){
            SBNUM( x , 22 , "%lld" );
        }
        StringBuilder& operator<<( unsigned long long x ){
            SBNUM( x , 22 , "%llu" );
        }
        StringBuilder& operator<<( short x ){
            SBNUM( x , 8 , "%hd" );
        }
        StringBuilder& operator<<( char c ){
            _buf.grow( 1 )[0] = c;
            return *this;
        }

        void append( const char * str ){
            int x = strlen( str );
            memcpy( _buf.grow( x ) , str , x );
        }
        StringBuilder& operator<<( const char * str ){
            append( str );
            return *this;
        }
        StringBuilder& operator<<( const string& s ){
            append( s.c_str() );
            return *this;
        }

        // access

        void reset( int maxSize = 0 ){
            _buf.reset( maxSize );
        }

        string str(){
            return string(_buf.data, _buf.l);
        }

    private:
        BufBuilder _buf;
    };

} // namespace mongo


text:
package com.mobgen.halo.android.sdk.core.management.segmentation;

import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;

import com.mobgen.halo.android.sdk.BuildConfig;
import com.mobgen.halo.android.sdk.R;
import com.mobgen.halo.android.testing.HaloRobolectricTest;

import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

import java.util.Locale;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

@Config(constants = BuildConfig.class, sdk = 23)
public class SegmentationTagCollectorsTests extends HaloRobolectricTest {

    @Test
    public void thatLoadFromDefaultLocale() {
        Locale.setDefault(Locale.CANADA);
        String locale = HaloLocale.fromDefaultLocale();
        assertThat(locale).isNotNull();
    }

    @Test
    public void thatLoadFromLocale() {
        String locale = HaloLocale.fromLocale(Locale.CANADA_FRENCH);
        assertThat(locale).isEqualTo(HaloLocale.FRENCH_CANADA);
    }

    @Test
    public void thatApplicationNameTagIsOk() {
        ApplicationNameCollector collector = new ApplicationNameCollector();
        ApplicationInfo info = new ApplicationInfo();
        info.labelRes = R.string.sdkName;
        Application app = spy(RuntimeEnvironment.application);
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return "Mock app name";
            }
        }).when(app).getString(R.string.sdkName);
        when(app.getApplicationInfo()).thenReturn(info);
        HaloSegmentationTag tag = collector.collect(app);
        assertThat(tag.getValue()).isEqualTo("Mock app name");
        assertThat(tag.getName()).isEqualTo("Application Name");
    }

    @Test
    public void thatApplicationSdkVersionTagIsOk() {
        SdkVersionCollector collector = new SdkVersionCollector();
        HaloSegmentationTag tag = collector.collect(RuntimeEnvironment.application);
        assertThat(tag.getValue()).isEqualTo(BuildConfig.HALO_SDK_VERSION);
        assertThat(tag.getName()).isEqualTo("Android SDK Version");
    }

    @Test
    public void thatApplicationVersionTagIsOk() {
        ApplicationVersionCollector collector = new ApplicationVersionCollector();
        HaloSegmentationTag tag = collector.collect(RuntimeEnvironment.application);
        //  assertThat(tag.getValue()).isEqualTo(BuildConfig.VERSION_NAME);
        assertThat(tag.getName()).isEqualTo("Application Version");
    }

    @Test
    public void thatApplicationVersionTagCreateAnException() throws PackageManager.NameNotFoundException {
        Context context = mock(Context.class);
        PackageManager manager = mock(PackageManager.class);
        String mockPackageName = "com.mock.mockpackage";
        when(manager.getPackageInfo(mockPackageName, 0)).thenThrow(new PackageManager.NameNotFoundException("Name not found"));
        when(context.getPackageManager()).thenReturn(manager);
        when(context.getPackageName()).thenReturn(mockPackageName);
        ApplicationVersionCollector collector = new ApplicationVersionCollector();
        HaloSegmentationTag tag = collector.collect(context);
        assertThat(tag).isNull();
    }

    @Test
    public void thatBluetooth4SupportIsEnabled() {
        Bluetooth4SupportCollector bluetoothTag = new Bluetooth4SupportCollector();
        Context context = mock(Context.class);
        PackageManager manager = mock(PackageManager.class);
        when(context.getPackageManager()).thenReturn(manager);
        when(manager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)).thenReturn(true);
        assertThat(bluetoothTag.collect(context)).isNotNull();
    }

    @Test
    public void thatBluetooth4SupportTagIsDisabled() {
        Bluetooth4SupportCollector bluetoothTag = new Bluetooth4SupportCollector();
        Context context = mock(Context.class);
        PackageManager manager = mock(PackageManager.class);
        when(context.getPackageManager()).thenReturn(manager);
        when(manager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)).thenReturn(false);
        assertThat(Boolean.valueOf(bluetoothTag.collect(context).getValue())).isFalse();
    }

    @Test
    public void thatDeviceManufacturerTagIsOk() {
        DeviceManufacturerCollector manufacturer = new DeviceManufacturerCollector();
        assertThat(manufacturer.collect(mock(Context.class)).getValue()).isEqualTo("unknown");
    }

    @Test
    public void thatDeviceModelTagIsOk() {
        DeviceModelCollector model = new DeviceModelCollector();
        assertThat(model.collect(mock(Context.class)).getValue()).isEqualTo("robolectric");
    }

    @Test
    public void thatDeviceTypeTagIsOk() {
        String tablet = "Tablet";
        String phone = "Phone";
        DeviceTypeCollector type = new DeviceTypeCollector();
        Context context = mock(Context.class);
        Resources resources = mock(Resources.class);
        when(context.getResources()).thenReturn(resources);
        when(resources.getBoolean(R.bool.isTablet)).thenReturn(true);
        assertThat(type.collect(context).getValue()).isEqualTo(tablet);
        when(resources.getBoolean(R.bool.isTablet)).thenReturn(false);
        assertThat(type.collect(context).getValue()).isEqualTo(phone);
    }

    @Test
    public void thatNfcSupportTagIsOk() {
        NFCSupportCollector nfcTag = new NFCSupportCollector();
        Context context = mock(Context.class);
        NfcManager manager = mock(NfcManager.class);
        Context emptyContext = mock(Context.class);
        NfcManager emptyManager = mock(NfcManager.class);
        when(context.getSystemService(Context.NFC_SERVICE)).thenReturn(manager);
        when(manager.getDefaultAdapter()).thenReturn(mock(NfcAdapter.class));
        when(emptyContext.getSystemService(Context.NFC_SERVICE)).thenReturn(emptyManager);
        when(emptyManager.getDefaultAdapter()).thenReturn(null);
        assertThat(Boolean.valueOf(nfcTag.collect(emptyContext).getValue())).isFalse();
        assertThat(nfcTag.collect(context)).isNotNull();
    }

    @Test
    public void thatPlatformNameTagIsOk() {
        assertThat(new PlatformNameCollector().collect(null).getValue()).isEqualTo(BuildConfig.HALO_PLATFORM_NAME);
        assertThat(new PlatformNameCollector().collect(mock(Context.class)).getValue()).isEqualTo(BuildConfig.HALO_PLATFORM_NAME);
    }

    @Test
    public void thatPlatformVersionTagIsOk() {
        assertThat(new PlatformVersionCollector().collect(null).getValue()).isEqualTo(Build.VERSION.RELEASE);
        assertThat(new PlatformVersionCollector().collect(mock(Context.class)).getValue()).isEqualTo(Build.VERSION.RELEASE);
    }

    @Test
    public void thatScreenSizeTagIsOk() {
        Context context = mock(Context.class);
        WindowManager manager = mock(WindowManager.class);
        Display display = mock(Display.class);
        when(context.getSystemService(Context.WINDOW_SERVICE)).thenReturn(manager);
        when(manager.getDefaultDisplay()).thenReturn(display);
        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Point point = (Point) invocation.getArguments()[0];
                point.x = 1080;
                point.y = 720;
                return null;
            }
        }).when(display).getSize(new Point());
        assertThat(new ScreenSizeCollector().collect(context).getValue()).isEqualTo("1080x720");
    }

    @Test
    public void thatTestDeviceTagValueIsOk() {
        TestDeviceCollector collector = new TestDeviceCollector(true);
        HaloSegmentationTag tag = collector.collect(RuntimeEnvironment.application);
        collector = new TestDeviceCollector(false);
        tag = collector.collect(RuntimeEnvironment.application);
        assertThat(Boolean.valueOf(tag.getValue())).isFalse();
    }

    @Test
    public void thatEqualsSegmentationIsOk() {
        TestDeviceCollector testCollector = new TestDeviceCollector(true);
        HaloSegmentationTag tag = testCollector.collect(RuntimeEnvironment.application);
        HaloSegmentationTag secondTag = testCollector.collect(RuntimeEnvironment.application);
        assertThat(tag.equals(secondTag)).isTrue();
        assertThat(tag.equals("Fake")).isFalse();
        assertThat(tag.getName().hashCode()).isEqualTo(tag.hashCode());
        assertThat(tag.compareTo(secondTag)).isEqualTo(0);
    }
}


text:
package test.cdi.beans_e;

import javax.enterprise.context.SessionScoped;

@SessionScoped
public class SessionScopedBean {

}


text:
/*
 * Save-state support.
 */

#define SAVE_STATE_MAGIC            "SNEPSAVE"

/* Consoles */
#define CONSOLE_ID_SG_1000          "SG\0"
#define CONSOLE_ID_COLECOVISION     "COL"
#define CONSOLE_ID_SMS              "SMS"
#define CONSOLE_ID_GAME_GEAR        "GG\0"

/* Console-specific state */
#define SECTION_ID_SG_1000_HW       "SG\0"
#define SECTION_ID_COLECOVISION_HW  "COL"
#define SECTION_ID_SMS_HW           "SMS"

/* Memory */
#define SECTION_ID_RAM              "RAM"
#define SECTION_ID_SRAM             "SRAM"
#define SECTION_ID_VRAM             "VRAM"

/* CPUs */
#define SECTION_ID_Z80              "Z80"

/* Sound Chips */
#define SECTION_ID_PSG              "PSG"

/* Video Chips */
#define SECTION_ID_VDP              "VDP"

/* Begin creating a new save state. */
void save_state_begin (const char *console_id);

/* Add a section to the save state. */
void save_state_section_add (const char *section_id, uint32_t version, uint32_t size, void *data);

/* Write the save state to disk. */
void save_state_write (const char *filename);

/* Load a state buffer from file. */
int load_state_begin (const char *filename, const char **console_id, uint32_t *sections_loaded);

/* Get a pointer to the next section. */
void load_state_section (const char **section_id, uint32_t *version, uint32_t *size, void **data);

/* Free the state buffer. */
void load_state_end (void);


text:
FNC_UI_PREFIX(dialogs,manageLocations,menu);
FNC_UI_PREFIX(dialogs,manageLocations,updateList);
FNC_UI_PREFIX(dialogs,manageLocations,selectOnMap);
FNC_UI_PREFIX(dialogs,manageLocations,add);
FNC_UI_PREFIX(dialogs,manageLocations,abandon);
FNC_UI_PREFIX(dialogs,manageLocations,rename);