text:
.navbar {
	background: #ff6600;
	border-bottom: none;
	color: #fff;
}
.navbar .center {
    max-width: 50%;
}
.statusbar-overlay {
	background: #ff6600;
}
a {
	color: #ff6600;
}
.page {
	background: #f6f6ef;
}
.stories-list {
	margin: 0;
}
.stories-list ul {
	border: none;
}
.stories-list .item-title {
	font-weight: normal;
}
.stories-list .item-subtitle {
	font-size: 14px;
	color: #555;
}
.stories-list .item-text {
	font-size: 14px;
	height: auto;
	-webkit-line-clamp: auto;
	white-space: nowrap;
}
.stories-list .badge {
	border: 1px solid #ff6600;
	color: #ff6600;
	background: none;
	min-width: 30px;
	text-align: center;
	line-height: 20px;
	display: block;
	position: relative;
}
.stories-list .badge:before {
	content: '';
	width: 0;
	height: 0;
	position: absolute;
	left: 50%;
	margin-left: -8px;
	bottom: -3px;
	border-left: 0px solid transparent;
	border-right: 4px solid transparent;
	border-top: 3px solid #ff6600;
}
.stories-list .item-link.active-state {
	background: #e7e7e7;
}
.stories-list.media-list .item-link .item-title-row {
	padding-right: 0;
	background: none;
}
.story-header {
	height: 130px;
	box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.1);
	position: relative;
	z-index: 10;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
	padding: 20px 15px;
	background: #fff;
}
.story-title {
	font-size: 17px;
	font-weight: 500;
	line-height: 22px;
	max-height: 44px;
	-webkit-line-clamp: 2;
	text-overflow: ellipsis;
	-webkit-box-orient: vertical;
	display: -webkit-box;
	position: relative;
	overflow: hidden;
	margin-bottom: 5px;
}
.story-info {
	color: #8e8e93;
}
.story-comments {
	position: relative;
	height: -moz-calc(100% - 130px);
	height: -ms-calc(100% - 130px);
	height: -webkit-calc(100% - 130px);
	height: calc(100% - 130px);
	overflow: auto;
	box-sizing: border-box;
	-webkit-overflow-scrolling: touch;
}
.story-comments .messages {
	padding-bottom: 20px;
}
.story-comments .messages > .preloader {
	position: absolute;
	width: 32px;
	height: 32px;
	left: 50%;
	margin-left: -16px;
	top: 20px;
}
.story-comments .preloader-label {
	position: absolute;
	top: 60px;
	left: 0;
	width: 100%;
	text-align: center;
}
.story-comments .message {
	max-width: 98%;
}
.story-comments .message-name .comment-name {
	font-weight: 500;
	color: #333;
}
.story-comments .message-text {
	font-size: 14px;
	background: #fff;
	color: #000;
	line-height: 1.3;
}
.story-comments .message-sent .message-text {
	font-size: 14px;
	background: #ff6600;
	color: #fff;
	line-height: 1.3;
}
.story-comments .message-sent .message-text a {
	color: #555;
}
.story-comments .message-kids {
	margin: 0 20px 0 15px;
}
.story-comments .message-kids > a,
.story-comments .message-kids > .preloader {
	margin-left: 12px;
	position: relative;
	top: -2px;
	display: inline-block;
}
.story-comments .message-kids > a {
	font-size: 12px;
	margin-bottom: 10px;
	height: 16px;
}
.story-comments .message-kids > .preloader {
	width: 16px;
	height: 16px;
	margin-bottom: 7px;
}
.story-comments .message-kids > a i {
	border: 1px solid #ff6600;
	width: 15px;
	height: 12px;
	display: inline-block;
	position: relative;
	border-radius: 10px;
	vertical-align: top;
}
.story-comments .message-kids > a i:before {
	content: '';
	width: 0;
	height: 0;
	position: absolute;
	left: 50%;
	margin-left: -5px;
	bottom: -3px;
	border-left: 0px solid transparent;
	border-right: 5px solid transparent;
	border-top: 3px solid #ff6600;
}
.message-kids {
	text-align: right;
}
.message-kids .message {
	text-align: left;
}
.story-comments .message pre {
	white-space: normal;
}
.icon-refresh {
	background: url(../img/icon-reload.png) no-repeat center;
	width: 25px;
	height: 25px;
	background-size: 25px auto;
}
.icon-watch {
	background: url(../img/icon-watch.png) no-repeat center;
	width: 25px;
	height: 25px;
	background-size: 25px auto;
}
.refresh-link.refreshing .icon-refresh {
	-webkit-animation-name: rotate;
	-webkit-animation-duration: 1s;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
	-moz-animation-name: rotate;
	-moz-animation-duration: 1s;
	-moz-animation-iteration-count: infinite;
	-moz-animation-timing-function: linear;
	animation-name: rotate;
	animation-duration: 1s;
	animation-iteration-count: infinite;
	animation-timing-function: linear;
}
@-webkit-keyframes rotate {
	from {
		-webkit-transform: rotate(0deg);
	}
	to {
		-webkit-transform: rotate(360deg);
	}
}
@-moz-keyframes rotate {
	from {
		-moz-transform: rotate(0deg);
	}
	to {
		-moz-transform: rotate(360deg);
	}
}
@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
/* This will fix flicker navbar in left panel view */

.panel-left .navbar {
	-webkit-transform: translate3d(0, 0, 0);
}
/* Because we have panels-overlay inside of .views we need to fix its open position for right panel */

body.with-panel-right-reveal .panel-overlay {
	margin-left: 0;
}
html.with-statusbar-overlay body .panel {
	padding-top: 0;
}
.navbar .left a + a {
	margin-left: 0;
}
.view-left .navbar .left .open-panel {
	display: none;
}
.choose-story {
	display: none;
}
@media (max-width: 767px) {
	.navbar .left .open-panel {
		display: none;
	}
	.view-main {
		display: none;
	}
	.panel.panel-left.panel-cover {
		display: block;
		left: 0%;
		width: 100%;
		-webkit-transition: 0ms;
		transition: 0ms;
	}
	body.with-panel-left-cover .panel-left {
		-webkit-transform: translate3d(0%, 0, 0);
		-ms-transform: translate3d(0%, 0, 0);
		transform: translate3d(0%, 0, 0);
		-webkit-transition: 0ms;
		transition: 0ms;
	}
	.view-left .tablet-title {
		display: none;
	}
}
@media (min-width: 768px) {
	.panel.panel-left.panel-cover {
		box-shadow: 1px 0px 0px rgba(0, 0, 0, 0.2);
		width: 320px;
	}
	.stories-list a.active-story {
		background: rgba(0, 0, 0, 0.1);
	}
	.view-main .navbar .back {
		display: none;
	}
	.view-left .mobile-title {
		display: none;
	}
	.view-left .tablet-title {
		display: block;
	}
}
@media (min-width: 768px) and (max-width: 1023px) {
	body.with-panel-left-cover .panel-left {
		-webkit-transform: translate3d(100%, 0, 0);
		-ms-transform: translate3d(100%, 0, 0);
		transform: translate3d(100%, 0, 0);
	}
	.panel.panel-left.panel-cover {
		left: -320px;
	}
	.choose-story {
		display: block;
		text-align: center;
		font-size: 21px;
		line-height: 30px;
		font-weight: 300;
		position: absolute;
		left: 0;
		width: 100%;
		top: 50%;
		margin-top: -15px;
		text-align: center;
	}
}
@media (min-width: 1024px) {
	.panel.panel-left.panel-cover {
		display: block;
		left: 0%;
	}
	body.with-panel-left-cover .panel-left {
		-webkit-transform: translate3d(0%, 0, 0);
		-ms-transform: translate3d(0%, 0, 0);
		transform: translate3d(0%, 0, 0);
	}
	.view-main {
		float: right;
		width: -webkit-calc(100% - 320px);
		width: -moz-calc(100% - 320px);
		width: -ms-calc(100% - 320px);
		width: calc(100% - 320px);
	}
	.view-main .navbar .open-panel {
		display: none;
	}
}
.notifications .item-text {
	display: block;
}


text:
const BaseHook = require('./_basehook.js');

class BeforeAll extends BaseHook {
  get skipTestcasesOnError() {
    return true;
  }

  constructor(context, addtOpts) {
    super(BaseHook.beforeEach, context, addtOpts);
  }
}

module.exports = BeforeAll;

redpajama_set_name: RedPajamaGithub


text:
module Cybele
  module Helpers
    module General
      def readme
        template 'README.md.erb',
                 'README.md',
                 force: true
      end

      def remove_readme_rdoc
        remove_file 'README.rdoc',
                    force: true
      end

      def add_gems
        # Add gems
        append_file('Gemfile', template_content('Gemfile.erb'))
      end

      def force_ssl_setting
        gsub_file 'config/environments/production.rb',
                  /# config.force_ssl = true/, "config.force_ssl = ENV['RAILS_FORCE_SSL'].present?"
        gsub_file 'config/environments/staging.rb',
                  /# config.force_ssl = true/, "config.force_ssl = ENV['RAILS_FORCE_SSL'].present?"
        %w[.env.local .env.production .env.staging .env.sample].each do |env|
          append_file(env, template_content('ssl/ssl_env_all.erb'))
        end
      end

      def add_editor_config
        copy_file 'editorconfig', '.editorconfig'
      end

      def add_cybele_version
        copy_file 'VERSION.txt', 'VERSION.txt'
        run 'ln -s ../VERSION.txt public/VERSION.txt'
      end

      def use_postgres_config_template
        template 'postgresql_database.yml.erb',
                 'config/database.yml',
                 force: true
      end

      def create_database
        bundle_command 'exec rake db:create db:migrate'
      end

      def generate_config
        generate 'config:install'
        run 'cp config/settings/development.yml config/settings/staging.yml'
        append_file('config/settings.yml', template_content('settings.yml.erb'))
        remove_file 'config/settings.local.yml', force: true
      end

      def generate_rollbar
        generate 'rollbar'
      end

      def configure_bullet
        configure_environment 'development', template_content('bullet/bullet_settings.rb.erb')
      end

      private

      def configure_environment(rails_env, config)
        inject_into_file("config/environments/#{rails_env}.rb", "\n#{config}", before: "\nend")
      end

      def action_mailer_host(rails_env)
        configure_environment(rails_env, template_content('mailer/host.rb.erb'))
      end
    end
  end
end


text:
local Recipe = {
    _class = 'Recipe',
    _ingredients_mt = require('stdlib/data/modules/ingredients'),
    _results_mt = require('stdlib/data/modules/results')
}
setmetatable(Recipe, require('stdlib/data/data'))

local Is = require('stdlib/utils/is')
local Item = require('stdlib/data/item')

--TODO
--[[
    Recipe:replace_ingredients --swap whole ingredients
    Recipe:replace_results --swap whole results

    Finish Recipe:xxx_result stuff
]]

function Recipe:_caller(recipe)
    local new = self:get(recipe, 'recipe')
    --[[prototype
        type, name
        localised_name[opt]
        localised_description[opt]
        subgroup, order (needed when no main product)
    --]]
    --[[recipe
        category
        icon/icons (or has main_product)
        crafting_machine_tint = {
            primary, secondary, tertiary
        }
        normal/expensive = {
            ingredients
            results, result, result_count[opt=1] (result ignored if results present) at least 1 result
            main_product
            energy_required > 0.001
            emissions_multiplier
            requester_paste_multiplier
            overload_multiplier
            enabled <boolean>
            hidden <boolean>
            hide_from_stats <boolean>
            allow_decomposition <boolean>
            allow_as_intermediate <boolean>
            allow_intermediates <boolean>
            always_show_made_in <boolean>
            show_amount_in_title <boolean>
            always_show_products <boolean>
        }
    --]]
    -- Convert the recipe to difficult format

    -- Convert the ingredients to full format
    --new:Ingredients()

    -- Convert the results to full format
    --new:Results()
    return new
end

function Recipe:Results(get_expensive)
    if self:valid('recipe') then
        if get_expensive then
            self:make_difficult()
        end
        if self.normal then
            if self.normal.result then
                self.normal.results = {
                    {type = 'item', name = self.normal.result, amount = self.normal.result_count or 1}
                }
                self.normal.result = nil
                self.normal.result_count = nil
            end
            self.normal.results._owner = self
            self.normal.results._valid = 'results'
            setmetatable(self.normal.results, Recipe._results_mt)
            if self.expensive.result then
                self.expensive.results = {
                    {type = 'item', name = self.expensive.result, amount = self.expensive.result_count or 1}
                }
                self.expensive.result = nil
                self.expensive.result_count = nil
            end
            self.expensive.results._owner = self
            self.expensive.results._valid = 'results'
            setmetatable(self.expensive.results, Recipe._results_mt)
            return get_expensive and self.expensive.results or self.normal.results
        else
            if self.result then
                self.results = {
                    {type = 'item', name = self.result, amount = self.result_count or 1}
                }
                self.result = nil
                self.result_count = nil
            end
            self.results._owner = self
            self.results._valid = 'results'
            return setmetatable(self.results, Recipe._results_mt)
        end
    end
    return self
end

function Recipe:Ingredients(get_expensive)
    if self:valid('recipe') then
        if get_expensive then
            self:make_difficult()
        end
        if self.normal then
            self.normal.ingredients._owner = self
            self.normal.ingredients._valid = 'ingredients'
            setmetatable(self.normal.ingredients, Recipe._ingredients_mt)
            self.expensive.ingredients._owner = self
            self.expensive.ingredients._valid = 'ingredients'
            setmetatable(self.expensive.ingredients, Recipe._ingredients_mt)
            return get_expensive and self.expensive.ingredients or self.normal.ingredients
        else
            self.ingredients._owner = self
            self.ingredients._valid = 'ingredients'
            return setmetatable(self.ingredients, Recipe._ingredients_mt)
        end
    end
    return self
end

-- Returns a formated ingredient or prodcut table
local function format(ingredient, result_count)
    --[[
    Ingredient table
    {"name", amount} -- Assumes a type of "item"
    {
        type :: string: "item" or "fluid".
        name :: string: Prototype name of the required item or fluid.
        amount :: uint: Amount of the item.
        minimum_temperature :: uint (optional): The minimum fluid temperature required. Has no effect if type is '"item"'.
        maximum_temperature :: uint (optional): The maximum fluid temperature allowed. Has no effect if type is '"item"'.
    }

    Product table
    {
        type :: string: "item" or "fluid".
        name :: string: Prototype name of the result.
        amount :: float (optional): If not specified, amount_min, amount_max and probability must all be specified.
        temperature :: uint (optional): The fluid temperature of this product. Has no effect if type is '"item"'.
        amount_min :: uint (optional):
        amount_max :: uint (optional):
        probability :: double (optional): A value in range [0, 1].
    }
    --]]
    local object
    if type(ingredient) == 'table' then
        if ingredient.valid and ingredient:valid() then
            return ingredient
        elseif ingredient.name then
            if Item(ingredient.name, ingredient.type):valid() then
                object = table.deepcopy(ingredient)
                if not object.amount and not (object.amount_min and object.amount_max and object.probability) then
                    error('Result table requires amount or probabilities')
                end
            end
        elseif #ingredient > 0 then
            -- Can only be item types not fluid
            local item = Item(ingredient[1])
            if item:valid() and item.type ~= 'fluid' then
                object = {
                    type = 'item',
                    name = ingredient[1],
                    amount = ingredient[2] or 1
                }
            end
        end
    elseif type(ingredient) == 'string' then
        -- Our shortcut so we need to check it
        local item = Item(ingredient)
        if item:valid() then
            object = {
                type = item.type == 'fluid' and 'fluid' or 'item',
                name = ingredient,
                amount = result_count or 1
            }
        end
    end
    return object
end

-- Format items for difficulties
-- If expensive is a boolean then return a copy of normal for expensive
local function get_difficulties(normal, expensive)
    return format(normal), format((expensive == true and table.deepcopy(normal)) or expensive)
end

--- Remove an ingredient from an ingredients table.
-- @tparam table ingredients
-- @tparam string name Name of the ingredient to remove
local function remove_ingredient(ingredients, name)
    name = name.name
    for i, ingredient in pairs(ingredients) do
        if ingredient[1] == name or ingredient.name == name then
            ingredients[i] = nil
            return true
        end
    end
end

--- Replace an ingredient.
-- @tparam table ingredients Ingredients table
-- @tparam string find ingredient to replace
-- @tparam concepts.ingredient replace
-- @tparam boolean replace_name_only Don't replace amounts
local function replace_ingredient(ingredients, find, replace, replace_name_only)
    for i, ingredient in pairs(ingredients) do
        if ingredient[1] == find or ingredient.name == find then
            if replace_name_only then
                local amount = ingredient[2] or ingredient.amount
                replace.amount = amount
            end
            ingredients[i] = replace
            return true
        end
    end
end

--- Add an ingredient to a recipe.
-- @tparam string|Concepts.ingredient normal
-- @tparam[opt] string|Concepts.ingredient|boolean expensive
-- @treturn Recipe
function Recipe:add_ingredient(normal, expensive)
    if self:valid() then
        normal, expensive = get_difficulties(normal, expensive)

        if self.normal then
            if normal then
                self.normal.ingredients[#self.normal.ingredients + 1] = normal
            end
            if expensive then
                self.expensive.ingredients[#self.expensive.ingredients + 1] = expensive
            end
        elseif normal then
            self.ingredients[#self.ingredients + 1] = normal
        end
    end
    return self
end

--- Remove one ingredient completely.
-- @tparam string normal
-- @tparam string|boolean expensive expensive recipe to remove, or if true remove normal recipe from both
-- @treturn Recipe
function Recipe:remove_ingredient(normal, expensive)
    if self:valid() then
        normal, expensive = get_difficulties(normal, expensive)
        if self.normal then
            if normal then
                remove_ingredient(self.normal.ingredients, normal)
            end
            if expensive then
                remove_ingredient(self.expensive.ingredients, expensive)
            end
        elseif normal then
            remove_ingredient(self.ingredients, normal)
        end
    end
    return self
end

--- Replace one ingredient with another.
-- @tparam string replace
-- @tparam string|ingredient normal
-- @tparam[opt] string|ingredient|boolean expensive
function Recipe:replace_ingredient(replace, normal, expensive)
    Is.Assert(replace, 'Missing recipe to replace')
    if self:valid() then
        local n_string = type(normal) == 'string'
        local e_string = type(expensive == true and normal or expensive) == 'string'
        normal, expensive = get_difficulties(normal, expensive)

        if self.normal then
            if normal then
                replace_ingredient(self.normal.ingredients, replace, normal, n_string)
            end
            if expensive then
                replace_ingredient(self.expensive.ingredients, replace, expensive, e_string)
            end
        elseif normal then
            replace_ingredient(self.ingredients, replace, normal, n_string)
        end
    end
    return self
end

-- Currently does no checking
function Recipe:clear_ingredients()
    if self:valid() then
        if self.normal then
            if self.normal.ingredients then
                self.normal.ingredients = {}
            end
            if self.expensive.ingredients then
                self.expensive.ingredients = {}
            end
        elseif self.ingredients then
            self.ingredients = {}
        end
    end
    return self
end

--- Converts a recipe to the difficulty recipe format.
-- @tparam[opt] number expensive_energy crafting energy_required for the expensive recipe
-- @treturn self
function Recipe:make_difficult(expensive_energy)
    if self:valid('recipe') and not self.normal then
        --convert all ingredients
        local normal, expensive = {}, {}
        for _, ingredient in ipairs(self.ingredients) do
            local this = format(ingredient)
            normal[#normal + 1] = this
            expensive[#expensive + 1] = table.deepcopy(this)
        end

        local r_normal, r_expensive = {}, {}
        for _, ingredient in ipairs(self.results or {self.result}) do
            local this = format(ingredient)
            r_normal[#r_normal + 1] = this
            r_expensive[#r_expensive + 1] = table.deepcopy(this)
        end

        self.normal = {
            enabled = self.enabled,
            energy_required = self.energy_required,
            ingredients = normal,
            results = r_normal,
            main_product = self.main_product
        }
        self.expensive = {
            enabled = self.enabled,
            energy_required = expensive_energy or self.energy_required,
            ingredients = expensive,
            results = r_expensive,
            main_product = self.main_product
        }

        self.ingredients = nil
        self.result = nil
        self.results = nil
        self.result_count = nil
        self.energy_required = nil
        self.enabled = nil
        self.main_product = nil
    end
    return self
end

--- Change the recipe category.
-- @tparam string category_name The new crafting category
-- @treturn self
function Recipe:change_category(category_name)
    if self:valid() then
        local Category = require('stdlib/data/category')
        self.category = Category(category_name, 'recipe-category'):valid() and category_name or self.category
    end
    return self
end
Recipe.set_category = Recipe.change_category

--- Add to technology as a recipe unlock.
-- @tparam string tech_name Name of the technology to add the unlock too
-- @treturn self
function Recipe:add_unlock(tech_name)
    if self:valid() then
        local Tech = require('stdlib/data/technology')
        Tech.add_effect(self, tech_name) --self is passed as a valid recipe
    end
    return self
end

--- Remove the recipe unlock from the technology.
-- @tparam string tech_name Name of the technology to remove the unlock from
-- @treturn self
function Recipe:remove_unlock(tech_name)
    if self:valid('recipe') then
        local Tech = require('stdlib/data/technology')
        Tech.remove_effect(self, tech_name, 'unlock-recipe')
    end
    return self
end

--- Set the enabled status of the recipe.
-- @tparam boolean enabled Enable or disable the recipe
-- @treturn self
function Recipe:set_enabled(enabled)
    if self:valid() then
        if self.normal then
            self.normal.enabled = enabled
            self.expensive.enabled = enabled
        else
            self.enabled = enabled
        end
    end
    return self
end

--- Convert result type to results type.
-- @treturn self
function Recipe:convert_results()
    if self:valid('recipe') then
        if self.normal then
            if self.normal.result then
                self.normal.results = {
                    format(self.normal.result, self.normal.result_count or 1)
                }
                self.normal.result = nil
                self.normal.result_count = nil
            end
            if self.expensive.result then
                self.expensive.results = {
                    format(self.expensive.result, self.expensive.result_count or 1)
                }
                self.expensive.result = nil
                self.expensive.result_count = nil
            end
        elseif self.result then
            self.results = {
                format(self.result, self.result_count or 1)
            }
            self.result = nil
            self.result_count = nil
        end
    end
    return self
end

--- Set the main product of the recipe.
-- @tparam string|boolean main_product if boolean then use normal/expensive recipes passed as main product
-- @tparam[opt] Concepts.Product|string normal recipe
-- @tparam[opt] Concepts.Product|string expensive recipe
-- @treturn self
function Recipe:set_main_product(main_product, normal, expensive)
    if self:valid('recipe') then
        normal, expensive = get_difficulties(normal, expensive)
        local normal_main, expensive_main
        if main_product then
            if type(main_product) == 'string' and Item(main_product):valid() then
                normal_main = normal and main_product
                expensive_main = expensive and main_product
            elseif type(main_product) == 'boolean' then
                normal_main = normal and Item(normal.name):valid() and normal.name
                expensive_main = expensive and Item(expensive.name):valid() and expensive.name
            end
            if self.normal then
                self.normal.main_product = normal_main
                self.expensive.main_product = expensive_main
            else
                self.main_product = normal_main
            end
        end
    end
    return self
end

--- Remove the main product of the recipe.
-- @tparam[opt=false] boolean for_normal
-- @tparam[opt=false] boolean for_expensive
function Recipe:remove_main_product(for_normal, for_expensive)
    if self:valid('recipe') then
        if self.normal then
            if for_normal or (for_normal == nil and for_expensive == nil) then
                self.normal.main_product = nil
            end
            if for_expensive or (for_normal == nil and for_expensive == nil) then
                self.expensive.main_product = nil
            end
        elseif for_normal or (for_normal == nil and for_expensive == nil) then
            self.main_product = nil
        end
    end
    return self
end

--- Add a new product to results, converts if needed.
-- @tparam string|Concepts.product normal
-- @tparam[opt] string|Concepts.product|boolean expensive
-- @tparam[opt] string main_product
function Recipe:add_result(normal, expensive, main_product)
    if self:valid() then
        normal, expensive = get_difficulties(normal, expensive)
        self:convert_results()
        self:set_main_product(main_product, normal, expensive)

    -- if self.normal then
    --     if normal then
    --     end
    --     if expensive then
    --     end
    -- elseif normal then
    -- end
    end
    return self
end

--- Remove a product from results, converts if needed.
-- @tparam[opt] string|Concepts.product normal
-- @tparam[opt] string|Concepts.product|boolean expensive
-- @tparam[opt] string main_product new main_product to use
function Recipe:remove_result(normal, expensive, main_product)
    if self:valid() then
        normal, expensive = get_difficulties(normal, expensive)
        self:convert_results()
        self:set_main_product(main_product, normal, expensive)

    -- if self.normal then
    --     if normal then
    --     end
    --     if expensive then
    --     end
    -- elseif normal then
    -- end
    end
    return self
end

--- Remove a product from results, converts if needed.
-- @tparam string|Concepts.product result_name
-- @tparam[opt] string|Concepts.product normal
-- @tparam[opt] string|Concepts.product|boolean expensive
-- @tparam[opt] string main_product
function Recipe:replace_result(result_name, normal, expensive, main_product)
    if self:valid() and normal or expensive then
        result_name = format(result_name)
        if result_name then
            normal, expensive = get_difficulties(normal, expensive)
            self:convert_results()
            self:remove_result(result_name, expensive and result_name)
            self:set_main_product(main_product, normal, expensive)

        -- if self.normal then
        --     if normal then
        --     end
        --     if expensive then
        --     end
        -- elseif normal then
        -- end
        end
    end
    return self
end

Recipe.rep_ing = Recipe.replace_ingredient
Recipe.add_ing = Recipe.add_ingredient
Recipe.rem_ing = Recipe.remove_ingredient

Recipe._mt = {
    __index = Recipe,
    __call = Recipe._caller,
    __tostring = Recipe.tostring
}

return Recipe


text:
NSString *const GNOAuth2ClientID = @"something.apps.googleusercontent.com";
NSString *const GNOAuth2ClientSecret = @"troLOLOloloLOLOl0l";


text:
puissance4
==========

Puissance4


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#include "config.h"
#include "PositionOptions.h"

namespace blink {

PositionOptions::PositionOptions()
{
    setEnableHighAccuracy(false);
    setMaximumAge(0u);
    setTimeout(4294967295u);
}

DEFINE_TRACE(PositionOptions)
{
}

} // namespace blink


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

namespace GreatQuotes.Data
{
    public class QuoteManager
    {

        static readonly Lazy<QuoteManager> _instance = new Lazy<QuoteManager>(() => new QuoteManager());
        public static QuoteManager Instance { get { return _instance.Value; } }

        readonly IQuoteLoader _repo;
        public IList<GreatQuote> Quotes { get; private set; }

        // the constructor is private because we're using the singleton pattern
        private QuoteManager()
        {
            _repo = QuoteLoaderFactory.Create();
            Quotes = new ObservableCollection<GreatQuote>(_repo.Load());
        }

        public void Save()
        {
            _repo.Save(Quotes);
        }

        public void SayQuote(GreatQuote quote)
        {
            if (quote == null)
                throw new ArgumentException("Quote is Null (TextToSpeech)");

            var textToSpeechService = ServiceLocator.Instance.Resolve<ITextToSpeech>();

            if (textToSpeechService != null)
            {
                string text = quote.QuoteText;

                if (!string.IsNullOrEmpty(quote.Author))
                    text += $" by {quote.Author}";

                textToSpeechService.Speak(text);
            }
        }

    }
}


text:
// Most of the following code has been 'borrowed' from
// Robert Escriva's HyperDex coordinator.
// see https://github.com/rescrv/HyperDex for the original code.

#ifndef weaver_server_manager_server_manager_h_
#define weaver_server_manager_server_manager_h_

// c++
#include <memory>

// po6
#include <po6/net/location.h>

// Replicant
#include <rsm.h>

// Weaver
#include "common/ids.h"
#include "common/server.h"
#include "coordinator/server_barrier.h"

namespace coordinator
{

class server_manager
{
    public:
        server_manager();
        ~server_manager() throw ();

    // identity
    public:
        void init(rsm_context* ctx, uint64_t token);
        uint64_t cluster() const { return m_cluster; }

    // server management
    public:
        void server_register(rsm_context* ctx,
                             const server_id& sid,
                             const po6::net::location& bind_to,
                             server::type_t type);
        void server_online(rsm_context* ctx,
                           const server_id& sid,
                           const po6::net::location* bind_to);
        void server_offline(rsm_context* ctx,
                            const server_id& sid);
        void server_shutdown(rsm_context* ctx,
                             const server_id& sid);
        void server_kill(rsm_context* ctx,
                         const server_id& sid);
        void server_forget(rsm_context* ctx,
                           const server_id& sid);
        void server_suspect(rsm_context* ctx,
                            const server_id& sid);
        void report_disconnect(rsm_context* ctx,
                               const server_id& sid, uint64_t version);

    private:
        void check_backup(rsm_context *ctx, server *new_srv);
        void find_backup(rsm_context *ctx, server::type_t type, uint64_t vid);
        void activate_backup(server *backup_srv, server::type_t type, uint64_t vid);

    // config management
    public:
        void config_get(rsm_context* ctx);
        void config_ack(rsm_context* ctx,
                        const server_id& sid, uint64_t version);
        void config_stable(rsm_context* ctx,
                           const server_id& sid, uint64_t version);

    // debug
    public:
        void debug_dump(rsm_context* ctx);

    // backup/restore
    public:
        static server_manager* recreate(rsm_context* ctx,
                                        const char* data, size_t data_sz);
        int snapshot(rsm_context* ctx,
                     char** data, size_t* data_sz);

    // utilities
    private:
        // servers
        server* new_server(const server_id& sid);
        server* get_server(const server_id& sid);
        // configuration
        void check_ack_condition(rsm_context* ctx);
        void check_stable_condition(rsm_context* ctx);
        void generate_next_configuration(rsm_context* ctx);
        void generate_cached_configuration(rsm_context* ctx);
        void servers_in_configuration(std::vector<server_id>* sids);

    private:
        // meta state
        uint64_t m_cluster;
        uint64_t m_counter;
        uint64_t m_version;
        uint64_t m_flags;
        uint64_t m_num_shards;
        uint64_t m_num_vts;
        uint64_t m_num_weaver;
        // servers
        std::vector<server> m_servers;
        // barriers
        uint64_t m_config_ack_through;
        server_barrier m_config_ack_barrier;
        uint64_t m_config_stable_through;
        server_barrier m_config_stable_barrier;
        // cached config
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
        std::auto_ptr<e::buffer> m_latest_config;
#pragma GCC diagnostic pop
        // for returning client id
        std::unique_ptr<e::buffer> m_response;

    private:
        server_manager(const server_manager&);
        server_manager& operator = (const server_manager&);
};

}

#endif


text:
require 'spec_helper'

describe Html::Pipeline::Hashtag do
  describe '.hashtags_in' do
    def extract_hashtags(text, context = {})
      tags = []

      filters = [
        HTML::Pipeline::MarkdownFilter,
        HTML::Pipeline::HashtagFilter
      ]

      pipeline = HTML::Pipeline.new filters
      result = pipeline.call text, context

      result[:hashtags]
    end

    context "extracts latin/numeric hashtags" do
      %w(text text123 123text).each do |hashtag|
        it "should extract ##{hashtag}" do
          expect( extract_hashtags("##{hashtag}") ).to eq([hashtag])
        end

          it "should extract ##{hashtag} within text" do
            expect( extract_hashtags("pre-text ##{hashtag} post-text") ).to eq([hashtag])
          end
      end
    end

    context "international hashtags" do
      context "should allow accents" do
        %w(Россия mañana café münchen).each do |hashtag|
          it "should extract ##{hashtag}" do
            expect( extract_hashtags("##{hashtag}") ).to eq([hashtag])
          end

          it "should extract ##{hashtag} within text" do
            expect( extract_hashtags("pre-text ##{hashtag} post-text") ).to eq([hashtag])
          end
        end
      end
    end

    it 'should extract hashtag followed by punctuations' do
      expect( extract_hashtags("#test1: #test2; #test3\"") ).to eq(["test1", "test2" ,"test3"])
    end

    context "custom hashtag pattern" do
      let(:custom_pattern) { /#([\p{L}\w\-]{5})/ }

      it "should extract hashtag length of 5 characters" do
        valid_tag = "world"
        invalid_tag = "WWW"

        expect(
          extract_hashtags("Hello ##{valid_tag}! ##{invalid_tag}", hashtag_pattern: custom_pattern)
        ).to eq([valid_tag])
      end
    end
  end

  describe '.call' do
    def filter(html, context = {})
      filters = [
        HTML::Pipeline::HashtagFilter
      ]

      pipeline = HTML::Pipeline.new filters
      pipeline.call(html, context)
    end

    def doc(html, context = {})
      filter(html, context)[:output]
    end

    context "should filtering plain text" do
      let(:tag) { 'world' }
      let(:html) { "
Hello ##{tag}!
" }

      [
        ['default', nil], ['custom', "/tags/%{tag}"]
      ].each do |title, tag_url|

        it "should filtering plain text with #{title} context" do
          url = (tag_url || "/tags/%{tag}") % { tag: tag }

          expect(url).to eq doc(html).search('a').attr('href').value
        end
      end
    end

    context 'should not replacing hashtag in' do
      it "links and styles" do
        html = 'Hello #magic #world!'
        expect( doc(html).search('a').count ).to eq(1)
      end

      it "code-tags" do
        html = 'Hello #magic #world!'
        expect( doc(html).search('a') ).to be_empty
      end

      it 'pre-tags' do
        html = '
Hello #magic #world!
'
        expect( doc(html).search('a') ).to be_empty
      end
    end
  end
end


text:
<?php

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Kind_EventEntry
 */
require_once 'Zend/Gdata/Kind/EventEntry.php';

/**
 * @see Zend_Gdata_Calendar_Extension_SendEventNotifications
 */
require_once 'Zend/Gdata/Calendar/Extension/SendEventNotifications.php';

/**
 * @see Zend_Gdata_Calendar_Extension_Timezone
 */
require_once 'Zend/Gdata/Calendar/Extension/Timezone.php';

/**
 * @see Zend_Gdata_Calendar_Extension_Link
 */
require_once 'Zend/Gdata/Calendar/Extension/Link.php';

/**
 * @see Zend_Gdata_Calendar_Extension_QuickAdd
 */
require_once 'Zend/Gdata/Calendar/Extension/QuickAdd.php';

/**
 * Data model class for a Google Calendar Event Entry
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_EventEntry extends Zend_Gdata_Kind_EventEntry
{

    protected $_entryClassName = 'Zend_Gdata_Calendar_EventEntry';
    protected $_sendEventNotifications = null;
    protected $_timezone = null;
    protected $_quickadd = null;

    public function __construct($element = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct($element);
    }

    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_sendEventNotifications != null) {
            $element->appendChild($this->_sendEventNotifications->getDOM($element->ownerDocument));
        }
        if ($this->_timezone != null) {
            $element->appendChild($this->_timezone->getDOM($element->ownerDocument));
        }
        if ($this->_quickadd != null) {
            $element->appendChild($this->_quickadd->getDOM($element->ownerDocument));
        }
        return $element;
    }

    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;

        switch ($absoluteNodeName) {
            case $this->lookupNamespace('gCal') . ':' . 'sendEventNotifications';
                $sendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications();
                $sendEventNotifications->transferFromDOM($child);
                $this->_sendEventNotifications = $sendEventNotifications;
                break;
            case $this->lookupNamespace('gCal') . ':' . 'timezone';
                $timezone = new Zend_Gdata_Calendar_Extension_Timezone();
                $timezone->transferFromDOM($child);
                $this->_timezone = $timezone;
                break;
            case $this->lookupNamespace('atom') . ':' . 'link';
                $link = new Zend_Gdata_Calendar_Extension_Link();
                $link->transferFromDOM($child);
                $this->_link[] = $link;
                break;
            case $this->lookupNamespace('gCal') . ':' . 'quickadd';
                $quickadd = new Zend_Gdata_Calendar_Extension_QuickAdd();
                $quickadd->transferFromDOM($child);
                $this->_quickadd = $quickadd;
                break;
            default:
                parent::takeChildFromDOM($child);
                break;
        }
    }

    public function getSendEventNotifications()
    {
        return $this->_sendEventNotifications;
    }

    public function setSendEventNotifications($value)
    {
        $this->_sendEventNotifications = $value;
        return $this;
    }

    public function getTimezone()
    {
        return $this->_timezone;
    }

    /**
     * @param Zend_Gdata_Calendar_Extension_Timezone $value
     * @return Zend_Gdata_Extension_EventEntry Provides a fluent interface
     */
    public function setTimezone($value)
    {
        $this->_timezone = $value;
        return $this;
    }

    public function getQuickAdd()
    {
        return $this->_quickadd;
    }

    /**
     * @param Zend_Gdata_Calendar_Extension_QuickAdd $value
     * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface
     */
    public function setQuickAdd($value)
    {
        $this->_quickadd = $value;
        return $this;
    }

}


text:
title: Use the flex-direction Property to Make a Column
localeTitle: Use a propriedade flex-direction para criar uma coluna
---
## Use a propriedade flex-direction para criar uma coluna

Para empilhar os elementos filhos do seu contêiner flexível um sobre o outro, você mudaria a _direção flexionada_ da seguinte maneira:

```CSS
#main-container {
    display: flex;
    flex-direction: column;
 }

```


text:
"""
▀████▀███▄   ▀███▀▄█▀▀▀█▄███▀▀██▀▀███     ██     ▀███▄   ▀███▀     ██
  ██   ███▄    █ ▄██    ▀█▀   ██   ▀█    ▄██▄      ███▄    █      ▄██▄
  ██   █ ███   █ ▀███▄        ██        ▄█▀██▄     █ ███   █     ▄█▀██▄
  ██   █  ▀██▄ █   ▀█████▄    ██       ▄█  ▀██     █  ▀██▄ █    ▄█  ▀██
  ██   █   ▀██▄█ ▄     ▀██    ██       ████████    █   ▀██▄█    ████████
  ██   █     ███ ██     ██    ██      █▀      ██   █     ███   █▀      ██
▄████▄███▄    ██ █▀█████▀   ▄████▄  ▄███▄   ▄████▄███▄    ██ ▄███▄   ▄████▄

https://www.instana.com/

Documentation: https://www.instana.com/docs/
Source Code: https://github.com/instana/python-sensor
"""

from __future__ import absolute_import

import os
import sys
import importlib
from threading import Timer
import pkg_resources

from .version import VERSION

__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2020 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo', 'Andrey Slotin']
__license__ = 'MIT'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
__version__ = VERSION

# User configurable EUM API key for instana.helpers.eum_snippet()
# pylint: disable=invalid-name
eum_api_key = ''

# This Python package can be loaded into Python processes one of three ways:
#   1. manual import statement
#   2. autowrapt hook
#   3. dynamically injected remotely
#
# With such magic, we may get pulled into Python processes that we have no interest being in.
# As a safety measure, we maintain a "do not load list" and if this process matches something
# in that list, then we go sit in a corner quietly and don't load anything at all.
do_not_load_list = ["pip", "pip2", "pip3", "pipenv", "docker-compose", "easy_install", "easy_install-2.7",
                    "smtpd.py", "twine", "ufw", "unattended-upgrade"]

def load(_):
    """
    Method used to activate the Instana sensor via AUTOWRAPT_BOOTSTRAP
    environment variable.
    """
    # Work around https://bugs.python.org/issue32573
    if not hasattr(sys, "argv"):
        sys.argv = ['']
    return None

def get_lambda_handler_or_default():
    """
    For instrumenting AWS Lambda, users specify their original lambda handler in the LAMBDA_HANDLER environment
    variable.  This function searches for and parses that environment variable or returns the defaults.

    The default handler value for AWS Lambda is 'lambda_function.lambda_handler' which
    equates to the function "lambda_handler in a file named "lambda_function.py" or in Python
    terms "from lambda_function import lambda_handler"
    """
    handler_module = "lambda_function"
    handler_function = "lambda_handler"

    try:
        handler = os.environ.get("LAMBDA_HANDLER", False)

        if handler:
            parts = handler.split(".")
            handler_function = parts.pop().strip()
            handler_module = ".".join(parts).strip()
    except Exception:
        pass

    return handler_module, handler_function

def lambda_handler(event, context):
    """
    Entry point for AWS Lambda monitoring.

    This function will trigger the initialization of Instana monitoring and then call
    the original user specified lambda handler function.
    """
    module_name, function_name = get_lambda_handler_or_default()

    try:
        # Import the module specified in module_name
        handler_module = importlib.import_module(module_name)
    except ImportError:
        print("Couldn't determine and locate default module handler: %s.%s" % (module_name, function_name))
    else:
        # Now get the function and execute it
        if hasattr(handler_module, function_name):
            handler_function = getattr(handler_module, function_name)
            return handler_function(event, context)
        else:
            print("Couldn't determine and locate default function handler: %s.%s" % (module_name, function_name))

def boot_agent():
    """Initialize the Instana agent and conditionally load auto-instrumentation."""
    # Disable all the unused-import violations in this function
    # pylint: disable=unused-import
    # pylint: disable=import-outside-toplevel

    import instana.singletons

    # Instrumentation
    if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
        # Import & initialize instrumentation
        from .instrumentation.aws import lambda_inst

        from .instrumentation import sanic_inst

        from .instrumentation import fastapi_inst
        from .instrumentation import starlette_inst

        from .instrumentation import asyncio
        from .instrumentation.aiohttp import client
        from .instrumentation.aiohttp import server
        from .instrumentation import boto3_inst

        from .instrumentation import mysqlclient

        from .instrumentation.google.cloud import storage
        from .instrumentation.google.cloud import pubsub

        from .instrumentation.celery import hooks

        from .instrumentation import cassandra_inst
        from .instrumentation import couchbase_inst
        from .instrumentation import flask
        from .instrumentation import gevent_inst
        from .instrumentation import grpcio
        from .instrumentation.tornado import client
        from .instrumentation.tornado import server
        from .instrumentation import logging
        from .instrumentation import pika
        from .instrumentation import pymysql
        from .instrumentation import psycopg2
        from .instrumentation import redis
        from .instrumentation import sqlalchemy
        from .instrumentation import urllib3
        from .instrumentation.django import middleware
        from .instrumentation import pymongo

    # Hooks
    from .hooks import hook_uwsgi

if 'INSTANA_DISABLE' not in os.environ:
    # There are cases when sys.argv may not be defined at load time.  Seems to happen in embedded Python,
    # and some Pipenv installs.  If this is the case, it's best effort.
    if hasattr(sys, 'argv') and len(sys.argv) > 0 and (os.path.basename(sys.argv[0]) in do_not_load_list):
        if "INSTANA_DEBUG" in os.environ:
            print("Instana: No use in monitoring this process type (%s).  "
                  "Will go sit in a corner quietly." % os.path.basename(sys.argv[0]))
    else:
        # AutoProfile
        if "INSTANA_AUTOPROFILE" in os.environ:
            from .singletons import get_profiler

            profiler = get_profiler()
            if profiler:
                profiler.start()

        boot_agent()


text:
using Foundation;
using System;
using UIKit;

namespace Shopping.DemoApp.iOS.Chunha.QLTC
{
    public partial class LSTTDetailViewController : UIViewController
    {
        public LSTTDetailViewController (IntPtr handle) : base (handle)
        {
        }

		public Product Item { get; set; }
		//public MasterViewController Delegate { get; set; } // will be used to Save, Delete later

		public override void ViewWillAppear(bool animated)
		{
			base.ViewWillAppear(animated);
			uxNgayThang.Text = Item.Name;
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();

		}

	}
}


text:
<?php
namespace tests\unit\fixtures\common\models;

use Sil\yii\test\ActiveFixture;

class UserFixture extends ActiveFixture
{
    public $modelClass = 'common\models\User';
    public $dataFile = 'tests/unit/fixtures/data/common/models/User.php';
    public $depends = [
    ];
}


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"github.com/bellycard/procd/resources"
	"github.com/bellycard/toml"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

type procdConfig struct {
	TickerInterval int               `toml:"ticker_interval"`
	Outputs        map[string]output `toml:"output"`
}

type output struct {
	BindAddress string `toml:"bind_address"`
	Server      string
	Encoder     string
	Sender      string
	Payload     bool
	Hostname    string
}

func waitForSignals(exitStatus <-chan bool) {
	signalChan := make(chan os.Signal)
	signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT, os.Kill)
	for {
		s := <-signalChan
		switch s {
		case syscall.SIGINT, syscall.SIGTERM, os.Kill:
			fmt.Println("Procd: Shutdown initiated.")
			os.Exit(0)
		}
	}
}

func main() {
	flagVersion := flag.Bool("version", false, "Display Procd version.")
	flagConfigFile := flag.String("config", "procd.toml", "Procd configuration file.")
	flag.Parse()

	runtime.GOMAXPROCS(runtime.NumCPU())

	// Handle no command-line paramters
	if flag.NFlag() == 0 {
		flag.PrintDefaults()
		os.Exit(0)
	}

	// Display Procd version
	if *flagVersion {
		fmt.Println("Procd v", Version)
		os.Exit(0)
	}

	// Decode configuration [https://github.com/mojombo/toml]
	var config procdConfig
	_, err := toml.DecodeFile(*flagConfigFile, &config)
	verifyErrorResponse(err, "could not decode TOML config")

	// Setup output channels
	for outputName, output := range config.Outputs {
		switch outputName {
		case "stdout":
			fmt.Printf("\nProcd: Output[stdout]\n")
		case "http":
			go HTTPServerStart(output.BindAddress)
			fmt.Printf("Procd: Output[http]: %s\n", output.BindAddress)
		case "heka":
			fmt.Printf("Procd: Output[heka]: %s [%s / Protobufs]\n", output.Server, output.Sender)
		}
	}

	// Timing channels for polling interval
	collectionInterval := time.NewTicker(time.Second * time.Duration(config.TickerInterval))

	collection := resources.NewCollection()
	// Update statistics on interval until sigterm
	go func() {
		for _ = range collectionInterval.C {
			collection.CollectAllMetrics()
			for outputName, output := range config.Outputs {
				switch outputName {
				case "stdout":
					marshalledResources, _ := json.MarshalIndent(collection, "", " ")
					fmt.Println(string(marshalledResources))
				case "heka":
					hc, err := NewHekaClient(output.Server, output.Sender, output.Hostname)
					if err == nil {
						err := hc.SendCPUResources(collection, output.Payload)
						verifyErrorResponse(err, "generate CPU resources Heka message")
						err = hc.SendMemoryResources(collection, output.Payload)
						verifyErrorResponse(err, "generate memory resources Heka message")
						err = hc.SendDiskResources(collection, output.Payload)
						verifyErrorResponse(err, "generate disk resources Heka message")
						hc.sender.Close()
					}
				}
			}
		}
	}()

	fmt.Printf("Procd: Collection interval: %v seconds\n", config.TickerInterval)
	exitStatus := make(chan bool, 1)
	fmt.Println("Procd: Started.")
	waitForSignals(exitStatus)
}


text:
function ecog=ecogImagescTS(ecog, timepoint,colorLim, nColumns)
% ecog=ecogImagescTS(ecog, trialList) an image of the time series amplitudes on the grid
%
% Purpose:  Plot an image of the time series amplitudes on the grid.
%           Channel positions:
%           Electrode positions are expected in ecog.channelPosition. in
%           the order x,y)
%           If this field does not exist the field channel2GridMatrixIdx is
%           used to construct the layout of the electrode grid.
%           If channel2GridMatrixIdx does not exist the variable nColumns
%           must be passed and grid positions for a rectangular grid are
%           constructed. %
% INPUT:
% ecog:      an ecog structure
% timepoint: The timepoint to plot (same unit as in ecog.timebase)
% colorLim:  OPTIONAL: Limits of the colormap. Each plot will be scaled
%            individually if not passed or empty.
% nColumns:  OPTIONAL: The number of columns in the plot matrix.
%            used MANDATORY if neither of the fields channelPosition
%            or channel2GridMatrixIdx exist.
%
% OUTPUT:
% ecog:     Returns the ecog structure.
%           If nColumns was provided the fields channelPosition and
%           channel2GridMatrixIdx are updated
% TODO: extend to 3D,
%       delete triangles containing deselected channels instead of setting
%       them to zero
%       optional transparent figure background
%

% 091106 JR wrote it
% ecogMovieTS depends on this function

%this will override any previous position definitions
if nargin>3 && ~isempty(nColumns)
    nRows=ceil(size(ecog.data,1)/nColumns);
    [channel2SubplotX, channel2SubplotY] = meshgrid([1:nColumns],[1:nRows]); % We work in cartesian coordinates on this
    %This is how we will index the subplots in the matrix of plots
    ecog.channel2GridMatrixIdx=[channel2SubplotX(1:size(ecog.data,1))' channel2SubplotY(1:size(ecog.data,1))'];
    ecog.channelPosition=ecog.channel2GridMatrixIdx;
end
%If still no positions are available try those used for grid plots
if isfield(ecog,'channel2GridMatrixIdx') && ~isfield(ecog,'channelPosition')
    ecog.channelPosition=ecog.channel2GridMatrixIdx;
elseif ~isfield(ecog,'channelPosition')
    error('no channelPosition in ecog structure.')
end

timeIdx=nearly(timepoint,ecog.timebase);
% We use a Delaunay trangulation to construct the surface
tri = delaunay(ecog.channelPosition(:,2),ecog.channelPosition(:,1));
%and plot it
colorVals=zeros(size(ecog.channelPosition,1),1);
if exist('colorLim')
    clFixed=1;
    cl=colorLim;
else
    clFixed=0;
end
set(gcf,'color','w')
colorVals(ecog.selectedChannels)=ecog.data(ecog.selectedChannels,timeIdx);
if ~clFixed
    cl=max(abs(colorVals));
    cl=[-cl cl];
end
pH=trisurf(tri,ecog.channelPosition(:,2),ecog.channelPosition(:,1),colorVals);
set(gca,'clim',cl,'zlim',cl,'box','off','gridlinestyle','none','color','none','linewidth',1,'fontweight','bold');
%axis('tight','equal','off')
axis on
axis tight
alphamap('vdown')
set(pH,'FaceAlpha','interp','AlphaDataMapping','scaled','FaceVertexAlphaData',colorVals);
view([0 -90])
%view([114 60])
set(gca,'zlim',cl)

shading interp
colorVals(:)=0;
tmp=get(gca,'xlim');
textPos(1)=tmp(1);
tmp=get(gca,'ylim');
textPos(2)=tmp(2);
tH=text(textPos(1),textPos(1),0,[num2str(timepoint) ' ms'],'VerticalAlignment','top','fontweight','bold');
colorbar


text:
<map>
  <entry>
    <string>plugin_status</string>
    <string>ready</string>
  </entry>
  <entry>
    <string>plugin_identifier</string>
    <string>org.lockss.plugin.sage.SageTriggeredContentPlugin</string>
  </entry>
  <entry>
    <string>plugin_version</string>
    <string>1</string>
  </entry>
  <entry>
    <string>au_name</string>
    <string>"Sage Triggered Content Plugin, Base URL %s, Journal Abbreviation %s, Volume %s", base_url, journal_dir, volume_name</string>
  </entry>
  <entry>
    <string>plugin_name</string>
    <string>Sage Triggered Content Plugin</string>
  </entry>
  <entry>
    <string>au_def_new_content_crawl</string>
    <long>1209600000</long>
  </entry>
  <entry>
    <string>au_crawlrules</string>
    <list>
      <string>1,"^https?://(%s|%s)/.*\.(bmp|css|gif|ico|jpe?g|js|png|tif?f)(_v[0-9]+)?$", base_url, base_url2</string>
      <string>1,"%s%s_[0-9]{4}_%s", base_url, journal_dir, volume_name</string>
      <string>2,"^(%s|%s)page", base_url, base_url2</string>
    </list>
  </entry>
  <entry>
    <string>au_start_url</string>
    <string>"%s", base_url2</string>
  </entry>
  <entry>
    <string>au_manifest</string>
      <list>
        <string>"%s", base_url2</string>
      </list>
  </entry>
  <entry>
    <string>au_feature_urls</string>
    <map>
      <entry>
        <string>au_title</string>
        <string>"%s", base_url</string>
      </entry>
    </map>
  </entry>
  <entry>
    <string>au_def_pause_time</string>
    <long>6000</long>
  </entry>
  <entry>
    <string>plugin_article_iterator_factory</string>
    <string>org.lockss.plugin.sage.SageTriggeredContentArticleIteratorFactory</string>
  </entry>
  <entry>
    <string>plugin_article_metadata_extractor_factory</string>
    <string>org.lockss.plugin.sage.SageTriggeredContentArticleIteratorFactory</string>
  </entry>
  <entry>
    <string>application/xml_metadata_extractor_factory_map</string>
    <map>
      <entry>
        <string>*</string>
        <string>org.lockss.plugin.sage.SageTriggeredContentMetadataExtractorFactory</string>
      </entry>
    </map>
  </entry>
  <entry>
    <string>plugin_config_props</string>
    <list>
      <org.lockss.daemon.ConfigParamDescr>
        <key>journal_dir</key>
        <displayName>Journal Abbreviation</displayName>
        <description>Identifier for journal</description>
        <type>1</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url</key>
        <displayName>Base URL</displayName>
        <description>Usually of the form http://<journal-name>.com/</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url2</key>
        <displayName>Second Base URL</displayName>
        <description>Usually of the form http://<journal-name>.com/</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>volume_name</key>
        <displayName>Volume Descriptor (Year or Number)</displayName>
        <type>1</type>
        <size>20</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
    </list>
  </entry>
</map>


text:
/* */
"format register";
"use strict";

var _prototypeProperties = function (child, staticProps, instanceProps) {
  if (staticProps) Object.defineProperties(child, staticProps);
  if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
};

var DirtyChecker = (function () {
  function DirtyChecker() {
    this.tracked = [];
    this.checkDelay = 120;
  }

  _prototypeProperties(DirtyChecker, null, {
    addProperty: {
      value: function addProperty(property) {
        var tracked = this.tracked;

        tracked.push(property);

        if (tracked.length === 1) {
          this.scheduleDirtyCheck();
        }
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    removeProperty: {
      value: function removeProperty(property) {
        var tracked = this.tracked;
        tracked.splice(tracked.indexOf(property), 1);
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    scheduleDirtyCheck: {
      value: function scheduleDirtyCheck() {
        var _this = this;
        setTimeout(function () {
          return _this.check();
        }, this.checkDelay);
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    check: {
      value: function check() {
        var tracked = this.tracked,
            i = tracked.length;

        while (i--) {
          var current = tracked[i];

          if (current.isDirty()) {
            current.call();
          }
        }

        if (tracked.length) {
          this.scheduleDirtyCheck();
        }
      },
      writable: true,
      enumerable: true,
      configurable: true
    }
  });

  return DirtyChecker;
})();

exports.DirtyChecker = DirtyChecker;
var DirtyCheckProperty = (function () {
  function DirtyCheckProperty(dirtyChecker, obj, propertyName) {
    this.dirtyChecker = dirtyChecker;
    this.obj = obj;
    this.propertyName = propertyName;
    this.callbacks = [];
    this.isSVG = obj instanceof SVGElement;
  }

  _prototypeProperties(DirtyCheckProperty, null, {
    getValue: {
      value: function getValue() {
        return this.obj[this.propertyName];
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    setValue: {
      value: function setValue(newValue) {
        if (this.isSVG) {
          this.obj.setAttributeNS(null, this.propertyName, newValue);
        } else {
          this.obj[this.propertyName] = newValue;
        }
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    call: {
      value: function call() {
        var callbacks = this.callbacks,
            i = callbacks.length,
            oldValue = this.oldValue,
            newValue = this.getValue();

        while (i--) {
          callbacks[i](newValue, oldValue);
        }

        this.oldValue = newValue;
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    isDirty: {
      value: function isDirty() {
        return this.oldValue !== this.getValue();
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    beginTracking: {
      value: function beginTracking() {
        this.tracking = true;
        this.oldValue = this.newValue = this.getValue();
        this.dirtyChecker.addProperty(this);
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    endTracking: {
      value: function endTracking() {
        this.tracking = false;
        this.dirtyChecker.removeProperty(this);
      },
      writable: true,
      enumerable: true,
      configurable: true
    },
    subscribe: {
      value: function subscribe(callback) {
        var callbacks = this.callbacks,
            that = this;

        callbacks.push(callback);

        if (!this.tracking) {
          this.beginTracking();
        }

        return function () {
          callbacks.splice(callbacks.indexOf(callback), 1);
          if (callbacks.length === 0) {
            that.endTracking();
          }
        };
      },
      writable: true,
      enumerable: true,
      configurable: true
    }
  });

  return DirtyCheckProperty;
})();

exports.DirtyCheckProperty = DirtyCheckProperty;


text:
var http = require("http");
var options = {
  hostname: '192.168.22.66',
  port: 8888,
  path: '/',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CentrePoint
{
    class Program
    {
        static double CalculateDistanceFromCentre(double x, double y)
        {
            double distance = 0.0;
            distance = Math.Sqrt(x*x + y*y);
            return distance;
        }

        static void PrintPointClosestToCentre(double x1, double y1, double x2, double y2)
        {
            double firstDistance = CalculateDistanceFromCentre(x1, y1);
            double secondDistance = CalculateDistanceFromCentre(x2, y2);

            if(firstDistance < secondDistance)
            {
                Console.WriteLine("({0}, {1})" ,x1,y1);
            }
            else if(secondDistance < firstDistance)
            {
                Console.WriteLine("({0}, {1})", x2, y2);
            }
            else
            {
                Console.WriteLine("({0}, {1})", x1, y1);
            }
        }

        static void Main(string[] args)
        {
            double x1 = double.Parse(Console.ReadLine());
            double y1 = double.Parse(Console.ReadLine());
            double x2 = double.Parse(Console.ReadLine());
            double y2 = double.Parse(Console.ReadLine());

            PrintPointClosestToCentre(x1,y1,x2,y2);

            String stopTheConsole = Console.ReadLine();
        }
    }
}


text:
[Join the new google group](http://groups.google.com/group/servicestack) or
follow [@demisbellot](http://twitter.com/demisbellot) and [@boxerab](http://twitter.com/boxerab)
for twitter updates.

# An Open Source C# Client for Redis

[Redis](http://code.google.com/p/redis/) is one of the fastest and feature-rich key-value stores to come from the [NoSQL](http://en.wikipedia.org/wiki/NoSQL) movement.
It is similar to memcached but the dataset is not volatile, and values can either be strings lists, sets, sorted sets or hashes.

[ServiceStack's C# Redis Client](~/redis-client/redis-client) is an Open Source C# Redis client based on [Miguel de Icaza](http://twitter.com/migueldeicaza) previous efforts with [redis-sharp](http://github.com/migueldeicaza/redis-sharp).

There are a number of different APIs available which are all a friendly drop-in with your local IOC:
The `ServiceStack.Redis.RedisClient` class below implements the following interfaces:

 * [ICacheClient](~/framework/caching-options) - If you are using Redis solely as a cache, you should bind to the [ServiceStack's common interface](~/framework/caching-options) as there already are In-Memory an Memcached implementations available in ServiceStack, allowing you to easily switch providers in-future.
 * [IRedisNativeClient](~/redis-client/iredisnativeclient-api) - For those wanting a low-level raw byte access (where you can control your own serialization/deserialization) that map 1:1 with Redis operations of the same name.

For most cases if you require access to Redis-specific functionality you would want to bind to the interface below:

  * [IRedisClient](~/redis-client/iredisclient-api) - Provides a friendlier, more descriptive API that lets you store values as strings (UTF8 encoding).
  * [IRedisTypedClient](~/redis-client/iredistypedclient-api) - created with `IRedisClient.GetTypedClient<T>()` - it returns a 'strongly-typed client' that provides a typed-interface for all redis value operations that works against any C#/.NET POCO type.

The class heirachy for the C# Redis clients effectively look like:

    RedisTypedClient (POCO) > RedisClient (string) > RedisNativeClient (raw byte[])

Each client is optimized for maximum efficiency and provides layered functionality for maximum developer productivity:

  * The RedisNativeClient exposes raw **byte[]** apis and does no marshalling and passes all values directly to redis.
  * The RedisClient assumes **string** values and simply converts strings to UTF8 bytes before sending to Redis
  * The RedisTypedClient provides a generic interface allowing you to add POCO values. The POCO types are serialized using [.NETs fastest JSON Serializer](http://www.servicestack.net/mythz_blog/?p=344) which is then converted to UTF8 bytes and sent to Redis.

At all times you can pick the most optimal Redis Client for your needs so you can achieve maximum efficiency in your applications.

### Redis Client API Overview
[![Redis Client API](http://servicestack.net/img/Redis-annotated-preview.png)](http://servicestack.net/img/Redis-annotated.png)

### Thread-safe client managers
For multi-threaded applications you can choose from our different client connection managers:

  * BasicRedisClientManager - a load-balance (master-write and read-slaves) client manager that returns a new [IRedisClient](~/redis-client/iredisclient-api) connection with the defaults specified (faster when accessing a redis-server instance on the same host).
  * PooledRedisClientManager - a load-balanced (master-write and read-slaves) client manager that utilizes a pool of redis client connections (faster when accessing a redis-server instance over the network).

# Download

You can download the Redis Client in any one of the following ways:

* Packaged by default in [ServiceStack.dll](https://github.com/ServiceStack/ServiceStack/downloads)
* Available to download separately as a stand-alone [ServiceStack.Redis.dll](https://github.com/ServiceStack/ServiceStack.Redis/downloads)
* As Source Code via Git: `git clone git://github.com/ServiceStack/ServiceStack.Redis.git`
* For those interested in having a GUI admin tool to visualize your Redis data should check out the [Redis Admin UI](http://www.servicestack.net/mythz_blog/?p=381)

[View the release notes](https://github.com/ServiceStack/ServiceStack.Redis/wiki/Redis-Client-Release-Notes).

### Redis Server builds for Windows

  * [Downloads for Cygwin 32bit Redis Server Windows builds](http://code.google.com/p/servicestack/wiki/RedisWindowsDownload).
  * [Project that lets you run Redis as a Windows Service](https://github.com/rgl/redis)
  * [Downloads for MinGW 32bit and 64bit Redis Server Windows builds](http://github.com/dmajkic/redis/downloads)

# Getting Started with the C# Redis client

###[C# Redis Client wiki](~/redis-client/redis-overview)
Contains all the examples, tutorials and resources you need to get you up to speed with common operations and the latest features.

[Useful Links on Redis server](~/redis-client/useful-redis-links)

### Specific Examples
  * [Using Transactions in Redis (i.e. MULTI/EXEC/DISCARD)](~/redis-client/redis-transactions)
  * [Using Redis's built-in Publsih/Subscribe pattern for high performance network notifications](~/redis-client/redis-pubsub)
  * [Using Redis to create high performance *distributed locks* spannable across multiple app servers](https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisLocks)

# Simple example using Redis Lists

Below is a simple example to give you a flavour of how easy it is to use some of Redis's advanced data structures - in this case Redis Lists:
_Full source code of this example is [viewable online](https://github.com/ServiceStack/ServiceStack.Redis/blob/master/tests/ServiceStack.Redis.Tests/ShippersExample.cs)_

    using (var redisClient = new RedisClient())
    {
        //Create a 'strongly-typed' API that makes all Redis Value operations to apply against Shippers
        IRedisTypedClient<Shipper> redis = redisClient.GetTypedClient<Shipper>();

        //Redis lists implement IList<T> while Redis sets implement ICollection<T>
        var currentShippers = redis.Lists["urn:shippers:current"];
        var prospectiveShippers = redis.Lists["urn:shippers:prospective"];

        currentShippers.Add(
            new Shipper {
                Id = redis.GetNextSequence(),
                CompanyName = "Trains R Us",
                DateCreated = DateTime.UtcNow,
                ShipperType = ShipperType.Trains,
                UniqueRef = Guid.NewGuid()
            });

        currentShippers.Add(
            new Shipper {
                Id = redis.GetNextSequence(),
                CompanyName = "Planes R Us",
                DateCreated = DateTime.UtcNow,
                ShipperType = ShipperType.Planes,
                UniqueRef = Guid.NewGuid()
            });

        var lameShipper = new Shipper {
            Id = redis.GetNextSequence(),
            CompanyName = "We do everything!",
            DateCreated = DateTime.UtcNow,
            ShipperType = ShipperType.All,
            UniqueRef = Guid.NewGuid()
        };

        currentShippers.Add(lameShipper);

        Dump("ADDED 3 SHIPPERS:", currentShippers);

        currentShippers.Remove(lameShipper);

        Dump("REMOVED 1:", currentShippers);

        prospectiveShippers.Add(
            new Shipper {
                Id = redis.GetNextSequence(),
                CompanyName = "Trucks R Us",
                DateCreated = DateTime.UtcNow,
                ShipperType = ShipperType.Automobiles,
                UniqueRef = Guid.NewGuid()
            });

        Dump("ADDED A PROSPECTIVE SHIPPER:", prospectiveShippers);

        redis.PopAndPushBetweenLists(prospectiveShippers, currentShippers);

        Dump("CURRENT SHIPPERS AFTER POP n' PUSH:", currentShippers);
        Dump("PROSPECTIVE SHIPPERS AFTER POP n' PUSH:", prospectiveShippers);

        var poppedShipper = redis.PopFromList(currentShippers);
        Dump("POPPED a SHIPPER:", poppedShipper);
        Dump("CURRENT SHIPPERS AFTER POP:", currentShippers);

        //reset sequence and delete all lists
        redis.SetSequence(0);
        redis.Remove(currentShippers, prospectiveShippers);
        Dump("DELETING CURRENT AND PROSPECTIVE SHIPPERS:", currentShippers);
    }

    /*
    == EXAMPLE OUTPUT ==

    ADDED 3 SHIPPERS:
    Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
    Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06
    Id:3,CompanyName:We do everything!,ShipperType:All,DateCreated:2010-01-31T11:53:37.8009371Z,UniqueRef:d0c249bbbaf84da39fc4afde1b34e332

    REMOVED 1:
    Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
    Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06

    ADDED A PROSPECTIVE SHIPPER:
    Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec

    CURRENT SHIPPERS AFTER POP n' PUSH:
    Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec
    Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5
    Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06

    PROSPECTIVE SHIPPERS AFTER POP n' PUSH:

    POPPED a SHIPPER:
    Id:2,CompanyName:Planes R Us,ShipperType:Planes,DateCreated:2010-01-31T11:53:37.799937Z,UniqueRef:e02a73191f4b4e7a9c44eef5b5965d06

    CURRENT SHIPPERS AFTER POP:
    Id:4,CompanyName:Trucks R Us,ShipperType:Automobiles,DateCreated:2010-01-31T11:53:37.8539401Z,UniqueRef:67d7d4947ebc4b0ba5c4d42f5d903bec
    Id:1,CompanyName:Trains R Us,ShipperType:Trains,DateCreated:2010-01-31T11:53:37.7169323Z,UniqueRef:d17c5db0415b44b2ac5da7b6ebd780f5

    DELETING CURRENT AND PROSPECTIVE SHIPPERS:
    */

More examples are available in the [RedisExamples Redis examples page] and in the comprehensive
[test suite](https://github.com/ServiceStack/ServiceStack.Redis/tree/master/tests/ServiceStack.Redis.Tests)

## Speed
One of the best things about Redis is the speed - it is quick.

[This example](https://github.com/ServiceStack/ServiceStack.Redis/blob/master/tests/ServiceStack.Redis.Tests/RedisClientTests.cs)
below stores and gets the entire [Northwind database](http://code.google.com/p/servicestack/source/browse/trunk/Common/Northwind.Benchmarks/Northwind.Common/DataModel/NorthwindData.cs) (3202 records) in less *1.2 secs* - we've never had it so quick!

_(Running inside a VS.NET/R# unit test on a 3 year old iMac)_

    using (var client = new RedisClient())
    {
        var before = DateTime.Now;
        client.StoreAll(NorthwindData.Categories);
        client.StoreAll(NorthwindData.Customers);
        client.StoreAll(NorthwindData.Employees);
        client.StoreAll(NorthwindData.Shippers);
        client.StoreAll(NorthwindData.Orders);
        client.StoreAll(NorthwindData.Products);
        client.StoreAll(NorthwindData.OrderDetails);
        client.StoreAll(NorthwindData.CustomerCustomerDemos);
        client.StoreAll(NorthwindData.Regions);
        client.StoreAll(NorthwindData.Territories);
        client.StoreAll(NorthwindData.EmployeeTerritories);

        Console.WriteLine("Took {0}ms to store the entire Northwind database ({1} records)",
            (DateTime.Now - before).TotalMilliseconds, totalRecords);

        before = DateTime.Now;
        var categories = client.GetAll<Category>();
        var customers = client.GetAll<Customer>();
        var employees = client.GetAll<Employee>();
        var shippers = client.GetAll<Shipper>();
        var orders = client.GetAll<Order>();
        var products = client.GetAll<Product>();
        var orderDetails = client.GetAll<OrderDetail>();
        var customerCustomerDemos = client.GetAll<CustomerCustomerDemo>();
        var regions = client.GetAll<Region>();
        var territories = client.GetAll<Territory>();
        var employeeTerritories = client.GetAll<EmployeeTerritory>();

        Console.WriteLine("Took {0}ms to get the entire Northwind database ({1} records)",
            (DateTime.Now - before).TotalMilliseconds, totalRecords);
    }
    /*
    == EXAMPLE OUTPUT ==

    Took 1020.0583ms to store the entire Northwind database (3202 records)
    Took 132.0076ms to get the entire Northwind database (3202 records)
    */

Note: The total time taken includes an extra Redis operation for each record to store the id in a Redis set for each
type as well as serializing and de-serializing each record using Service Stack's TypeSerializer.


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxEventsCronPublishing extends BxBaseModGroupsCronPublishing
{
    public function __construct()
    {
        $this->_sModule = 'bx_events';

        parent::__construct();
    }
}

/** @} */


text:
package org.openas2;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.openas2.params.InvalidParameterException;

public class BaseComponent implements Component {
    private Map parameters;
    private Session session;

    public String getName() {
        String clippedName = this.getClass().getName();

        // this clips off the package information
        StringTokenizer classParts = new StringTokenizer(clippedName, ".", false);

        while (classParts.hasMoreTokens()) {
            clippedName = classParts.nextToken();
        }

        return clippedName;
    }

    public void setParameter(String key, String value) {
        getParameters().put(key, value);
    }

    public void setParameter(String key, int value) {
        setParameter(key, Integer.toString(value));
    }

    public String getParameter(String key, boolean required)
        throws InvalidParameterException {
        String parameter = (String) getParameters().get(key);

        if (required && (parameter == null)) {
            throw new InvalidParameterException(this, key, null);
        }

        return parameter;
    }

    public String getParameter(String key, String defaultValue)
        throws InvalidParameterException {
        String value = getParameter(key, false);

        if (value == null) {
            return defaultValue;
        }

        return value;
    }

    public int getParameterInt(String key, boolean required)
        throws InvalidParameterException {
        String value = getParameter(key, required);

        if (value != null) {
            return Integer.parseInt(value);
        }

        return 0;
    }

    public Map getParameters() {
        if (parameters == null) {
            parameters = new HashMap();
        }

        return parameters;
    }

    public Session getSession() {
        return session;
    }

    public void init(Session session, Map parameters) throws OpenAS2Exception {
        this.session = session;
        this.parameters = parameters;
    }

}


text:
module Restforce
  class Document < Restforce::SObject
    # Public: Returns the body of the document.
    #
    # Examples
    #
    #   document = client.query('select Id, Name, Body from Document').first
    #   File.open(document.Name, 'wb') { |f| f.write(document.Body) }
    def Body
      ensure_id && ensure_body
      @client.get(super).body
    end

    private

    def ensure_body
      return true if self.Body?

      raise 'You need to query the Body for the record first.'
    end
  end
end


text:
package tetra.logic;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class MatrixGetSetBlocksTest {

    Matrix matrix;
    Block block;

    @Before
    public void setUp() {
        matrix = new Matrix(20, 10);
        block = new Block(1010);
    }

    @Test
    public void getBlockReturnsNullForNegativeCoordinates() {
        assertNull(matrix.getBlock(-1, -1));
        assertNull(matrix.getBlock(-1, 0));
        assertNull(matrix.getBlock(0, -1));
    }

    @Test
    public void getBlockReturnsNullForNegativeCoordinatesEvenForAFullMatrix() {
        matrix = MatrixHelper.getFullMatrix(10, 20, block);
        assertNull(matrix.getBlock(-1, -1));
        assertNull(matrix.getBlock(-1, 0));
        assertNull(matrix.getBlock(0, -1));
    }

    @Test
    public void getBlockReturnsNullForTooLargeCoordinates() {
        assertNull(matrix.getBlock(matrix.getCols(), matrix.getRows()));
        assertNull(matrix.getBlock(matrix.getCols(), 0));
        assertNull(matrix.getBlock(0, matrix.getRows()));
        assertNull(matrix.getBlock(100, 100));
    }

    @Test
    public void getBlockReturnsNullForTooLargeCoordinatesEvenForAFullMatrix() {
        matrix = MatrixHelper.getFullMatrix(10, 20, block);
        assertNull(matrix.getBlock(matrix.getCols(), matrix.getRows()));
        assertNull(matrix.getBlock(matrix.getCols(), 0));
        assertNull(matrix.getBlock(0, matrix.getRows()));
        assertNull(matrix.getBlock(100, 100));
    }

    @Test
    public void setBlockWorksCorrectly() {
        matrix.setBlock(5, 10, block);
        assertEquals(block, matrix.getBlock(5, 10));
    }

    @Test
    public void setBlockWorksForTopLeftCorner() {
        matrix.setBlock(0, 0, block);
        assertEquals(block, matrix.getBlock(0, 0));
    }

    @Test
    public void setBlockWorksForTopRightCorner() {
        matrix.setBlock(9, 0, block);
        assertEquals(block, matrix.getBlock(9, 0));
    }

    @Test
    public void setBlockWorksForBottomLeftCorner() {
        matrix.setBlock(0, 19, block);
        assertEquals(block, matrix.getBlock(0, 19));
    }

    @Test
    public void setBlockWorksForBottomRightCorner() {
        matrix.setBlock(9, 19, block);
        assertEquals(block, matrix.getBlock(9, 19));
    }

    @Test
    public void setBlockIsAbleToFillAllCells() {
        matrix = MatrixHelper.getFullMatrix(10, 20, block);
        for (int y = 0; y < matrix.getRows(); y++) {
            for (int x = 0; x < matrix.getCols(); x++) {
                assertEquals(block, matrix.getBlock(x, y));
            }
        }
    }

}


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

namespace App\Form;

use App\Entity\SettingEntity;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ResetType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class SettingAddForm
 * @package App\Form
 */
class SettingForm extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $function = $options['attr']['function'];
        $builder
            ->add('settingName', TextType::class, array(
                'label' => 'settings.add.name.label',
                'attr' => array('size' => 30)
            ));
        switch ($function) {
            case 'add':
                $builder
                    ->add('factory', EntityType::class, array(
                        'label' => 'factories.add.name.label',
                        'placeholder' => 'Выберите завод',
                        'class' => 'App:FactoryEntity',
                        'choice_label' => 'factoryName',
                    ))
                    ->add('submitButton', SubmitType::class, array('label' => 'facset.setting.create'));
                break;
            case 'edit':
                $builder
                    ->add('submitButton', SubmitType::class, array('label' => 'facset.setting.edit'))
                    ->add('cancelButton', ResetType::class, array('label' => 'facset.setting.cancel'));
                break;
        }
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => SettingEntity::class,
            'validation_groups' => array('setting_addition'),
            'attr' => array('id' => 'setting_form'),
            'translation_domain' => 'facset'
        ));
    }
}