text:
$(function() {

    $("#demo_rules").jui_filter_rules({

        bootstrap_version: "3",

        filters: [
            {
                filterName: "Lastname", "filterType": "text", field: "lastname", filterLabel: "Text",
                excluded_operators: ["in", "not_in"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {"type": "text", "value": "Krauß"}
                    }
                ]
            },
            {
                filterName: "AgeInYears", "filterType": "number", "numberType": "double", field: "age", filterLabel: "Nummer double",
                excluded_operators: ["in", "not_in"]
            },
            {
                filterName: "GroupMembers", "filterType": "number", "numberType": "integer", field: "group_members", filterLabel: "Nummer int",
                excluded_operators: ["in", "not_in"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {
                            type: "text",
                            value: "1",
                            "style": "width: 75px; margin: 0 5px;"
                        },
                        filter_widget: "spinner",
                        filter_widget_properties: {
                            min: 1,
                            max: 10
                        }
                    }

                ]
            },
            {
                filterName: "PerCentCompleted", "filterType": "number", "numberType": "integer", field: "percent_completed", filterLabel: "Prozent",
                excluded_operators: ["in", "not_in"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {
                            type: "text",
                            disabled: "disabled",
                            style: "width: 40px;  display: inline-block;"
                        }
                    },
                    {
                        filter_element: "div",
                        filter_element_attributes: {
                            style: "width: 120px; margin-left: 15px; display: inline-block;"
                        },
                        filter_widget: "slider",
                        filter_widget_properties: {
                            min: 0,
                            max: 100,
                            slide: function(event, ui) {
                                $(this).prev("input").val(ui.value);
                            }
                        },
                        returns_no_value: "yes"
                    }
                ]
            },
            {
                filterName: "DateInserted", "filterType": "date", field: "date_inserted", filterLabel: "Datum",
                excluded_operators: ["in", "not_in"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {
                            type: "text"
                        },
                        filter_widget: "datepicker",
                        filter_widget_properties: {
                            dateFormat: "dd/mm/yy",
                            changeMonth: true,
                            changeYear: true
                        }
                    }
                ],
                validate_dateformat: ["DD/MM/YYYY"],
                filter_value_conversion_server_side: {
                    function_name: "date_encode",
                    args: [
                        {"filter_value": "yes"},
                        {"value": "d/m/Y"}
                    ]
                }
            },
            {
                filterName: "DateUpdated", "filterType": "date", field: "date_updated", filterLabel: "Datum Update",
                excluded_operators: ["in", "not_in"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {
                            type: "text",
                            title: "Set the date and time using format: dd/mm/yyyy hh:mm:ss"
                        },
                        filter_widget: "datetimepicker",
                        filter_widget_properties: {
                            dateFormat: "dd/mm/yy",
                            timeFormat: "HH:mm:ss",
                            changeMonth: true,
                            changeYear: true,
                            showSecond: true
                        }
                    }
                ],
                validate_dateformat: ["DD/MM/YYYY HH:mm:ss"],
                filter_value_conversion: {
                    function_name: "local_datetime_to_UTC_timestamp",
                    args: [
                        {"filter_value": "yes"},
                        {"value": "DD/MM/YYYY HH:mm:ss"}
                    ]
                }
            },
            {
                filterName: "Category", "filterType": "number", "numberType": "integer", field: "category", filterLabel: "Kategorien (Ajax)",
                excluded_operators: ["equal", "not_equal", "less", "less_or_equal", "greater", "greater_or_equal"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {type: "checkbox"},
                        vertical_orientation: "yes"
                    }
                ],
                lookup_values_ajax_url: "ajax/kategorien.php"
            },
            {
                filterName: "Level", "filterType": "number", "numberType": "integer", field: "level", filterLabel: "Level",
                excluded_operators: ["in", "not_in", "less", "less_or_equal", "greater", "greater_or_equal"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {
                            type: "radio",
                            style: "width: auto; margin-top: 0; display: inline-block;"
                        }
                    }
                ],
                lookup_values: [
                    {lk_option: "Level1", lk_value: "1"},
                    {lk_option: "Level2", lk_value: "2"},
                    {lk_option: "Level3", lk_value: "3", lk_selected: "yes"}
                ]
            },
            {
                filterName: "Language", "filterType": "text", field: "language", filterLabel: "Sprache Ajax",
                excluded_operators: ["in", "not_in", "less", "less_or_equal", "greater", "greater_or_equal"],
                filter_interface: [
                    {
                        filter_element: "select"
                    }
                ],
                lookup_values_ajax_url: "ajax/languages.php"
            },
            {
                filterName: "Company", "filterType": "number", "numberType": "integer", field: "company", filterLabel: "Company",
                excluded_operators: ["in", "not_in", "less", "less_or_equal", "greater", "greater_or_equal"],
                filter_interface: [
                    {
                        filter_element: "select"
                    }
                ],
                lookup_values: [
                    {lk_option: "Company1", lk_value: "1"},
                    {lk_option: "Company2", lk_value: "2"},
                    {lk_option: "Company3", lk_value: "3", lk_selected: "yes"}
                ]
            },
            {
                filterName: "Country", "filterType": "text", field: "country", filterLabel: "Country code (Ajax)",
                excluded_operators: ["in", "not_in", "less", "less_or_equal", "greater", "greater_or_equal"],
                filter_interface: [
                    {
                        filter_element: "input",
                        filter_element_attributes: {type: "text", disabled: "disabled", style: "width: 80px; display: inline-block;"}
                    },
                    {
                        filter_element: "input",
                        filter_element_attributes: {type: "text", style: "width: 120px; margin-left: 5px; display: inline-block;"},
                        filter_widget: "autocomplete",
                        filter_widget_properties: {
                            source: "ajax/countries.php",
                            minLength: 1,
                            select: function(event, ui) {
                                $(this).prevAll("input").val(ui.item.id);
                            },
                            // mustMatch implementation
                            change: function(event, ui) {
                                if(ui.item == null) {
                                    $(this).val('');
                                    $(this).prevAll("input").val('');
                                }
                            }
                        },
                        returns_no_value: "yes"
                    }
                ]
            }
        ],

        onValidationError: function(event, data) {
            alert(data["err_description"] + ' (' + data["err_code"] + ')');
            if(data.hasOwnProperty("elem_filter")) {
                data.elem_filter.focus();
            }
        }

    });

});


text:
#include <aws/apigateway/model/RestApi.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace APIGateway
{
namespace Model
{

RestApi::RestApi() :
    m_idHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_createdDateHasBeenSet(false),
    m_versionHasBeenSet(false),
    m_warningsHasBeenSet(false),
    m_binaryMediaTypesHasBeenSet(false),
    m_minimumCompressionSize(0),
    m_minimumCompressionSizeHasBeenSet(false),
    m_apiKeySource(ApiKeySourceType::NOT_SET),
    m_apiKeySourceHasBeenSet(false),
    m_endpointConfigurationHasBeenSet(false),
    m_policyHasBeenSet(false)
{
}

RestApi::RestApi(JsonView jsonValue) :
    m_idHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_createdDateHasBeenSet(false),
    m_versionHasBeenSet(false),
    m_warningsHasBeenSet(false),
    m_binaryMediaTypesHasBeenSet(false),
    m_minimumCompressionSize(0),
    m_minimumCompressionSizeHasBeenSet(false),
    m_apiKeySource(ApiKeySourceType::NOT_SET),
    m_apiKeySourceHasBeenSet(false),
    m_endpointConfigurationHasBeenSet(false),
    m_policyHasBeenSet(false)
{
  *this = jsonValue;
}

RestApi& RestApi::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("id"))
  {
    m_id = jsonValue.GetString("id");

    m_idHasBeenSet = true;
  }

  if(jsonValue.ValueExists("name"))
  {
    m_name = jsonValue.GetString("name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("description"))
  {
    m_description = jsonValue.GetString("description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("createdDate"))
  {
    m_createdDate = jsonValue.GetDouble("createdDate");

    m_createdDateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("version"))
  {
    m_version = jsonValue.GetString("version");

    m_versionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("warnings"))
  {
    Array<JsonView> warningsJsonList = jsonValue.GetArray("warnings");
    for(unsigned warningsIndex = 0; warningsIndex < warningsJsonList.GetLength(); ++warningsIndex)
    {
      m_warnings.push_back(warningsJsonList[warningsIndex].AsString());
    }
    m_warningsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("binaryMediaTypes"))
  {
    Array<JsonView> binaryMediaTypesJsonList = jsonValue.GetArray("binaryMediaTypes");
    for(unsigned binaryMediaTypesIndex = 0; binaryMediaTypesIndex < binaryMediaTypesJsonList.GetLength(); ++binaryMediaTypesIndex)
    {
      m_binaryMediaTypes.push_back(binaryMediaTypesJsonList[binaryMediaTypesIndex].AsString());
    }
    m_binaryMediaTypesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("minimumCompressionSize"))
  {
    m_minimumCompressionSize = jsonValue.GetInteger("minimumCompressionSize");

    m_minimumCompressionSizeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("apiKeySource"))
  {
    m_apiKeySource = ApiKeySourceTypeMapper::GetApiKeySourceTypeForName(jsonValue.GetString("apiKeySource"));

    m_apiKeySourceHasBeenSet = true;
  }

  if(jsonValue.ValueExists("endpointConfiguration"))
  {
    m_endpointConfiguration = jsonValue.GetObject("endpointConfiguration");

    m_endpointConfigurationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("policy"))
  {
    m_policy = jsonValue.GetString("policy");

    m_policyHasBeenSet = true;
  }

  return *this;
}

JsonValue RestApi::Jsonize() const
{
  JsonValue payload;

  if(m_idHasBeenSet)
  {
   payload.WithString("id", m_id);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_createdDateHasBeenSet)
  {
   payload.WithDouble("createdDate", m_createdDate.SecondsWithMSPrecision());
  }

  if(m_versionHasBeenSet)
  {
   payload.WithString("version", m_version);

  }

  if(m_warningsHasBeenSet)
  {
   Array<JsonValue> warningsJsonList(m_warnings.size());
   for(unsigned warningsIndex = 0; warningsIndex < warningsJsonList.GetLength(); ++warningsIndex)
   {
     warningsJsonList[warningsIndex].AsString(m_warnings[warningsIndex]);
   }
   payload.WithArray("warnings", std::move(warningsJsonList));

  }

  if(m_binaryMediaTypesHasBeenSet)
  {
   Array<JsonValue> binaryMediaTypesJsonList(m_binaryMediaTypes.size());
   for(unsigned binaryMediaTypesIndex = 0; binaryMediaTypesIndex < binaryMediaTypesJsonList.GetLength(); ++binaryMediaTypesIndex)
   {
     binaryMediaTypesJsonList[binaryMediaTypesIndex].AsString(m_binaryMediaTypes[binaryMediaTypesIndex]);
   }
   payload.WithArray("binaryMediaTypes", std::move(binaryMediaTypesJsonList));

  }

  if(m_minimumCompressionSizeHasBeenSet)
  {
   payload.WithInteger("minimumCompressionSize", m_minimumCompressionSize);

  }

  if(m_apiKeySourceHasBeenSet)
  {
   payload.WithString("apiKeySource", ApiKeySourceTypeMapper::GetNameForApiKeySourceType(m_apiKeySource));
  }

  if(m_endpointConfigurationHasBeenSet)
  {
   payload.WithObject("endpointConfiguration", m_endpointConfiguration.Jsonize());

  }

  if(m_policyHasBeenSet)
  {
   payload.WithString("policy", m_policy);

  }

  return payload;
}

} // namespace Model
} // namespace APIGateway
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
package de.sldk.mc.metrics;

import java.util.List;

import org.bukkit.plugin.Plugin;

import io.prometheus.client.Collector;
import io.prometheus.client.hotspot.ThreadExports;

public class ThreadsWrapper extends Metric {
    public ThreadsWrapper(Plugin plugin) {
        super(plugin, new ThreadExportsCollector());
    }

    @Override
    protected void doCollect() {}

    private static class ThreadExportsCollector extends Collector {
        private static final ThreadExports threadExports = new ThreadExports();

        @Override
        public List<MetricFamilySamples> collect() {
            return HotspotPrefixer.prefixFromCollector(threadExports);
        }
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**access_info** | [**\Alfaview\Model\CommonAccessInfo**](CommonAccessInfo.md) |  | [optional]
**room_id** | **string** |  | [optional]
**ignore_promotes** | **bool** |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
#ifndef ORCS_PROPERTIES_H
#define ORCS_PROPERTIES_H

#include <map>
#include <string>
#include <set>
#include <sstream>

/**
 * This utility class is an alternative of a map to variable types. Internally
 * it store data as string objects, then the data must have the stream operator
 * implemented to store and retrieve the information.
 */
class Properties {

public:

    /**
     * Default constructor.
     */
    Properties() {
        // It does nothing.
    }

    /**
     * Copy constructor.
     *
     * @param   other
     *          The object to be copied.
     */
    Properties(const Properties& other) : properties(other.properties) {
        // It does nothing.
    }

    /**
     * Destructor.
     */
    virtual ~Properties() {
        // It does nothing.
    }

    /**
     * Assignment operator. Makes this object a copy of the the specified
     * object.
     *
     * @param   other
     *          The object to be copied.
     *
     * @return  A constant reference to this object.
     */
    virtual const Properties& operator=(const Properties& other) {
        this->properties.clear();
        this->properties.insert(other.properties.begin(), other.properties.end());
        return *this;
    }

    /**
     * The number of pairs key-value in this object.
     *
     * @return  The number of pairs key-value in this object.
     */
    unsigned int size() const {
        return properties.size();
    }

    /**
     * Check if this object contains a property with the given key.
     *
     * @param   key
     *          A key.
     *
     * @return  True if this object contains a property of the given key, false
     *          otherwise.
     */
    bool contains(std::string key) const {
        return (properties.count(key) > 0);
    }

    /**
     * Return a set with keys of the properties in this object.
     *
     * @return  A set with keys of properties.
     */
    std::set<std::string> get_keys() const {
        std::set<std::string> keys;
        for (auto iter = properties.cbegin(); iter != properties.cend(); ++iter) {
            keys.insert(iter->first);
        }

        return keys;
    }

    /**
     * Get a property by its key.
     *
     * @param   key
     *          The key.
     *
     * @return  The value.
     */
    template<typename T>
    T get(const std::string& key) const {

        // Load the value into a stream
        std::stringstream stream;
        stream << properties.at(key);

        // Get the value
        T value;
        stream >> value;

        return value;
    }

    /**
     * Get a property by its key.
     *
     * @param   key
     *          The key.
     * @param   default_value
     *          The value returned if this object does not contain a property
     *          with the given key.
     *
     * @return  The value.
     */
    template<typename T>
    T get(const std::string& key, T& default_value) const {

        // Check whether this object contains the given key
        if (contains(key)) {

            // Load the value into a stream
            std::stringstream stream;
            stream << properties.at(key);

            // Get the value
            T value;
            stream >> value;

            return value;
        }

        return default_value;
    }

    /**
     * Add a ney pair key-value.
     *
     * @param   key
     *          The key.
     * @param   value
     *          The value.
     */
    template<typename T>
    void add(const std::string& key, const T& value) {

        // Load the value into a stream
        std::stringstream stream;
        stream << value;

        // Store the value
        properties[key] = stream.str();
    }

private:
    std::map<std::string, std::string> properties;

};

#endif


text:
/**
 * Module dependencies.
 */
var util = require('util')
  , OAuth2Strategy = require('passport-oauth').OAuth2Strategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The pnut.io authentication strategy authenticates requests by delegating to
 * pnut.io using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `clientID`      your pnut.io application's App ID
 *   - `clientSecret`  your pnut.io application's App Secret
 *   - `callbackURL`   URL to which pnut.io will redirect the user after granting authorization
 *
 * Examples:
 *
 *     passport.use(new PnutStrategy({
 *         clientID: '123-456-789',
 *         clientSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/pnut/callback'
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://pnut.io/oauth/authenticate';
  options.tokenURL = options.tokenURL || 'https://api.pnut.io/v0/oauth/access_token';
  options.scopeSeparator = options.scopeSeparator || ',';

  OAuth2Strategy.call(this, options, verify);
  this.name = 'pnut';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Return extra pnut.io-specific parameters to be included in the authorization
 * request.
 *
 * Options:
 *  - `state`  A unique string used to maintain application state between the request and callback. Helpful in preventing XSS attacks. Gets appended to the end of the Callback URL to which pnut.io redirects the user after authentication.
 *
 * @param {Object} options
 * @return {Object}
 * @api protected
 */
Strategy.prototype.authorizationParams = function (options) {
  var params = {},
      state = options.state;

  if (state) {
    params['state'] = state;
  }

  return params;
};

/**
 * Retrieve user profile from pnut.io.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `facebook`
 *   - `id`               the user's pnut.io ID
 *   - `username`         the user's pnut.io username
 *   - `displayName`      the user's full name
 *   - `profileUrl`       the URL of the profile for the user on pnut.io
 *   - `emails`           the proxied or contact email address granted by the user
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {
  this._oauth2.getProtectedResource('https://api.pnut.io/v0/users/me', accessToken, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

    try {
      var json = JSON.parse(body).data || JSON.parse(body);

      var profile = { provider: 'pnut' };
      profile.id = json.id;
      profile.username = json.username;
      profile.displayName = json.name;
      profile.profileUrl = 'https://pnut.io/@' + json.username;

      profile._raw = body;
      profile._json = json;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;


text:
module Amigrind
  module Environments
    class Channel
      include Virtus.model

      attribute :name, String
    end
  end
end


text:
var assert = require("chai").assert;
var Init = require("truffle-init");
var Profiler = require("truffle-compile/profiler.js");
var Resolver = require("truffle-resolver");
var Artifactor = require("truffle-artifactor");

// TOOD: Move this to truffle-compile!

describe('profiler', function() {
  var config;

  before("Create a sandbox", function(done) {
    this.timeout(10000);
    Init.sandbox(function(err, result) {
      if (err) return done(err);
      config = result;
      config.resolver = new Resolver(config);
      config.artifactor = new Artifactor(config.contracts_build_directory);
      config.network = "development";
      done();
    });
  });

  it('profiles example project successfully', function(done) {
    Profiler.required_sources(config.with({
      paths: ["./MetaCoin.sol"],
      base_path: config.contracts_directory
    }), function(err, result) {
      if (err) return done(err);

      assert.equal(Object.keys(result).length, 2);
      done();
    });
  });
});


text:
require "spec_helper"
require_relative '../lib/zit/settings.rb'

def setup
    ENV.stub(:[]).with("HOME").and_return("foo")
    settings_file = double("File")
    File.stub(:open).with("foo/.zit").and_return(settings_file)
    settings_hash = Zit::Settings::DEFAULTS
    Psych.stub(:load).with(settings_file).and_return(settings_hash)
end

describe Zit::Settings::DEFAULTS do
  it "should have a skeletal settings defined" do
    Zit::Settings::DEFAULTS.should be_a_kind_of Hash
  end

  it "should have sensible defaults" do
    Zit::Settings::DEFAULTS[:settings_version].should be_a_kind_of(Float)
  end
end

describe Zit::Settings.new do
    before :each do
        setup
    end

    it "should create a new settings class" do
        File.stub(:exists?).with("foo/.zit").and_return("true")
        settings = Zit::Settings.new()
        settings.should be_an_instance_of Zit::Settings
    end

    it "should create a new file if one doesn't exist" do
        File.stub(:exists?).with("foo/.zit").and_return(false)
        File.stub(:open).with("foo/.zit", "w").and_return(true)
        settings = Zit::Settings.new
    end

    describe "foo" do
        before :each do
            setup
            File.stub(:exists?).with("foo/.zit").and_return(true)
            @settings = Zit::Settings.new()
            @settings.stub(:[]).with(:settings_version).and_return(1.0)
        end

        it "should return the right value" do
            @settings.get(:settings_version).should eq(1.0)
        end

        it "should convert non-symbol setting names" do
            @settings.get("settings_version").should eq(1.0)
        end
    end
end


text:
from .widget import Widget
from .error import Error, ErrorException

__all__ = [
    'Widget',
    'Error', 'ErrorException',
]


text:
<?php

namespace Drupal\Core\Entity\Plugin\EntityReferenceSelection;

use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Defines a fallback plugin for missing entity_reference selection plugins.
 *
 * @EntityReferenceSelection(
 *   id = "broken",
 *   label = @Translation("Broken/Missing")
 * )
 */
class Broken implements SelectionInterface {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['selection_handler'] = [
      '#markup' => t('The selected selection handler is broken.'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) { }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { }

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    return 0;
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableEntities(array $ids) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function entityQueryAlter(SelectInterface $query) { }

}


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

namespace _09.Custom_List_Sorter.Generic
{
    public class GenericList<T>
        where T : IComparable<T>
    {
        private readonly List<T> genericList;

        public GenericList()
        {
            this.genericList = new List<T>();
        }

        public void Add(T element)
        {
            if (element != null)
            {
                this.genericList.Add(element);
            }
        }

        public T Remove(int index)
        {
            if (index > this.genericList.Count - 1)
            {
                throw new IndexOutOfRangeException();
            }

            T elementToRemove = this.genericList[index];
            this.genericList.RemoveAt(index);
            return elementToRemove;
        }

        public bool Contains(T element)
        {
            return this.genericList.Any(s => s.Equals(element));
        }

        public void Swap(int index1, int index2)
        {
            if (index1 > this.genericList.Count - 1 || index2 > this.genericList.Count - 1)
            {
                throw new IndexOutOfRangeException();
            }

            T tmp = this.genericList[index1];
            this.genericList[index1] = this.genericList[index2];
            this.genericList[index2] = tmp;
        }

        public int Greater(T element)
        {
            return this.genericList.Count(s => s.CompareTo(element) == 1);
        }

        public T Max()
        {
            return this.genericList.Max();
        }

        public T Min()
        {
            return this.genericList.Min();
        }

        public string Print()
        {
            return string.Join(Environment.NewLine, this.genericList);
        }

        public void Sort()
        {
            this.genericList.Sort();
        }
    }
}


text:
{% extends path+"/_layout-case-simple2.html" %}

{% block actioncolumn %}

   {% include path+"/scenario1/_actionColumn.html" %}
{% endblock %}

{% block citizen_detail %}
Stevie Barnes
{% endblock %}

{% block citizen_content %}

    {# macro #}
  {{ nav.scenario_tabs("timeline",1,path1, customer._id) }}

              {% if data['confirm']%}

Referral closed

{{ 'Do MMMM YYYY' | baseDate(0)}}

               {% endif %}

Did not attend appointment

{{ 'Do MMMM YYYY' | baseDate(6)}}

                      Appointment details:
                      Non-neuro appointment
                      30th July 2019
                      11:00am
                      Tresco House

Appointment sms sent

{{ 'Do MMMM YYYY' | baseDate(9)}}

                          Phone number:
                          07815 526 315

Appointment letter sent

{{ 'Do MMMM YYYY' | baseDate(13)}}

                          Address:
                          158 Merit Court
                          Birmingham
                          B9 9IP

Appointment booked

{{ 'Do MMMM YYYY' | baseDate(16)}}

                          Appointment details:
                          Non-neuro appointment
                          {{ 'Do MMMM YYYY' | baseDate(10)}}
                          11:00am
                          Tresco House

Cancelled appointment

{{ 'Do MMMM YYYY' | baseDate(16)}}/ Barry Gallager / Tresco assessment centre

                          Assessment centre:
                          We have cancelled this appointment because there wasn't a hcp available to fullfill the appointment

Appointment booked

{{ 'Do MMMM YYYY' | baseDate(18)}}

                          Appointment details:
                          Non-neuro appointment
                          21st July 2019
                          11:00am
                          Tresco House

Referred for appointment

{{ 'Do MMMM YYYY' | baseDate(20)}}

GP report - medical evidence received

{{ 'Do MMMM YYYY' | baseDate(22)}}

GP Report - medical evidence requested

{{ 'Do MMMM YYYY' | baseDate(30)}}

Med 3 - medical evidence received

{{ 'Do MMMM YYYY' | baseDate(32)}}

UC50 form received

{{ 'Do MMMM YYYY' | baseDate(32)}}

UC50 form sent out

{{ 'Do MMMM YYYY' | baseDate(36)}}

                        Address:
                        158 Merit Court
                        Birmingham
                        B9 9IP

New referral created

{{ 'Do MMMM YYYY' | baseDate(36)}}

{% endblock %}

{# {% block page_script %}

{% endblock %} #}


text:
import argparse
import logging
import os
import sys

import ujson as json

from ifc import common
from ifc.gather import rss

def create_urls(config):
    ret = []
    for s in config["sites"]:
        url_template = s['url']
        titles_key = "titles"
        if titles_key in s: # append each url
            for title in s['titles']:
                ret.append(url_template % (title))
        else: # there's no url template just a straight url
            ret.append(url_template)
    return ret

def parse_args():
    parser = argparse.ArgumentParser(description='Downloads all article from Reuters archives between two dates')
    parser.add_argument('-c', "--config", help="Config file to load in via json. Default ./conf.json", default="./conf.json")
    args = parser.parse_args()
    if not os.path.exists(args.config) or not os.path.isfile(args.config):
        raise IOError("Config file missing or not a file: %s", args.config)
    return args

def main():
    args = parse_args()
    config = common.load_config_file(args.config)

    #TODO set up logging
    FORMAT = '%(asctime)-15s %(filename)s %(thread)d %(funcName)s %(lineno)d %(message)s'
    logging.basicConfig(format=FORMAT)

    articles_path = config["articlesPath"]
    base_path = config["basePath"]
    common.create_dir(articles_path)
    common.create_dir(base_path)

    stock_path = os.path.join(base_path, "stock")
    other_path = os.path.join(base_path, "other")
    bad_path = os.path.join(base_path, "bad")
    error_path = os.path.join(base_path, "error")
    common.create_dir(error_path)
    common.create_dir(bad_path)
    common.create_dir(stock_path)
    common.create_dir(other_path)

    storage_cfg = rss.ArticleStorageConfig(stock_path, other_path, bad_path, error_path)

    t_handles = []
    for url in create_urls(config): # each thread gets a url to watch
        t = rss.RssGatherer(url, articles_path, storage_cfg)
        t.start()
        t_handles.append(t)

    # wait for threads to never finish
    for t in t_handles:
        t.join()

if __name__ == "__main__":
    main()


text:
#ifndef _SYS__LOCK_H_
#define	_SYS__LOCK_H_

struct lock_object {
	const	char *lo_name;		/* Individual lock name. */
	u_int	lo_flags;
	u_int	lo_data;		/* General class specific data. */
	struct	witness *lo_witness;	/* Data for witness. */
};

#endif /* !_SYS__LOCK_H_ */


text:
namespace AjTalk.Compiler
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class Token
    {
        public TokenType Type { get; set; }

        public string Value { get; set; }

        public bool IsName() { return this.Type == TokenType.Name; }

        public bool IsOperator()
        {
            return this.Type == TokenType.Operator ||
                (this.Type == TokenType.Punctuation && this.Value == "|");
        }
    }
}


text:
<?php

namespace Fuel\Core;

/**
 * Security class tests
 *
 * @group Core
 * @group Security
 */
class Test_Security extends TestCase
{
	/**
	* Tests Security::htmlentities()
	*
	* @test
	*/
	public function test_htmlentities_doublequote_and_ampersand()
	{
		$output = Security::htmlentities('"H&M"');
		$expected = '"H&M"';
		$this->assertEquals($expected, $output);
	}

	/**
	* Tests Security::htmlentities()
	*
	* @test
	*/
	public function test_htmlentities_singlequote()
	{
		$output = Security::htmlentities("'");
		$expected = ''';
		$this->assertEquals($expected, $output);
	}

	/**
	* Tests Security::htmlentities()
	*
	* @test
	*/
	public function test_htmlentities_charactor_references_no_double_encode()
	{
		$output = Security::htmlentities('You must write & as &');
		$expected = 'You must write & as &';
		$this->assertEquals($expected, $output);
	}

	/**
	* Tests Security::htmlentities()
	*
	* @test
	*/
	public function test_htmlentities_charactor_references_double_encode()
	{
		$config = \Config::get('security.htmlentities_double_encode');
		\Config::set('security.htmlentities_double_encode', true);

		$output = Security::htmlentities('You must write & as &');
		$expected = 'You must write & as &amp;';
		$this->assertEquals($expected, $output);

		\Config::set('security.htmlentities_double_encode', $config);
	}

	/**
	* Tests Security::htmlentities()
	*
	* @test
	*/
	public function test_htmlentities_double_encode()
	{
		$output = Security::htmlentities('"H&M"');
		$output = Security::htmlentities($output);
		$expected = '"H&M"';
		$this->assertEquals($expected, $output);
	}
}


text:
package org.apache.hadoop.hbase.replication.regionserver;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hbase.CompatibilitySingletonFactory;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;

/**
 * This class is for maintaining the various replication statistics for a source and publishing them
 * through the metrics interfaces.
 */
@InterfaceAudience.Private
public class MetricsSource {

  public static final String SOURCE_SIZE_OF_LOG_QUEUE = "source.sizeOfLogQueue";
  public static final String SOURCE_AGE_OF_LAST_SHIPPED_OP = "source.ageOfLastShippedOp";
  public static final String SOURCE_LOG_EDITS_READ = "source.logEditsRead";
  public static final String SOURCE_LOG_EDITS_FILTERED = "source.logEditsFiltered";
  public static final String SOURCE_SHIPPED_BATCHES = "source.shippedBatches";
  public static final String SOURCE_SHIPPED_OPS = "source.shippedOps";

  public static final Log LOG = LogFactory.getLog(MetricsSource.class);
  private String id;

  private long lastTimestamp = 0;
  private int lastQueueSize = 0;

  private String sizeOfLogQueKey;
  private String ageOfLastShippedOpKey;
  private String logEditsReadKey;
  private String logEditsFilteredKey;
  private final String shippedBatchesKey;
  private final String shippedOpsKey;

  private MetricsReplicationSource rms;

  /**
   * Constructor used to register the metrics
   *
   * @param id Name of the source this class is monitoring
   */
  public MetricsSource(String id) {
    this.id = id;

    sizeOfLogQueKey = "source." + id + ".sizeOfLogQueue";
    ageOfLastShippedOpKey = "source." + id + ".ageOfLastShippedOp";
    logEditsReadKey = "source." + id + ".logEditsRead";
    logEditsFilteredKey = "source." + id + ".logEditsFiltered";
    shippedBatchesKey = "source." + this.id + ".shippedBatches";
    shippedOpsKey = "source." + this.id + ".shippedOps";
    rms = CompatibilitySingletonFactory.getInstance(MetricsReplicationSource.class);
  }

  /**
   * Set the age of the last edit that was shipped
   *
   * @param timestamp write time of the edit
   */
  public void setAgeOfLastShippedOp(long timestamp) {
    long age = EnvironmentEdgeManager.currentTimeMillis() - timestamp;
    rms.setGauge(ageOfLastShippedOpKey, age);
    rms.setGauge(SOURCE_AGE_OF_LAST_SHIPPED_OP, age);
    this.lastTimestamp = timestamp;
  }

  /**
   * Convenience method to use the last given timestamp to refresh the age of the last edit. Used
   * when replication fails and need to keep that metric accurate.
   */
  public void refreshAgeOfLastShippedOp() {
    if (this.lastTimestamp > 0) {
      setAgeOfLastShippedOp(this.lastTimestamp);
    }
  }

  /**
   * Set the size of the log queue
   *
   * @param size the size.
   */
  public void setSizeOfLogQueue(int size) {
    rms.setGauge(sizeOfLogQueKey, size);
    rms.incGauge(SOURCE_SIZE_OF_LOG_QUEUE, size - lastQueueSize);
    lastQueueSize = size;
  }

  /**
   * Add on the the number of log edits read
   *
   * @param delta the number of log edits read.
   */
  private void incrLogEditsRead(long delta) {
    rms.incCounters(logEditsReadKey, delta);
    rms.incCounters(SOURCE_LOG_EDITS_READ, delta);
  }

  /** Increment the number of log edits read by one. */
  public void incrLogEditsRead() {
    incrLogEditsRead(1);
  }

  /**
   * Add on the number of log edits filtered
   *
   * @param delta the number filtered.
   */
  private void incrLogEditsFiltered(long delta) {
    rms.incCounters(logEditsFilteredKey, delta);
    rms.incCounters(SOURCE_LOG_EDITS_FILTERED, delta);
  }

  /** The number of log edits filtered out. */
  public void incrLogEditsFiltered() {
    incrLogEditsFiltered(1);
  }

  /**
   * Convience method to apply changes to metrics do to shipping a batch of logs.
   *
   * @param batchSize the size of the batch that was shipped to sinks.
   */
  public void shipBatch(long batchSize) {
    rms.incCounters(shippedBatchesKey, 1);
    rms.incCounters(SOURCE_SHIPPED_BATCHES, 1);
    rms.incCounters(shippedOpsKey, batchSize);
    rms.incCounters(SOURCE_SHIPPED_OPS, batchSize);
  }

  /** Removes all metrics about this Source. */
  public void clear() {
    rms.removeMetric(sizeOfLogQueKey);
    rms.decGauge(SOURCE_SIZE_OF_LOG_QUEUE, lastQueueSize);
    lastQueueSize = 0;
    rms.removeMetric(ageOfLastShippedOpKey);

    rms.removeMetric(logEditsFilteredKey);
    rms.removeMetric(logEditsReadKey);

  }
}


text:
{% extends "lists/task_history_list_template.html" %}
{% block table_rows %}

      Latitude Range:
      ({{ task.latitude_min }}, {{ task.latitude_max }})

      Longitude Range:
      ({{ task.longitude_min }}, {{ task.longitude_max }})

      Time Range:
      ({{ task.time_start|date:"m/d/Y" }}, {{ task.time_end|date:"m/d/Y" }})

      Animated Product:
      {{ task.animated_product }}

      Query Type:
      {{ task.query_type }}

      Description:
      {{ task.description }}

{% endblock %}


text:
-- --------------------------------------------------------
-- Host:                         127.0.0.1
-- Server version:               5.5.44-MariaDB - mariadb.org binary distribution
-- Server OS:                    Win32
-- HeidiSQL Version:             9.1.0.4867
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

-- Dumping structure for table apps.rotas
DROP TABLE IF EXISTS `rotas`;
CREATE TABLE IF NOT EXISTS `rotas` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `comment` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `fullname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Data exporting was unselected.

-- Dumping structure for table apps.rotas_users
DROP TABLE IF EXISTS `rotas_users`;
CREATE TABLE IF NOT EXISTS `rotas_users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `users_id` int(11) unsigned DEFAULT NULL,
  `rotas_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UQ_1c53a186da714da27d2a3d895fa728d59dc97258` (`rotas_id`,`users_id`),
  KEY `index_foreignkey_rotas_users_users` (`users_id`),
  KEY `index_foreignkey_rotas_users_rotas` (`rotas_id`),
  CONSTRAINT `c_fk_rotas_users_rotas_id` FOREIGN KEY (`rotas_id`) REFERENCES `rotas` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Data exporting was unselected.

-- Dumping structure for table apps.users
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(10) NOT NULL,
  `fullname` char(20) DEFAULT NULL,
  `password` char(15) DEFAULT NULL,
  `hash` varchar(255) DEFAULT NULL,
  `colour` char(10) DEFAULT NULL,
  `shortdial` char(10) DEFAULT NULL,
  `longdial` char(15) DEFAULT NULL,
  `mobile` char(15) DEFAULT NULL,
  `home` char(15) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='InnoDB free: 11264 kB';

INSERT INTO `users` (`id`, `name`, `fullname`, `password`, `hash`, `colour`, `shortdial`, `longdial`, `mobile`, `home`) VALUES
	(1, 'ADMIN', 'Administrator_', 'Password1', '$2y$10$/Z3v5y2T/jBWaNcxXzFsA.KyF34yy0Dpbxz/R6Ba09Wn19J2tiSiW', 'FAD2F5', '611 7739', '07977 917739', '', '');

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
$output.java($WebConversation, "ConversationUtil")##

$output.requireStatic("org.apache.commons.lang.StringUtils.substringAfter")##
$output.requireStatic("org.apache.commons.lang.StringUtils.substringBefore")##
$output.require("javax.servlet.http.HttpServletRequest")##

public final class $output.currentClass {
    public static final String CID_PARAM_NAME = "_cid";
    public static final String CID_PARAM_SEPARATOR = "c";

    private ${output.currentClass}(){
    }

    public static String cidParamValue(String conversationId, String conversationContextId) {
        return conversationId + CID_PARAM_SEPARATOR + conversationContextId;
    }

    public static String cidParamNameValue(String conversationId, String conversationContextId) {
        return CID_PARAM_NAME + "=" + cidParamValue(conversationId, conversationContextId);
    }

    public static String getConversationId(HttpServletRequest request) {
        String _cid = request.getParameter(CID_PARAM_NAME);
        return _cid != null ? substringBefore(_cid, CID_PARAM_SEPARATOR) : null;
    }

    public static String getConversationContextId(HttpServletRequest request) {
        String _cid = request.getParameter(CID_PARAM_NAME);
        return _cid != null ? substringAfter(_cid, CID_PARAM_SEPARATOR) : null;
    }
}


text:
from i2cdevice import Device, Register, BitField

I2C_ADDR_35 = 35
I2C_ADDR_92 = 92
I2C_ADDR = [I2C_ADDR_35, I2C_ADDR_92]

CONTINUOUSHRES2MODE = Register('CONTINUOUSHRES2MODE', 17, read_only=False, bitwidth=0)
CONTINUOUSHRESMODE = Register('CONTINUOUSHRESMODE', 16, read_only=False, bitwidth=0)
CONTINUOUSLYLRESMODE = Register('CONTINUOUSLYLRESMODE', 19, read_only=False, bitwidth=0)
ONCEHRES2MODE = Register('ONCEHRES2MODE', 33, read_only=False, bitwidth=0)
ONCEHRESMODE = Register('ONCEHRESMODE', 32, read_only=False, bitwidth=0)
ONCELRESMODE = Register('ONCELRESMODE', 35, read_only=False, bitwidth=0)
POWERDOWN = Register('POWERDOWN', 0, read_only=False, bitwidth=0)
POWERON = Register('POWERON', 1, read_only=False, bitwidth=0)
RESET = Register('RESET', 7, read_only=False, bitwidth=0)

bh1750fvi = Device(I2C_ADDR, registers=(
    CONTINUOUSHRES2MODE,
    CONTINUOUSHRESMODE,
    CONTINUOUSLYLRESMODE,
    ONCEHRES2MODE,
    ONCEHRESMODE,
    ONCELRESMODE,
    POWERDOWN,
    POWERON,
    RESET
))


text:
package org.springframework.cloud.config.server.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.config.server.environment.SearchPathLocator;
import org.springframework.cloud.config.server.resource.GenericResourceRepository;
import org.springframework.cloud.config.server.resource.ResourceRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Dave Syer
 *
 */
@Configuration
@EnableConfigurationProperties(ConfigServerProperties.class)
@ConditionalOnMissingBean(ResourceRepository.class)
public class ResourceRepositoryConfiguration {

	@Bean
	@ConditionalOnBean(SearchPathLocator.class)
	public ResourceRepository resourceRepository(SearchPathLocator service) {
		return new GenericResourceRepository(service);
	}
}


text:
namespace cc {
class ScrollOffsetAnimationCurve;
}

namespace blink {

class PLATFORM_EXPORT CompositorScrollOffsetAnimationCurve
    : public CompositorAnimationCurve {
 public:
  using ScrollType = cc::ScrollOffsetAnimationCurveFactory::ScrollType;

  CompositorScrollOffsetAnimationCurve(FloatPoint, ScrollType);
  explicit CompositorScrollOffsetAnimationCurve(
      cc::ScrollOffsetAnimationCurve*);

  ~CompositorScrollOffsetAnimationCurve() override;

  void SetInitialValue(FloatPoint);
  FloatPoint GetValue(double time) const;
  double Duration() const;
  FloatPoint TargetValue() const;
  void ApplyAdjustment(IntSize);
  void UpdateTarget(base::TimeDelta time, FloatPoint new_target);

  // CompositorAnimationCurve implementation.
  std::unique_ptr<cc::AnimationCurve> CloneToAnimationCurve() const override;

 private:
  std::unique_ptr<cc::ScrollOffsetAnimationCurve> curve_;

  DISALLOW_COPY_AND_ASSIGN(CompositorScrollOffsetAnimationCurve);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_ANIMATION_COMPOSITOR_SCROLL_OFFSET_ANIMATION_CURVE_H_


text:
<?php

namespace Application\Config;

 class Config
 {
    const MAX_ITEM_OF_PAGE = 20;
    const MAX_DAYS_COUNTER =30;
    const USER_ADMIN =1;
    const USER_LEAVE1 =2;
    const USER_LEAVE2 =3;
    const ROLE_AGENCY = 4;

    // Acction id
    const LOGIN_ACTION = 1;
    const EDIT_ACTION = 2;
    const ADD_ACTION = 3;
    const REMOVE_ACTION = 4;
    const PAY_ACTION = 5;
    const EDIT_PAY_ACTION = 6;
    const DELETE_PAY_ACTION =7;
    const FILE_ACTION = 8;
    const EDIT_FILE_ACTION = 9;
    const DELETE_FILE_ACTION = 10;
    const COMMENT_ACTION = 11;
    const ADD_RECEIPT_ACTION = 12;
    const ADD_PAY_ACTION = 13;
    // process id
    const PROCESS_REC = 1;
    // type pay
    const PAY_INFO_COMMON = 0;
    const PAY_CUSTUMER = 1;
    const PAY_PROVIDER = 2;

    const PAY_ACTION_IS_TASK  = 1;
    const PAY_ACTION_NOT_TASK = 2;

    const IMAGE_PATH = "/files/users/avatar/origin/";
    const FILE_ATTACHMENT_PATH = "/data/attachment/";

    const ID_REPORTER_DEFAULT = 24;
    const ID_ASSIGN_DEFAULT = 19;

    const PASSWORD_MAX_LEN = 500;
    const PASSWORD_MIN_LEN = 8;
    const USERNAME_MAX_LEN = 500;
    const USERNAME_MIN_LEN = 5;

    const FILE_PERMISSION_ERROR    = 0;
    const FILE_PERMISSION_RDC      = 1;
    const FILE_PERMISSION_CUSTUMER = 2;
    const FILE_PERMISSION_PROVIDER = 3;
    const FILE_PERMISSION_ALL = 4;
    const FILE_PERMISSION_CUSTUMER_PROVIDER = 6;
    /* Add user */
    const PROCESS_OK = "Xử Lý Thành công";
    const PROCESS_NG = "Có Lỗi Trong Quá Trình Xử Lý";
    const PASSWORD_DIFFERENT = "Mật Khẩu Không Giống Nhau";
    const PASSWORD_IS_THE_SAME = "Mất Khẩu Giống Với Mật Khẩu Cũ";
    const PASSWORD_IS_WRONG = "Mật Khẩu Sai";
    const USER_EXIST = "Tài Khoản Đã Tồn Tài";
    const USER_IS_NOT_EXIST = "Tài Khoản Không Tồn Tại";
    const PASSWORD_EXCEED_MAX_LEN = "Mật Khẩu Quá Dài! (8 đến 500) ";
    const PASSWORD_BENEATH_MIN_LEN = "Mật Khẩu Quá Ngắn! (8 đến 500) ";
    const USERNAME_EXCEED_MAX_LEN = "Tài Khoản Quá Dài! (5 đến 500)";
    const USERNAME_BENEATH_MIN_LEN = "Tài Khoản Quá Ngắn! (5 đến 500)";
    const CERTIFICATE_EXIST = "Mã Chứng Chỉ Đã Tồn Tại";

    const AGENCY_TYPE = 0;
    const PROVIDER_TYPE = 1;
    const ASSIGN_REPORTER_TYPE = 2;
    const NOTIFY_CREATE = 0;
    const NOTIFY_MODIFY = 1;

    /* Task database field */
    const custumer_id = "custumer";
    const custumer_name = "Tên Khách Hàng";

    const agency_id = "agency_id";
    const agency_name = "Người Gửi (Bên Khách Hàng)";

    const agency_note_id = "agency_note";
    const agency_note_name = "Ghi Chú (Bên Khách Hàng)";

    const provider_id = "provider_id";
    const provider_name = "Người Gửi (Bên Khách Hàng)";

    const reporter_id = "reporter_id";
    const reporter_name = "Người Giám Sát";

    const date_open_id = "date_open";
    const date_open_name = "Ngày Nhận (Bên Khách Hàng)";

    const date_end_id = "date_end";
    const date_end_name = "Ngày Hẹn (Bên Khách Hàng)";

    const date_open_pr_id = "date_open_pr";
    const date_open_pr_name = "Ngày Nhận (Bên Nhà Cung Cấp)";

    const date_end_pr_id = "date_end_pr";
    const date_end_pr_name = "Ngày Hẹn (Bên Nhà Cung Cấp)";

    const provider_note_id = "provider_note";
    const provider_note_name = "Ghi Chú (Bên Nhà Cung Cấp)";

    const certificate_id = "certificate";
    const certificate_name = "Tên Sản Phẩm";

    const cost_sell_id = "cost_sell";
    const cost_sell_name = "Thoả Thuận (Bên Khách Hàng)";

    const cost_buy_id = "cost_buy";
    const cost_buy_name = "Thoả Thuận (Bên Nhà Cung Cấp)";

    const process_id = "process_id";
    const process_name = "Trạng Thái";

    const assign_id = "assign_id";
    const assign_name = "Người Chịu Trách Nhiệm";

    public static function getMinValue()
    {
        return self::MAX_ITEM_OF_PAGE;
    }

    public static function convertFieldID($field_id)
    {
        if ($field_id == Config::custumer_id) return Config::custumer_name;
        if ($field_id == Config::agency_id) return Config::agency_name;
        if ($field_id == Config::provider_id) return Config::provider_name;
        if ($field_id == Config::reporter_id) return Config::reporter_name;
        if ($field_id == Config::date_open_id) return Config::date_open_name;
        if ($field_id == Config::date_open_pr_id) return Config::date_open_pr_name;
        if ($field_id == Config::certificate_id) return Config::certificate_name;
        if ($field_id == Config::cost_sell_id) return Config::cost_sell_name;
        if ($field_id == Config::date_end_id) return Config::date_end_name;
        if ($field_id == Config::date_end_pr_id) return Config::date_end_pr_name;
        if ($field_id == Config::cost_buy_id) return Config::cost_buy_name;
        if ($field_id == Config::process_id) return Config::process_name;
        if ($field_id == Config::assign_id) return Config::assign_name;
        if ($field_id == Config::agency_note_id) return Config::agency_note_name;
        if ($field_id == Config::provider_note_id) return Config::provider_note_name;
        return $field_id;
    }
 }


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE400_Resource_Exhaustion__rand_fwrite_74a.cpp
Label Definition File: CWE400_Resource_Exhaustion.label.xml
Template File: sources-sinks-74a.tmpl.cpp
*/
/*
 * @description
 * CWE: 400 Resource Exhaustion
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Assign count to be a relatively small number
 * Sinks: fwrite
 *    GoodSink: Write to a file count number of times, but first validate count
 *    BadSink : Write to a file count number of times
 * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <map>

using namespace std;

namespace CWE400_Resource_Exhaustion__rand_fwrite_74
{

#ifndef OMITBAD

/* bad function declaration */
void badSink(map<int, int> countMap);

void bad()
{
    int count;
    map<int, int> countMap;
    /* Initialize count */
    count = -1;
    /* POTENTIAL FLAW: Set count to a random value */
    count = RAND32();
    /* Put count in a map */
    countMap[0] = count;
    countMap[1] = count;
    countMap[2] = count;
    badSink(countMap);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int> countMap);

static void goodG2B()
{
    int count;
    map<int, int> countMap;
    /* Initialize count */
    count = -1;
    /* FIX: Use a relatively small number */
    count = 20;
    /* Put count in a map */
    countMap[0] = count;
    countMap[1] = count;
    countMap[2] = count;
    goodG2BSink(countMap);
}

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(map<int, int> countMap);

static void goodB2G()
{
    int count;
    map<int, int> countMap;
    /* Initialize count */
    count = -1;
    /* POTENTIAL FLAW: Set count to a random value */
    count = RAND32();
    countMap[0] = count;
    countMap[1] = count;
    countMap[2] = count;
    goodB2GSink(countMap);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE400_Resource_Exhaustion__rand_fwrite_74; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package org.apache.thrift.partial;

import static org.junit.Assert.*;

import org.apache.thrift.partial.TestStruct;
import org.apache.thrift.partial.ThriftField;
import org.apache.thrift.partial.TstEnum;
import org.apache.thrift.partial.ExceptionAsserts;

import org.apache.thrift.TBase;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestPartialThriftDeserializer {

  private ThriftSerDe serde = new ThriftSerDe();
  private TBinaryProtocol.Factory binaryProtocolFactory = new TBinaryProtocol.Factory();
  private TCompactProtocol.Factory compactProtocolFactory = new TCompactProtocol.Factory();

  private PartialThriftTestData testData = new PartialThriftTestData();

  public TestPartialThriftDeserializer() throws TException {
  }

  @Test
  public void testArgChecks() throws TException {
    // Should not throw.
    List<String> fieldNames = Arrays.asList("i32Field");
    new TDeserializer(TestStruct.class, fieldNames, binaryProtocolFactory);

    // Verify it throws correctly.
    ExceptionAsserts.assertThrows(
        IllegalArgumentException.class,
        "'thriftClass' must not be null",
        () -> new TDeserializer(null, fieldNames, binaryProtocolFactory));

    ExceptionAsserts.assertThrows(
        IllegalArgumentException.class,
        "'fieldNames' must not be null",
        () -> new TDeserializer(TestStruct.class, null, binaryProtocolFactory));

    ExceptionAsserts.assertThrows(
        IllegalArgumentException.class,
        "'processor' must not be null",
        () -> new TDeserializer(TestStruct.class, fieldNames, null, binaryProtocolFactory));
  }

  /**
   * This test does not use partial deserialization. It is used to establish correctness
   * of full serialization used in the other tests.
   */
  @Test
  public void testRoundTripFull() throws TException {
    TestStruct ts1 = testData.createTestStruct(1, 2);

    byte[] bytesBinary = serde.serializeBinary(ts1);
    byte[] bytesCompact = serde.serializeCompact(ts1);

    TestStruct ts2 =  serde.deserializeBinary(bytesBinary, TestStruct.class);
    assertEquals(ts1, ts2);

    ts2 = serde.deserializeCompact(bytesCompact, TestStruct.class);
    assertEquals(ts1, ts2);
  }

  @Test
  public void testPartialSimpleField() throws TException, IOException {
    TestStruct ts1 = testData.createTestStruct(1, 1);
    assertTrue(ts1.isSetI16Field());
    assertTrue(ts1.isSetI32Field());

    byte[] bytesBinary = serde.serializeBinary(ts1);
    byte[] bytesCompact = serde.serializeCompact(ts1);

    List<String> fieldNames = Arrays.asList("i32Field");

    TDeserializer partialBinaryDeserializer =
        new TDeserializer(TestStruct.class, fieldNames, binaryProtocolFactory);
    TDeserializer partialCompactDeserializer =
        new TDeserializer(TestStruct.class, fieldNames, compactProtocolFactory);

    PartialThriftComparer comparer =
        new PartialThriftComparer(partialBinaryDeserializer.getMetadata());

    StringBuilder sb = new StringBuilder();
    TestStruct ts2 = (TestStruct) partialBinaryDeserializer.partialDeserializeObject(bytesBinary);
    validatePartialSimpleField(ts1, ts2);
    if (!comparer.areEqual(ts1, ts2, sb)) {
      fail(sb.toString());
    }

    ts2 = (TestStruct) partialCompactDeserializer.partialDeserializeObject(bytesCompact);
    validatePartialSimpleField(ts1, ts2);
    if (!comparer.areEqual(ts1, ts2, sb)) {
      fail(sb.toString());
    }
  }

  private void validatePartialSimpleField(TestStruct ts1, TestStruct ts2) {
    assertTrue(ts2.toString(), ts2.isSetI32Field());
    assertEquals(ts1.getI32Field(), ts2.getI32Field());
    assertFalse(ts2.isSetI16Field());
  }

  @Test
  public void testPartialComplex() throws TException {
    int id = 1;
    int numItems = 10;
    TestStruct ts1 = testData.createTestStruct(id, numItems);

    byte[] bytesBinary = serde.serializeBinary(ts1);
    byte[] bytesCompact = serde.serializeCompact(ts1);

    List<String> fieldNames = Arrays.asList(
        "byteField",
        "i16Field",
        "i32Field",
        "i64Field",
        "doubleField",
        "stringField",

        "enumField",
        "binaryField",

        // List fields
        "byteList",
        "i16List",
        "i32List",
        "i64List",
        "doubleList",
        "stringList",
        "enumList",
        "listList",
        "setList",
        "mapList",
        "structList",
        "binaryList",

        // Set fields
        "byteSet",
        "i16Set",
        "i32Set",
        "i64Set",
        "doubleSet",
        "stringSet",
        "enumSet",
        "listSet",
        "setSet",
        "mapSet",
        "structSet",
        "binarySet",

        // Map fields
        "byteMap",
        "i16Map",
        "i32Map",
        "i64Map",
        "doubleMap",
        "stringMap",
        "enumMap",
        "listMap",
        "setMap",
        "mapMap",
        "structMap",
        "binaryMap",

        // Struct field
        "structField"
    );
    StringBuilder sb = new StringBuilder();
    TDeserializer partialBinaryDeserializer =
        new TDeserializer(TestStruct.class, fieldNames, binaryProtocolFactory);
    TDeserializer partialCompactDeserializer =
        new TDeserializer(TestStruct.class, fieldNames, compactProtocolFactory);
    PartialThriftComparer comparer =
        new PartialThriftComparer(partialBinaryDeserializer.getMetadata());

    TestStruct ts2 = (TestStruct) partialBinaryDeserializer.partialDeserializeObject(bytesBinary);
    validatePartialComplex(ts1, ts2, id, numItems);
    if (!comparer.areEqual(ts1, ts2, sb)) {
      fail(sb.toString());
    }

    ts2 = (TestStruct) partialCompactDeserializer.partialDeserializeObject(bytesCompact);
    validatePartialComplex(ts1, ts2, id, numItems);
    if (!comparer.areEqual(ts1, ts2, sb)) {
      fail(sb.toString());
    }
  }

  private void validatePartialComplex(TestStruct ts1, TestStruct ts2, int id, int numItems) {

    // Validate primitive fields.
    assertTrue(ts2.toString(), ts2.isSetByteField());
    assertEquals(ts1.getByteField(), ts2.getByteField());

    assertTrue(ts2.isSetI16Field());
    assertEquals(ts1.getI16Field(), ts2.getI16Field());

    assertTrue(ts2.isSetI32Field());
    assertEquals(ts1.getI32Field(), ts2.getI32Field());

    assertTrue(ts2.isSetI64Field());
    assertEquals(ts1.getI64Field(), ts2.getI64Field());

    assertTrue(ts2.isSetDoubleField());
    assertEquals(ts1.getDoubleField(), ts2.getDoubleField(), 0.0001);

    assertTrue(ts2.isSetStringField());
    assertEquals(ts1.getStringField(), ts2.getStringField());

    assertTrue(ts2.isSetEnumField());
    assertEquals(ts1.getEnumField(), ts2.getEnumField());

    assertTrue(ts2.isSetBinaryField());
    assertArrayEquals(ts1.getBinaryField(), ts2.getBinaryField());

    // Validate list fields.
    validateList(ts2.getByteList(), id, numItems);
    validateList(ts2.getI16List(), id, numItems);
    validateList(ts2.getI32List(), id, numItems);
    validateList(ts2.getI64List(), id, numItems);
    validateList(ts2.getDoubleList(), id, numItems);
    validateStringList(ts2.getStringList(), id, numItems);
    validateEnumList(ts2.getEnumList(), id, numItems);

    validateListOfList(ts2.getListList(), id, numItems);
    validateListOfSet(ts2.getSetList(), id, numItems);
    validateListOfMap(ts2.getMapList(), id, numItems);
    validateListOfStruct(ts2.getStructList(), id, numItems);
    validateListOfBinary(ts2.getBinaryList(), id, numItems);

    // Validate set fields.
    validateSet(ts2.getByteSet(), Byte.class, numItems);
    validateSet(ts2.getI16Set(), Short.class, numItems);
    validateSet(ts2.getI32Set(), Integer.class, numItems);
    validateSet(ts2.getI64Set(), Long.class, numItems);
    validateSet(ts2.getDoubleSet(), Double.class, numItems);
    validateStringSet(ts2.getStringSet(), id, numItems);
    validateEnumSet(ts2.getEnumSet(), id, numItems);

    validateSetOfList(ts2.getListSet(), id, numItems);
    validateSetOfSet(ts2.getSetSet(), id, numItems);
    validateSetOfMap(ts2.getMapSet(), id, numItems);
    validateSetOfStruct(ts2.getStructSet(), id, numItems);
    validateSetOfBinary(ts2.getBinarySet(), id, numItems);

    // Validate map fields.
    validateMap(ts2.getByteMap(), Byte.class, numItems);
    validateMap(ts2.getI16Map(), Short.class, numItems);
    validateMap(ts2.getI32Map(), Integer.class, numItems);
    validateMap(ts2.getI64Map(), Long.class, numItems);
    validateMap(ts2.getDoubleMap(), Double.class, numItems);
    validateStringMap(ts2.getStringMap(), id, numItems);
    validateEnumMap(ts2.getEnumMap(), id, numItems);

    validateMapOfList(ts2.getListMap(), id, numItems);
    validateMapOfSet(ts2.getSetMap(), id, numItems);
    validateMapOfMap(ts2.getMapMap(), id, numItems);
    validateMapOfStruct(ts2.getStructMap(), id, numItems);
    validateMapOfBinary(ts2.getBinaryMap(), id, numItems);

    // Validate struct field.
    assertEquals(testData.createSmallStruct(id), ts2.getStructField());
  }

  private void validateNotNullAndNotEmpty(Collection<?> collection, int numItems) {
    assertNotNull(collection);
    assertEquals(numItems, collection.size());
  }

  // ----------------------------------------------------------------------
  // List validation helpers.

  private <V extends Number> void validateList(List<V> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      assertEquals(i, list.get(i).longValue());
    }
  }

  private void validateStringList(List<String> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);
    for (int i = 0; i < numItems; i++) {
      assertEquals(Integer.valueOf(i), Integer.valueOf(list.get(i)));
    }
  }

  private void validateEnumList(List<TstEnum> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);
    for (int i = 0; i < numItems; i++) {
      assertEquals(TstEnum.E_ONE, list.get(i));
    }
  }

  private <V extends Number> void validateListOfList(List<List<V>> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      validateList(list.get(i), id, numItems);
    }
  }

  private <V extends Number> void validateListOfSet(List<Set<V>> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      Set<V> set = list.get(i);
      for (int j = 0; j < numItems; j++) {
        assertTrue(set.contains(j));
      }
    }
  }

  private <V extends Number> void validateListOfMap(
      List<Map<String, V>> list, int id, int numItems) {

    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      Map<String, V> map = list.get(i);
      for (int j = 0; j < numItems; j++) {
        String key = Integer.toString(j);
        assertTrue(map.containsKey(key));
        assertEquals(j, map.get(key));
      }
    }
  }

  private void validateListOfStruct(List<SmallStruct> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      SmallStruct ss = testData.createSmallStruct(i);
      for (int j = 0; j < numItems; j++) {
        assertEquals(ss, list.get(i));
      }
    }
  }

  private void validateListOfBinary(List<ByteBuffer> list, int id, int numItems) {
    validateNotNullAndNotEmpty(list, numItems);

    for (int i = 0; i < numItems; i++) {
      ByteBuffer bb = ByteBuffer.wrap(testData.BYTES);
      assertTrue(bb.compareTo(list.get(i)) == 0);
    }
  }

  // ----------------------------------------------------------------------
  // Set validation helpers.

  private <V extends Number> void validateSet(Set<V> set, Class<V> clasz, int numItems) {
    validateNotNullAndNotEmpty(set, numItems);

    for (int i = 0; i < numItems; i++) {
      if (clasz == Byte.class) {
        assertTrue(set.contains((byte)i));
      } else if (clasz == Short.class) {
        assertTrue(set.contains((short)i));
      } else if (clasz == Integer.class) {
        assertTrue(set.contains(i));
      } else if (clasz == Long.class) {
        assertTrue(set.contains((long)i));
      } else if (clasz == Double.class) {
        assertTrue(set.contains((double)i));
      }
    }
  }

  private void validateStringSet(Set<String> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, numItems);

    for (int i = 0; i < numItems; i++) {
      assertTrue(set.contains(Integer.toString(i)));
    }
  }

  private void validateEnumSet(Set<TstEnum> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, 1);

    assertTrue(set.contains(TstEnum.E_ONE));
  }

  private void validateSetOfList(Set<List<Integer>> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, 1);

    List<Integer> list = new ArrayList<>(numItems);
    for (int i = 0; i < numItems; i++) {
      list.add(i);
    }

    assertTrue(set.contains(list));
  }

  private void validateSetOfSet(Set<Set<Integer>> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, 1);

    Set<Integer> setElt = new HashSet<>();
    for (int i = 0; i < numItems; i++) {
      setElt.add(i);
    }

    assertTrue(set.contains(setElt));
  }

  private void validateSetOfMap(Set<Map<String, Integer>> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, 1);

    Map<String, Integer> map = new HashMap<>();
    for (int i = 0; i < numItems; i++) {
      map.put(Integer.toString(i), i);
    }

    assertTrue(set.contains(map));
  }

  private void validateSetOfStruct(Set<SmallStruct> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, numItems);

    for (int i = 0; i < numItems; i++) {
      SmallStruct ss = testData.createSmallStruct(i);
      assertTrue(set.contains(ss));
    }
  }

  private void validateSetOfBinary(Set<ByteBuffer> set, int id, int numItems) {
    validateNotNullAndNotEmpty(set, 1);

    for (ByteBuffer b : set) {
      ByteBuffer bb = ByteBuffer.wrap(testData.BYTES);
      assertEquals(0, bb.compareTo(b));
    }
  }

  // ----------------------------------------------------------------------
  // Map validation helpers.

  void validateNotNullAndNotEmpty(Map<?, ?> map, int numItems) {
    assertNotNull(map);
    assertEquals(numItems, map.size());
  }

  private <V extends Number> void validateMap(Map<V, V> map, Class<V> clasz, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    for (int i = 0; i < numItems; i++) {
      if (clasz == Byte.class) {
        assertTrue(map.containsKey((byte)i));
        assertEquals((byte) i, map.get((byte) i));
      } else if (clasz == Short.class) {
        assertTrue(map.containsKey((short)i));
        assertEquals((short) i, map.get((short) i));
      } else if (clasz == Integer.class) {
        assertTrue(map.containsKey(i));
        assertEquals(i, map.get(i));
      } else if (clasz == Long.class) {
        assertTrue(map.containsKey((long)i));
        assertEquals((long) i, map.get((long) i));
      } else if (clasz == Double.class) {
        assertTrue(map.containsKey((double)i));
        assertEquals((double) i, map.get((double) i));
      }
    }
  }

  private void validateStringMap(Map<String, String> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    for (int i = 0; i < numItems; i++) {
      String key = Integer.toString(i);
      assertTrue(map.containsKey(key));
      assertEquals(key, map.get(key));
    }
  }

  private void validateEnumMap(Map<TstEnum, TstEnum> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, 1);

    assertTrue(map.containsKey(TstEnum.E_ONE));
    assertEquals(TstEnum.E_ONE, map.get(TstEnum.E_ONE));
  }

  private void validateMapOfList(Map<Integer, List<Integer>> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    List<Integer> list = new ArrayList<>(numItems);
    for (int i = 0; i < numItems; i++) {
      list.add(i);
    }

    for (int i = 0; i < numItems; i++) {
      assertTrue(map.containsKey(i));
      assertEquals(list, map.get(i));
    }
  }

  private void validateMapOfSet(Map<Integer, Set<Integer>> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    Set<Integer> setElt = new HashSet<>();
    for (int i = 0; i < numItems; i++) {
      setElt.add(i);
    }

    for (int i = 0; i < numItems; i++) {
      assertTrue(map.containsKey(i));
      assertEquals(setElt, map.get(i));
    }
  }

  private void validateMapOfMap(Map<Integer, Map<Integer, Integer>> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    Map<Integer, Integer> mapElt = new HashMap<>();
    for (int i = 0; i < numItems; i++) {
      mapElt.put(i, i);
    }

    for (int i = 0; i < numItems; i++) {
      assertTrue(map.containsKey(i));
      assertEquals(mapElt, map.get(i));
    }
  }

  private void validateMapOfStruct(Map<SmallStruct, SmallStruct> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    for (int i = 0; i < numItems; i++) {
      SmallStruct ss = testData.createSmallStruct(i);
      assertTrue(map.containsKey(ss));
      assertEquals(ss, map.get(ss));
    }
  }

  private void validateMapOfBinary(Map<Integer, ByteBuffer> map, int id, int numItems) {
    validateNotNullAndNotEmpty(map, numItems);

    for (int i = 0; i < numItems; i++) {
      ByteBuffer bb = ByteBuffer.wrap(testData.BYTES);
      assertTrue(map.containsKey(i));
      assertEquals(0, bb.compareTo(map.get(i)));
    }
  }
}


text:
@interface eleveSearch : BaseViewController
@property (nonatomic, assign) BOOL isDelete; //if u want clean
@end

@interface SearchElevesCell : UITableViewCell
@property (nonatomic, strong) UIImageView *avatarUser,*verifyStatus,*countryCode;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) UILabel *integralLabel;
@property (nonatomic, strong) UILabel *o_priceLabel ;
@property (nonatomic, strong) ColorLabel *priceLAbel;
@property (nonatomic, strong) ColorLabel *MyMobile;
@property (nonatomic, strong) UILabel *fullNameUser,*totalStudent,*province,*cityName,*areaName,*details,*locationUser,*locationIcon,*signForCall,*userNationality,*userNationalityIcon,*phoneIcon;
- (void)setInfoWith:(Student_data *)student_data;
@end


text:
"""Check all our redirects from remora to zamboni."""
from nose.tools import eq_

import amo
import amo.tests
from addons.models import Category
from applications.models import Application

from django.db import connection

class TestRedirects(amo.tests.TestCase):
    fixtures = ['base/apps', 'reviews/test_models',
                'addons/persona', 'base/global-stats']

    def test_persona_category(self):
        """`/personas/film and tv` should go to /themes/film-and-tv"""
        r = self.client.get('/personas/film and tv', follow=True)
        assert r.redirect_chain[-1][0].endswith(
                '/en-US/firefox/themes/film-and-tv')

    def test_top_tags(self):
        """`/top-tags/?` should 301 to `/tags/top`."""
        response = self.client.get(u'/top-tags/', follow=True)
        self.assert3xx(response, '/en-US/firefox/tags/top',
                       status_code=301)

    def test_contribute_installed(self):
        """`/addon/\d+/about` should go to
           `/addon/\d+/contribute/installed`."""
        r = self.client.get(u'/addon/5326/about', follow=True)
        redirect = r.redirect_chain[-1][0]
        assert redirect.endswith(
                        '/en-US/firefox/addon/5326/contribute/installed/')

    def test_contribute(self):
        """`/addons/contribute/$id` should go to `/addon/$id/contribute`."""
        response = self.client.get(u'/addon/5326/contribute', follow=True)
        redirect = response.redirect_chain[-1][0]
        assert redirect.endswith('/en-US/firefox/addon/5326/contribute/')

    def test_utf8(self):
        """Without proper unicode handling this will fail."""
        response = self.client.get(u'/api/1.5/search/ツールバー',
                                   follow=True)
        # Sphinx will be off so let's just test that it redirects.
        eq_(response.redirect_chain[0][1], 301)

    def test_parameters(self):
        """Bug 554976. Make sure when we redirect, we preserve our query
        strings."""
        url = u'/users/login?to=/en-US/firefox/users/edit'
        r = self.client.get(url, follow=True)
        self.assert3xx(r, '/en-US/firefox' + url, status_code=301)

    def test_reviews(self):
        response = self.client.get('/reviews/display/4', follow=True)
        self.assert3xx(response, '/en-US/firefox/addon/a4/reviews/',
                       status_code=301)

    def test_browse(self):
        response = self.client.get('/browse/type:3', follow=True)
        self.assert3xx(response, '/en-US/firefox/language-tools/',
                       status_code=301)

        response = self.client.get('/browse/type:2', follow=True)
        self.assert3xx(response, '/en-US/firefox/complete-themes/',
                       status_code=301)

        # Drop the category.
        response = self.client.get('/browse/type:2/cat:all', follow=True)
        self.assert3xx(response, '/en-US/firefox/complete-themes/',
                       status_code=301)

    def test_accept_language(self):
        """
        Given an Accept Language header, do the right thing.  See bug 439568
        for juicy details.
        """

        response = self.client.get('/', follow=True, HTTP_ACCEPT_LANGUAGE='de')
        self.assert3xx(response, '/de/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='en-us, de')
        self.assert3xx(response, '/en-US/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='fr, en')
        self.assert3xx(response, '/fr/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='pt-XX, xx, yy')
        self.assert3xx(response, '/pt-PT/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='pt')
        self.assert3xx(response, '/pt-PT/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='pt, de')
        self.assert3xx(response, '/pt-PT/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='pt-XX, xx, de')
        self.assert3xx(response, '/pt-PT/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='xx, yy, zz')
        self.assert3xx(response, '/en-US/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                   HTTP_ACCEPT_LANGUAGE='some,thing-very;very,,,broken!\'jj')
        self.assert3xx(response, '/en-US/firefox/', status_code=301)

        response = self.client.get('/', follow=True,
                                   HTTP_ACCEPT_LANGUAGE='en-us;q=0.5, de')
        self.assert3xx(response, '/de/firefox/', status_code=301)

    def test_users(self):
        response = self.client.get('/users/info/1', follow=True)
        self.assert3xx(response, '/en-US/firefox/user/1/',
                       status_code=301)

    def test_extension_sorting(self):
        r = self.client.get('/browse/type:1?sort=updated', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/?sort=updated',
                       status_code=301)
        r = self.client.get('/browse/type:1?sort=name', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/?sort=name',
                       status_code=301)
        r = self.client.get('/browse/type:1?sort=newest', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/?sort=created',
                       status_code=301)
        r = self.client.get('/browse/type:1?sort=weeklydownloads', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/?sort=popular',
                       status_code=301)
        r = self.client.get('/browse/type:1?sort=averagerating', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/?sort=rating',
                       status_code=301)
        # If we don't recognize the sort, they get nothing.
        r = self.client.get('/browse/type:1?sort=xxx', follow=True)
        self.assert3xx(r, '/en-US/firefox/extensions/',
                       status_code=301)

        a = Application.objects.create()
        Category.objects.create(pk=12, slug='woo', type=amo.ADDON_EXTENSION,
                                application=a, count=1, weight=0)
        r = self.client.get('/browse/type:1/cat:12?sort=averagerating',
                            follow=True)
        url, code = r.redirect_chain[-1]
        eq_(code, 301)
        assert url.endswith('/en-US/firefox/extensions/woo/?sort=rating')

    def test_addons_versions(self):
        r = self.client.get('/addons/versions/4', follow=True)
        self.assert3xx(r, '/en-US/firefox/addon/a4/versions/', status_code=301)

    def test_addons_versions_rss(self):
        r = self.client.get('/addons/versions/4/format:rss', follow=True)
        self.assert3xx(r, '/en-US/firefox/addon/4/versions/format:rss',
                       status_code=301)

    def test_addons_reviews_rss(self):
        r = self.client.get('/addons/reviews/4/format:rss', follow=True)
        self.assert3xx(r, '/en-US/firefox/addon/4/reviews/format:rss',
                       status_code=301)

    def test_mobile_to_android(self):
        """
        'Mobile' is the legacy XUL-based Firefox for Android.
        'Android' is the new hotness.
        """
        res = self.client.get('/mobile', follow=True)
        self.assert3xx(res, '/en-US/android/', status_code=301)

        res = self.client.get('/mobile/', follow=True)
        self.assert3xx(res, '/en-US/android/', status_code=301)

        res = self.client.get('/mobile/extensions/', follow=True)
        self.assert3xx(res, '/en-US/mobile/extensions/', status_code=301)

class TestPersonaRedirect(amo.tests.TestCase):
    fixtures = ['addons/persona']

    def test_persona_redirect(self):
        """`/persona/\d+` should go to `/addon/\d+`."""
        r = self.client.get('/persona/813', follow=True)
        self.assert3xx(r, '/en-US/firefox/addon/a15663/', status_code=301)

    def test_persona_redirect_addon_no_exist(self):
        """When the persona exists but not its addon, throw a 404."""
        # Got get shady to separate Persona/Addons.
        connection.cursor().execute("""
            SET FOREIGN_KEY_CHECKS = 0;
            TRUNCATE addons;
            SET FOREIGN_KEY_CHECKS = 1;
        """)
        r = self.client.get('/persona/813', follow=True)
        eq_(r.status_code, 404)


text:
#include "redis.h"
#include "pqsort.h" /* Partial qsort for SORT+LIMIT */

redisSortOperation *createSortOperation(int type, robj *pattern) {
    redisSortOperation *so = zmalloc(sizeof(*so));
    so->type = type;
    so->pattern = pattern;
    return so;
}

/* Return the value associated to the key with a name obtained
 * substituting the first occurence of '*' in 'pattern' with 'subst'.
 * The returned object will always have its refcount increased by 1
 * when it is non-NULL. */
robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
    char *p, *f;
    sds spat, ssub;
    robj keyobj, fieldobj, *o;
    int prefixlen, sublen, postfixlen, fieldlen;
    /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
    struct {
        int len;
        int free;
        char buf[REDIS_SORTKEY_MAX+1];
    } keyname, fieldname;

    /* If the pattern is "#" return the substitution object itself in order
     * to implement the "SORT ... GET #" feature. */
    spat = pattern->ptr;
    if (spat[0] == '#' && spat[1] == '\0') {
        incrRefCount(subst);
        return subst;
    }

    /* The substitution object may be specially encoded. If so we create
     * a decoded object on the fly. Otherwise getDecodedObject will just
     * increment the ref count, that we'll decrement later. */
    subst = getDecodedObject(subst);

    ssub = subst->ptr;
    if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
    p = strchr(spat,'*');
    if (!p) {
        decrRefCount(subst);
        return NULL;
    }

    /* Find out if we're dealing with a hash dereference. */
    if ((f = strstr(p+1, "->")) != NULL) {
        fieldlen = sdslen(spat)-(f-spat);
        /* this also copies \0 character */
        memcpy(fieldname.buf,f+2,fieldlen-1);
        fieldname.len = fieldlen-2;
    } else {
        fieldlen = 0;
    }

    prefixlen = p-spat;
    sublen = sdslen(ssub);
    postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
    memcpy(keyname.buf,spat,prefixlen);
    memcpy(keyname.buf+prefixlen,ssub,sublen);
    memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
    keyname.buf[prefixlen+sublen+postfixlen] = '\0';
    keyname.len = prefixlen+sublen+postfixlen;
    decrRefCount(subst);

    /* Lookup substituted key */
    initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(struct sdshdr)));
    o = lookupKeyRead(db,&keyobj);
    if (o == NULL) return NULL;

    if (fieldlen > 0) {
        if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;

        /* Retrieve value from hash by the field name. This operation
         * already increases the refcount of the returned object. */
        initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(struct sdshdr)));
        o = hashTypeGetObject(o, &fieldobj);
    } else {
        if (o->type != REDIS_STRING) return NULL;

        /* Every object that this function returns needs to have its refcount
         * increased. sortCommand decreases it again. */
        incrRefCount(o);
    }

    return o;
}

/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
 * the additional parameter is not standard but a BSD-specific we have to
 * pass sorting parameters via the global 'server' structure */
int sortCompare(const void *s1, const void *s2) {
    const redisSortObject *so1 = s1, *so2 = s2;
    int cmp;

    if (!server.sort_alpha) {
        /* Numeric sorting. Here it's trivial as we precomputed scores */
        if (so1->u.score > so2->u.score) {
            cmp = 1;
        } else if (so1->u.score < so2->u.score) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else {
        /* Alphanumeric sorting */
        if (server.sort_bypattern) {
            if (!so1->u.cmpobj || !so2->u.cmpobj) {
                /* At least one compare object is NULL */
                if (so1->u.cmpobj == so2->u.cmpobj)
                    cmp = 0;
                else if (so1->u.cmpobj == NULL)
                    cmp = -1;
                else
                    cmp = 1;
            } else {
                /* We have both the objects, use strcoll */
                cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
            }
        } else {
            /* Compare elements directly. */
            cmp = compareStringObjects(so1->obj,so2->obj);
        }
    }
    return server.sort_desc ? -cmp : cmp;
}

/* The SORT command is the most complex command in Redis. Warning: this code
 * is optimized for speed and a bit less for readability */
void sortCommand(redisClient *c) {
    list *operations;
    unsigned int outputlen = 0;
    int desc = 0, alpha = 0;
    int limit_start = 0, limit_count = -1, start, end;
    int j, dontsort = 0, vectorlen;
    int getop = 0; /* GET operation counter */
    robj *sortval, *sortby = NULL, *storekey = NULL;
    redisSortObject *vector; /* Resulting vector to sort */

    /* Lookup the key to sort. It must be of the right types */
    sortval = lookupKeyRead(c->db,c->argv[1]);
    if (sortval == NULL) {
        addReply(c,shared.emptymultibulk);
        return;
    }
    if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
        sortval->type != REDIS_ZSET)
    {
        addReply(c,shared.wrongtypeerr);
        return;
    }

    /* Create a list of operations to perform for every sorted element.
     * Operations can be GET/DEL/INCR/DECR */
    operations = listCreate();
    listSetFreeMethod(operations,zfree);
    j = 2;

    /* Now we need to protect sortval incrementing its count, in the future
     * SORT may have options able to overwrite/delete keys during the sorting
     * and the sorted key itself may get destroied */
    incrRefCount(sortval);

    /* The SORT command has an SQL-alike syntax, parse it */
    while(j < c->argc) {
        int leftargs = c->argc-j-1;
        if (!strcasecmp(c->argv[j]->ptr,"asc")) {
            desc = 0;
        } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
            desc = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
            alpha = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
            limit_start = atoi(c->argv[j+1]->ptr);
            limit_count = atoi(c->argv[j+2]->ptr);
            j+=2;
        } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
            storekey = c->argv[j+1];
            j++;
        } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
            sortby = c->argv[j+1];
            /* If the BY pattern does not contain '*', i.e. it is constant,
             * we don't need to sort nor to lookup the weight keys. */
            if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
            j++;
        } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
            listAddNodeTail(operations,createSortOperation(
                REDIS_SORT_GET,c->argv[j+1]));
            getop++;
            j++;
        } else {
            decrRefCount(sortval);
            listRelease(operations);
            addReply(c,shared.syntaxerr);
            return;
        }
        j++;
    }

    /* Destructively convert encoded sorted sets for SORT. */
    if (sortval->type == REDIS_ZSET) zsetConvert(sortval, REDIS_ENCODING_SKIPLIST);

    /* Load the sorting vector with all the objects to sort */
    switch(sortval->type) {
    case REDIS_LIST: vectorlen = listTypeLength(sortval); break;
    case REDIS_SET: vectorlen =  setTypeSize(sortval); break;
    case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
    default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
    }
    vector = zmalloc(sizeof(redisSortObject)*vectorlen);
    j = 0;

    if (sortval->type == REDIS_LIST) {
        listTypeIterator *li = listTypeInitIterator(sortval,0,REDIS_TAIL);
        listTypeEntry entry;
        while(listTypeNext(li,&entry)) {
            vector[j].obj = listTypeGet(&entry);
            vector[j].u.score = 0;
            vector[j].u.cmpobj = NULL;
            j++;
        }
        listTypeReleaseIterator(li);
    } else if (sortval->type == REDIS_SET) {
        setTypeIterator *si = setTypeInitIterator(sortval);
        robj *ele;
        while((ele = setTypeNextObject(si)) != NULL) {
            vector[j].obj = ele;
            vector[j].u.score = 0;
            vector[j].u.cmpobj = NULL;
            j++;
        }
        setTypeReleaseIterator(si);
    } else if (sortval->type == REDIS_ZSET) {
        dict *set = ((zset*)sortval->ptr)->dict;
        dictIterator *di;
        dictEntry *setele;
        di = dictGetIterator(set);
        while((setele = dictNext(di)) != NULL) {
            vector[j].obj = dictGetEntryKey(setele);
            vector[j].u.score = 0;
            vector[j].u.cmpobj = NULL;
            j++;
        }
        dictReleaseIterator(di);
    } else {
        redisPanic("Unknown type");
    }
    redisAssert(j == vectorlen);

    /* Now it's time to load the right scores in the sorting vector */
    if (dontsort == 0) {
        for (j = 0; j < vectorlen; j++) {
            robj *byval;
            if (sortby) {
                /* lookup value to sort by */
                byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
                if (!byval) continue;
            } else {
                /* use object itself to sort by */
                byval = vector[j].obj;
            }

            if (alpha) {
                if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
            } else {
                if (byval->encoding == REDIS_ENCODING_RAW) {
                    vector[j].u.score = strtod(byval->ptr,NULL);
                } else if (byval->encoding == REDIS_ENCODING_INT) {
                    /* Don't need to decode the object if it's
                     * integer-encoded (the only encoding supported) so
                     * far. We can just cast it */
                    vector[j].u.score = (long)byval->ptr;
                } else {
                    redisAssert(1 != 1);
                }
            }

            /* when the object was retrieved using lookupKeyByPattern,
             * its refcount needs to be decreased. */
            if (sortby) {
                decrRefCount(byval);
            }
        }
    }

    /* We are ready to sort the vector... perform a bit of sanity check
     * on the LIMIT option too. We'll use a partial version of quicksort. */
    start = (limit_start < 0) ? 0 : limit_start;
    end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
    if (start >= vectorlen) {
        start = vectorlen-1;
        end = vectorlen-2;
    }
    if (end >= vectorlen) end = vectorlen-1;

    if (dontsort == 0) {
        server.sort_desc = desc;
        server.sort_alpha = alpha;
        server.sort_bypattern = sortby ? 1 : 0;
        if (sortby && (start != 0 || end != vectorlen-1))
            pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
        else
            qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
    }

    /* Send command output to the output buffer, performing the specified
     * GET/DEL/INCR/DECR operations if any. */
    outputlen = getop ? getop*(end-start+1) : end-start+1;
    if (storekey == NULL) {
        /* STORE option not specified, sent the sorting result to client */
        addReplyMultiBulkLen(c,outputlen);
        for (j = start; j <= end; j++) {
            listNode *ln;
            listIter li;

            if (!getop) addReplyBulk(c,vector[j].obj);
            listRewind(operations,&li);
            while((ln = listNext(&li))) {
                redisSortOperation *sop = ln->value;
                robj *val = lookupKeyByPattern(c->db,sop->pattern,
                    vector[j].obj);

                if (sop->type == REDIS_SORT_GET) {
                    if (!val) {
                        addReply(c,shared.nullbulk);
                    } else {
                        addReplyBulk(c,val);
                        decrRefCount(val);
                    }
                } else {
                    redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
                }
            }
        }
    } else {
        robj *sobj = createZiplistObject();

        /* STORE option specified, set the sorting result as a List object */
        for (j = start; j <= end; j++) {
            listNode *ln;
            listIter li;

            if (!getop) {
                listTypePush(sobj,vector[j].obj,REDIS_TAIL);
            } else {
                listRewind(operations,&li);
                while((ln = listNext(&li))) {
                    redisSortOperation *sop = ln->value;
                    robj *val = lookupKeyByPattern(c->db,sop->pattern,
                        vector[j].obj);

                    if (sop->type == REDIS_SORT_GET) {
                        if (!val) val = createStringObject("",0);

                        /* listTypePush does an incrRefCount, so we should take care
                         * care of the incremented refcount caused by either
                         * lookupKeyByPattern or createStringObject("",0) */
                        listTypePush(sobj,val,REDIS_TAIL);
                        decrRefCount(val);
                    } else {
                        /* always fails */
                        redisAssert(sop->type == REDIS_SORT_GET);
                    }
                }
            }
        }
        setKey(c->db,storekey,sobj);
        decrRefCount(sobj);
        /* Note: we add 1 because the DB is dirty anyway since even if the
         * SORT result is empty a new key is set and maybe the old content
         * replaced. */
        server.dirty += 1+outputlen;
        addReplyLongLong(c,outputlen);
    }

    /* Cleanup */
    if (sortval->type == REDIS_LIST || sortval->type == REDIS_SET)
        for (j = 0; j < vectorlen; j++)
            decrRefCount(vector[j].obj);
    decrRefCount(sortval);
    listRelease(operations);
    for (j = 0; j < vectorlen; j++) {
        if (alpha && vector[j].u.cmpobj)
            decrRefCount(vector[j].u.cmpobj);
    }
    zfree(vector);
}