text:
#region Using Statements
using System;
using System.Collections.Generic;

using Spectrum.Framework.Physics.Dynamics;
using Spectrum.Framework.Physics.LinearMath;
using Spectrum.Framework.Physics.Collision.Shapes;
#endregion

namespace Spectrum.Framework
{

    /// <summary>
    /// A thread safe resource pool.
    /// </summary>
    /// <typeparam name="T">The type of the object to cache. The type T must
    /// have a parameterless constructor.</typeparam>
    #region public class ResourcePool<T>
    public class ResourcePool<T>
    {
        private Stack<T> stack = new Stack<T>();
        readonly Func<T> constructor;
        readonly Action<T> onAcquire;
        public ResourcePool(Func<T> constructor = null, Action<T> onAcquire = null)
        {
            this.constructor = constructor;
            this.onAcquire = onAcquire;
        }

        public void Clear()
        {
            lock (stack)
                stack.Clear();
        }

        public int Count => stack.Count;

        public void GiveBack(T obj)
        {
            lock (stack) { stack.Push(obj); }
        }

        public T GetNew()
        {
            lock (stack)
            {
                if (stack.Count == 0)
                    return constructor == null ? Activator.CreateInstance<T>() : constructor();

                var freeObj = stack.Pop();
                onAcquire?.Invoke(freeObj);
                return freeObj;
            }
        }
    }
    #endregion

    /// <summary>
    /// A thread safe resource pool.
    /// </summary>
    /// <typeparam name="T">The type of the array of objects to cache. The type T must
    /// have a parameterless constructor.  Do not specify [].</typeparam>
    #region public class ArrayResourcePool<T>
    public class ArrayResourcePool<T>
    {
        private Stack<T[]> stack = new Stack<T[]>();

        /// <summary>
        /// The length of each array object to be created in the pool.
        /// </summary>
        private int arrayLength;

        /// <summary>
        /// Creates a new instance of the ResourcePool class.
        /// </summary>
        public ArrayResourcePool(int arrayLength)
        {
            this.arrayLength = arrayLength;
        }

        /// <summary>
        /// Removes all cached resources.
        /// So they can get garbage collected.
        /// </summary>
        public void ResetResourcePool()
        {
            lock (stack) { stack.Clear(); }
        }

        public int Count { get { return stack.Count; } }

        /// <summary>
        /// Gives a resource back to the pool.
        /// </summary>
        /// <param name="obj">The resource to give back</param>
        public void GiveBack(T[] obj)
        {
            lock (stack) { stack.Push(obj); }
        }

        /// <summary>
        /// Get a free resource.
        /// </summary>
        /// <returns>The free resource.</returns>
        public T[] GetNew()
        {
            T[] freeObj;

            lock (stack)
            {
                if (stack.Count == 0)
                {
                    freeObj = new T[arrayLength];
                    //freeObj = Activator.CreateInstance<T>();
                    stack.Push(freeObj);
                }

                freeObj = stack.Pop();
            }

            return freeObj;
        }
    }
    #endregion
}


text:
/**
 * Localization file for Croatian - Croatia (hr-HR)
 */
(function(factory) {
	// Module systems magic dance.
	/*global require,ko.validation,define*/
	if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
		// CommonJS or Node: hard-coded dependency on 'knockout-validation'
		factory(require('knockout.validation'));
	} else if (typeof define === "function" && define['amd']) {
		// AMD anonymous module with hard-coded dependency on 'knockout-validation'
		define(['knockout.validation'], factory);
	} else {
		// <script> tag: use the global `ko.validation` object
		factory(ko.validation);
	}
}(function(kv) {
	if (!kv || typeof kv.defineLocale !== 'function') {
		throw new Error('Knockout-Validation is required, please ensure it is loaded before this localization file');
	}
	return kv.defineLocale('hr-HR', {
		required: 'Ovo polje je obavezno.',
		min: 'Unesena vrijednost mora biti jednaka ili veća od {0}.',
		max: 'Unesena vrijednost mora biti jednaka ili manja od {0}.',
		minLength: 'Minimalna dužina polja je {0} znakova.',
		maxLength: 'Maksimalna dužina polja je {0} znakova.',
		pattern: 'Unesena vrijednost nije ispravnog formata.',
		step: 'Vrijednost se mora povećavati za {0}.',
		email: 'Potrebno je unijeti ispravnu e-mail adresu.',
		date: 'Potrebno je unijeti ispravan datum.',
		dateISO: 'Potrebno je unijeti ispravan datum.',
		number: 'Unesena vrijednost mora biti broj.',
		digit: 'Unesena vrijednost mora biti znamenka.',
		phoneUS: 'Potrebno je unijeti ispravan broj telefona.',
		equal: 'Vrijednosti moraju biti jednake.',
		notEqual: 'Unesite drugu vrijednost.',
		unique: 'Unesena vrijednost mora biti jedinstvena.'
	});
}));

redpajama_set_name: RedPajamaGithub


text:
package br.mp.mpt.prt8.severino.dao;

import java.util.List;
import java.util.Objects;
import java.util.Properties;

import javax.annotation.Resource;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.ContainerCriteria;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.stereotype.Repository;

import br.mp.mpt.prt8.severino.mediator.UsuarioHolder;
import br.mp.mpt.prt8.severino.utils.Constantes;
import br.mp.mpt.prt8.severino.valueobject.PessoaLdap;

/**
 * Consultas no LDAP.
 *
 * @author sergio.eoliveira
 *
 */
@Repository
public class LdapRepository {
	private static final Logger LOG = LoggerFactory.getLogger(LdapRepository.class);
	private static final String KEY_ATRIBUTOS_TRAZER = "attributesToShow";

	@Autowired
	private LdapTemplate ldapTemplate;

	@Autowired
	private UsuarioHolder usuarioHolder;

	@Resource(name = "ldapProperties")
	private Properties ldapProperties;

	public List<PessoaLdap> findByNomeLike(String parteNome) {
		LOG.info(String.format("Consultando LDAP por \"%s\" ...", parteNome));
		String ldapName = usuarioHolder.getLocal().getOrganizacao().getLdapName();
		String base = ldapName + ldapProperties.getProperty(Constantes.KEY_USER_SEARCH_BASE);
		String atributos = ldapProperties.getProperty(KEY_ATRIBUTOS_TRAZER);

		String[] attr = atributos.split(",");

		String cn = ldapProperties.getProperty("groupRoleAttribute");
		ContainerCriteria criteria = LdapQueryBuilder.query().base(base).attributes(attr).where("objectClass").is("person").and(cn).whitespaceWildcardsLike(parteNome);
		return ldapTemplate.search(criteria, new PessoaLdapAttributeMapper(attr));
	}

	/**
	 * Mapeador de atributos do LDAP.
	 *
	 * @author sergio.eoliveira
	 *
	 */
	private final class PessoaLdapAttributeMapper implements AttributesMapper<PessoaLdap> {

		private final String[] atributos;

		public PessoaLdapAttributeMapper(String[] atributos) {
			super();
			this.atributos = atributos;

		}

		@Override
		public PessoaLdap mapFromAttributes(Attributes attributes) throws NamingException {
			PessoaLdap pessoaLdap = new PessoaLdap();
			BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(pessoaLdap);
			for (String atributo : atributos) {
				Attribute attribute = attributes.get(atributo);
				String value = "";
				if (attribute != null) {
					value = Objects.toString(attribute.get());
				}
				wrapper.setPropertyValue(atributo, value);

			}
			return pessoaLdap;
		}
	}
}


text:
package com.vaadin.tests.components.textfield;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.testbench.elements.TextFieldElement;
import com.vaadin.tests.tb3.MultiBrowserTest;

/**
 * Test for .v-required style
 *
 * @author Vaadin Ltd
 */
public class RequiredTextFieldTest extends MultiBrowserTest {

    @Test
    public void testRequiredStyleName() {
        openTestURL();

        $(ButtonElement.class).first().click();

        assertTrue("Text field doesn't contain .v-required style",
                getStyles().contains("v-required"));

        $(ButtonElement.class).first().click();

        assertFalse(
                "Text field contains .v-required style for non-required field",
                getStyles().contains("v-required"));
    }

    private String getStyles() {
        return $(TextFieldElement.class).first().getAttribute("class");
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Metadiplodia tephrostoma f. tephrostoma

### Remarks
null


text:
import unittest as ut
import PyZOGY.util as util
from . import mock_image_class
import numpy as np

class test_util(ut.TestCase):

    def test_center_psf(self):
        psf = np.zeros((50, 51))
        psf[25, 25] = 1
        assert util.center_psf(psf)[0, 0] == 1

    def test_make_mask(self):
        saturation = 1.
        image = mock_image_class.MockImageClass(shape=(50, 50), saturation=saturation)
        image[25, 25] = 2.
        image[30, 30] = 1.

        mask = util.mask_saturated_pix(image, image.saturation, np.zeros(image.shape))
        assert mask[image >= saturation].all()

        mask = util.mask_saturated_pix(image, image.saturation, None)
        assert mask[image >= saturation].all()

    def test_interpolate_bad_pixels(self):
        image = mock_image_class.MockImageClass(shape=(50, 50))
        image[0, 25] = np.nan
        image[25, 0] = np.nan
        image[25, 25] = np.nan
        image.mask = np.zeros(shape=(50, 50))
        image.mask[np.isnan(image)] = 1
        image = util.interpolate_bad_pixels(image)
        assert np.isfinite(image).all()


text:
#include <set>
#include <list>
#include <iostream>
#include <fstream>

#include <util/timer.h>
#include <mve/image_tools.h>

#include "defines.h"
#include "settings.h"
#include "histogram.h"
#include "texture_patch.h"
#include "texture_atlas.h"

#define MAX_TEXTURE_SIZE (8 * 1024)
#define PREF_TEXTURE_SIZE (4 * 1024)
#define MIN_TEXTURE_SIZE (256)

TEX_NAMESPACE_BEGIN

/**
  * Heuristic to calculate an appropriate texture atlas size.
  * @warning asserts that no texture patch exceeds the dimensions
  * of the maximal possible texture atlas size.
  */
unsigned int
calculate_texture_size(std::list<TexturePatch::ConstPtr> const & texture_patches) {
    unsigned int size = MAX_TEXTURE_SIZE;

    while (true) {
        unsigned int total_area = 0;
        unsigned int max_width = 0;
        unsigned int max_height = 0;
        unsigned int padding = size >> 7;

        for (TexturePatch::ConstPtr texture_patch : texture_patches) {
            unsigned int width = texture_patch->get_width() + 2 * padding;
            unsigned int height = texture_patch->get_height() + 2 * padding;

            max_width = std::max(max_width, width);
            max_height = std::max(max_height, height);

            unsigned int area = width * height;
            unsigned int waste = area - texture_patch->get_size();

            /* Only consider patches where the information dominates padding. */
            if (static_cast<double>(waste) / texture_patch->get_size() > 1.0) {
                /* Since the patches are sorted by size we can assume that only
                 * few further patches will contribute to the size and break. */
                break;
            }

            total_area += area;
        }

        assert(max_width < MAX_TEXTURE_SIZE);
        assert(max_height < MAX_TEXTURE_SIZE);
        if (size > PREF_TEXTURE_SIZE &&
            max_width < PREF_TEXTURE_SIZE &&
            max_height < PREF_TEXTURE_SIZE &&
            total_area / (PREF_TEXTURE_SIZE * PREF_TEXTURE_SIZE) < 8) {
            size = PREF_TEXTURE_SIZE;
            continue;
        }

        if (size <= MIN_TEXTURE_SIZE) {
            return MIN_TEXTURE_SIZE;
        }

        if (max_height < size / 2 && max_width < size / 2 &&
            static_cast<double>(total_area) / (size * size) < 0.2) {
            size = size / 2;
            continue;
        }

        return size;
    }
}

bool comp(TexturePatch::ConstPtr first, TexturePatch::ConstPtr second) {
    return first->get_size() > second->get_size();
}

void
generate_texture_atlases(std::vector<TexturePatch::Ptr> * orig_texture_patches,
    Settings const & settings, std::vector<TextureAtlas::Ptr> * texture_atlases) {

    std::list<TexturePatch::ConstPtr> texture_patches;
    while (!orig_texture_patches->empty()) {
        TexturePatch::Ptr texture_patch = orig_texture_patches->back();
        orig_texture_patches->pop_back();

        if (settings.tone_mapping != TONE_MAPPING_NONE) {
            mve::image::gamma_correct(texture_patch->get_image(), 1.0f / 2.2f);
        }

        texture_patches.push_back(texture_patch);
    }

    std::cout << "\tSorting texture patches... " << std::flush;
    /* Improve the bin-packing algorithm efficiency by sorting texture patches
     * in descending order of size. */
    texture_patches.sort(comp);
    std::cout << "done." << std::endl;

    std::size_t const total_num_patches = texture_patches.size();
    std::size_t remaining_patches = texture_patches.size();
    std::ofstream tty("/dev/tty", std::ios_base::out);

    #pragma omp parallel
    {
    #pragma omp single
    {

    while (!texture_patches.empty()) {
        unsigned int texture_size = calculate_texture_size(texture_patches);

        texture_atlases->push_back(TextureAtlas::create(texture_size));
        TextureAtlas::Ptr texture_atlas = texture_atlases->back();

        /* Try to insert each of the texture patches into the texture atlas. */
        std::list<TexturePatch::ConstPtr>::iterator it = texture_patches.begin();
        for (; it != texture_patches.end();) {
            std::size_t done_patches = total_num_patches - remaining_patches;
            int precent = static_cast<float>(done_patches)
                / total_num_patches * 100.0f;
            if (total_num_patches > 100
                && done_patches % (total_num_patches / 100) == 0) {

                tty << "\r\tWorking on atlas " << texture_atlases->size() << " "
                 << precent << "%... " << std::flush;
            }

            if (texture_atlas->insert(*it)) {
                it = texture_patches.erase(it);
                remaining_patches -= 1;
            } else {
                ++it;
            }
        }

        #pragma omp task
        texture_atlas->finalize();
    }

    std::cout << "\r\tWorking on atlas " << texture_atlases->size()
        << " 100%... done." << std::endl;
    util::WallTimer timer;
    std::cout << "\tFinalizing texture atlases... " << std::flush;
    #pragma omp taskwait
    std::cout << "done. (Took: " << timer.get_elapsed_sec() << "s)" << std::endl;

    /* End of single region */
    }
    /* End of parallel region. */
    }
}

TEX_NAMESPACE_END


text:
abstract type Sim end

struct POMDPSim <: Sim
    simulator::Simulator
    pomdp::POMDP
    policy::Policy
    updater::Updater
    initial_belief::Any
    initial_state::Any
    metadata::Dict{Symbol}
end

problem(sim::POMDPSim) = sim.pomdp

struct MDPSim <: Sim
    simulator::Simulator
    mdp::MDP
    policy::Policy
    initial_state::Any
    metadata::Dict{Symbol}
end

problem(sim::MDPSim) = sim.mdp

"""
    Sim(p::POMDP, policy::Policy, metadata=Dict(:note=>"a note"))
    Sim(p::POMDP, policy::Policy[, updater[, initial_belief[, initial_state]]]; kwargs...)

Create a `Sim` object that represents a POMDP simulation.
"""
function Sim(pomdp::POMDP,
             policy::Policy,
             up=updater(policy),
             initial_belief=initial_state_distribution(pomdp),
             initial_state=nothing;
             rng::AbstractRNG=Base.GLOBAL_RNG,
             max_steps::Int=typemax(Int),
             simulator::Simulator=HistoryRecorder(rng=rng, max_steps=max_steps),
             metadata::Dict{Symbol}=Dict{Symbol, Any}()
            )

    if initial_state == nothing && state_type(pomdp) != Void
        is = rand(rng, initial_belief)
    else
        is = initial_state
    end
    return POMDPSim(simulator, pomdp, policy, up, initial_belief, is, metadata)
end

"""
    Sim(p::MDP, policy::Policy, metadata=Dict(:note=>"a note"))
    Sim(p::MDP, policy::Policy[, initial_state]; kwargs...)

Create a `Sim` object that represents a MDP simulation.

A vector of `Sim` objects can be executed with `run` or `run_parallel`.

## Keyword Arguments
- `rng::AbstractRNG=Base.GLOBAL_RNG`
- `max_steps::Int=typemax(Int)`
- `simulator::Simulator=HistoryRecorder(rng=rng, max_steps=max_steps)`
- `metadata::Dict{Symbol}=Dict{Symbol, Any}()` a dictionary of metadata for the sim that will be recorded, e.g. `Dict(:solver_iterations=>500)`.
"""
function Sim(mdp::MDP,
             policy::Policy,
             initial_state=nothing;
             rng::AbstractRNG=Base.GLOBAL_RNG,
             max_steps::Int=typemax(Int),
             simulator::Simulator=HistoryRecorder(rng=rng, max_steps=max_steps),
             metadata::Dict{Symbol}=Dict{Symbol, Any}()
            )

    if initial_state == nothing && state_type(mdp) != Void
        is = POMDPs.initial_state(mdp, rng)
    else
        is = initial_state
    end
    return MDPSim(simulator, mdp, policy, is, metadata)
end

POMDPs.simulate(s::POMDPSim) = simulate(s.simulator, s.pomdp, s.policy, s.updater, s.initial_belief, s.initial_state)
POMDPs.simulate(s::MDPSim) = simulate(s.simulator, s.mdp, s.policy, s.initial_state)

default_process(s::Sim, r::Float64) = :reward=>r
default_process(s::Sim, hist::SimHistory) = default_process(s, discounted_reward(hist))

run_parallel(queue::AbstractVector; kwargs...) = run_parallel(default_process, queue; kwargs...)

"""
    run_parallel(queue::Vector{Sim})
    run_parallel(f::Function, queue::Vector{Sim})

Run `Sim` objects in `queue` in parallel and return results as a `DataFrame`.

By default, the `DataFrame` will contain the reward for each simulation and the metadata provided to the sim.

# Arguments
- `queue`: List of `Sim` objects to be executed
- `f`: Function to process the results of each simulation
This function should take two arguments, (1) the `Sim` that was executed and (2) the result of the simulation, by default a `SimHistory`. It should return a dictionary or vector of pairs of `Symbol`s and values that will appear in the dataframe. See Examples below.

## Keyword Arguments
- `progress`: a `ProgressMeter.Progress` for showing progress through the simulations; `progress=false` will suppress the progress meter

# Examples

```julia
run_parallel(queue) do sim, hist
    return [:n_steps=>n_steps(hist), :reward=>discounted_reward(hist)]
end
```
will return a dataframe with with the number of steps and the reward in it.
"""
function run_parallel(process::Function, queue::AbstractVector;
                      progress=Progress(length(queue), desc="Simulating..."),
                      proc_warn=true)

    #=
    frame_lines = pmap(progress, queue) do sim
        result = simulate(sim)
        return process(sim, result)
    end
    =#

    np = nprocs()
    if np == 1 && proc_warn
        warn("""
             run_parallel(...) was started with only 1 process, so simulations will be run in serial.

             To suppress this warning, use run_parallel(..., proc_warn=false).

             To use multiple processes, use addprocs() or the -p option (e.g. julia -p 4).
             """)
    end
    n = length(queue)
    i = 1
    prog = 0
    # based on the simple implementation of pmap here: https://docs.julialang.org/en/latest/manual/parallel-computing
    frame_lines = Vector{Any}(n)
    nextidx() = (idx=i; i+=1; idx)
    prog_lock = ReentrantLock()
    @sync begin
        for p in 1:np
            if np == 1 || p != myid()
                @async begin
                    while true
                        idx = nextidx()
                        if idx > n
                            break
                        end
                        frame_lines[idx] = remotecall_fetch(p, queue[idx]) do sim
                            result = simulate(sim)
                            output = process(sim, result)
                            return append_metadata(output, sim.metadata)
                        end
                        if progress isa Progress
                            lock(prog_lock)
                            update!(progress, prog+=1)
                            unlock(prog_lock)
                        end
                    end
                end
            end
        end
    end
    if progress isa Progress
        lock(prog_lock)
        finish!(progress)
        unlock(prog_lock)
    end

    return create_dataframe(frame_lines)
end

Base.run(queue::AbstractVector) = run(default_process, queue)

"""
    run(queue::Vector{Sim})
    run(f::Function, queue::Vector{Sim})

Run the `Sim` objects in `queue` on a single process and return the results as a dataframe.

See `run_parallel` for more information.
"""
function Base.run(process::Function, queue::AbstractVector; show_progress=true)
    lines = []
    if show_progress
        @showprogress for sim in queue
            result = simulate(sim)
            output = process(sim, result)
            line = append_metadata(output, sim.metadata)
            push!(lines, line)
        end
    else
        for sim in queue
            result = simulate(sim)
            output = process(sim, result)
            line = append_metadata(output, sim.metadata)
            push!(lines, line)
        end
    end
    return create_dataframe(lines)
end

append_metadata(single::Pair, metadata::Dict) = append!(Any[single], collect(metadata))
append_metadata(pairvec::AbstractVector, metadata::Dict) = vcat(pairvec, collect(metadata))
append_metadata(d::Dict, metadata::Dict) = merge!(d, metadata)

metadata_as_pairs(s::Sim) = convert(Array{Any}, collect(s.metadata))

function create_dataframe(lines::Vector)
    master = Dict{Symbol, AbstractVector}()
    for line in lines
        push_line!(master, line)
    end
    return DataFrame(master)
end

function _push_line!(d::Dict{Symbol, AbstractVector}, line)
    if isempty(d)
        len = 0
    else
        len = length(first(values(d)))
    end
    for (key, val) in line
        T = typeof(val)
        if !haskey(d, key)
            d[key] = fill!(Array{Union{T,Missing}}(len), missing)
        end
        data = d[key]
        if !isa(val,eltype(data))
            d[key] = convert(Array{Any,1}, data)
        end
        push!(d[key], val)
    end
    for da in values(d)
        if length(da) < len + 1
            push!(da, missing)
        end
    end
    return d
end
push_line!(d::Dict{Symbol, AbstractVector}, line::Dict) = _push_line!(d, line)
push_line!(d::Dict{Symbol, AbstractVector}, line::DataFrame) = _push_line!(d, n=>first(line[n]) for n in names(line))
push_line!(d::Dict{Symbol, AbstractVector}, line::AbstractVector) = _push_line!(d, line)
push_line!(d::Dict{Symbol, AbstractVector}, line::Tuple) = _push_line!(d, line)
push_line!(d::Dict{Symbol, AbstractVector}, line::Pair) = _push_line!(d, (line,))


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/codemirror.css"/>
<link rel="stylesheet" type="text/css" href="//cdn.rawgit.com/oracle/oraclejet/2a420014546d371d076ec741ef171f0a3c71f28d/dist/css/alta/oj-alta-min.css"/>

<title>ORDS REST enabled SQL</title>

Request

                                Server

                                <input id="server" type="text" data-bind="ojComponent: {component: 'ojInputText',value: server,optionChange: onChange, rootAttributes: { style: 'max-width: 20em;' } }">

                                Username

                                <input id="username" type="text" data-bind="ojComponent: {component: 'ojInputText',value: username,optionChange: onChange, rootAttributes: { style: 'max-width: 20em;' } }">

                                Password

                                <input id="password" type="text" data-bind="ojComponent: {component: 'ojInputText',value: password,optionChange: onChange, rootAttributes: { style: 'max-width: 20em;' } }">

                                Schema

                                <input id="schema" type="text" data-bind="ojComponent: {component: 'ojInputText',value: schema,optionChange: onChange, rootAttributes: { style: 'max-width: 20em;' } }">

                                Content Type

                                <input id="contentType" list="contentTypes" data-bind="ojComponent: {component: 'ojSelect', value: 'application/sql',optionChange: onChange,rootAttributes: {style:'max-width:20em'}}"/>
                                <datalist id="contentTypes">

                                    <option data-bind="value:value, text:label"></option>

                                </datalist>

                                Examples

                                <input id="exampleSelector" list="exampleList" data-bind="ojComponent: {component: 'ojSelect',rootAttributes: {style:'max-width:20em'} ,optionChange: onChange}"/>
                                <datalist id="exampleList">

                                    <option data-bind="value: $index, text:name"></option>

                                </datalist>

                        <textarea id="sql" wrap="off"></textarea>

                        <input id="submit" type="submit" data-bind="click: runIt, ojComponent: {component: 'ojButton', label: 'Run »'}" style="margin: 0;"/>

Response

            <textarea id="results" wrap="off" style="height: calc(100% - 36px);"></textarea>

Curl Example

JQuery

SQLcl

curl


text:
RdnTrailingSlash
================

The **RdnTrailingSlash** ZF2 module trims the trailing slash in a path and then redirects the request if it does not match an existing route.

## Installation

1. Use `composer` to require the `radnan/rdn-trailing-slash` package:

   ~~~bash
   $ composer require radnan/rdn-trailing-slash:1.*
   ~~~

2. Activate the module by including it in your `application.config.php` file:

   ~~~php
   <?php

   return array(
       'modules' => array(
           'RdnTrailingSlash',
           // ...
       ),
   );
   ~~~

That's it! The module will take care of the rest.


text:
001    package org.apache.hadoop.hdfs.server.namenode;
002
003    import javax.servlet.*;
004    import javax.servlet.http.*;
005    import javax.servlet.jsp.*;
006    import org.apache.hadoop.util.ServletUtil;
007    import org.apache.hadoop.hdfs.server.namenode.ClusterJspHelper.ClusterStatus;
008    import java.util.List;
009    import org.znerd.xmlenc.*;
010
011    public final class dfsclusterhealth_jsp extends org.apache.jasper.runtime.HttpJspBase
012        implements org.apache.jasper.runtime.JspSourceDependent {
013
014
015
032
033
034      //for java.io.Serializable
035      private static final long serialVersionUID = 1L;
036
037      private static java.util.List _jspx_dependants;
038
039      public Object getDependants() {
040        return _jspx_dependants;
041      }
042
043      public void _jspService(HttpServletRequest request, HttpServletResponse response)
044            throws java.io.IOException, ServletException {
045
046        JspFactory _jspxFactory = null;
047        PageContext pageContext = null;
048        HttpSession session = null;
049        ServletContext application = null;
050        ServletConfig config = null;
051        JspWriter out = null;
052        Object page = this;
053        JspWriter _jspx_out = null;
054        PageContext _jspx_page_context = null;
055
056
057        try {
058          _jspxFactory = JspFactory.getDefaultFactory();
059          response.setContentType("application/xml");
060          pageContext = _jspxFactory.getPageContext(this, request, response,
061                            null, true, 8192, true);
062          _jspx_page_context = pageContext;
063          application = pageContext.getServletContext();
064          config = pageContext.getServletConfig();
065          session = pageContext.getSession();
066          out = pageContext.getOut();
067          _jspx_out = out;
068
069          out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"dfsclusterhealth.xsl\"?>\n");
070
071       /**
072        * This JSP page provides cluster summary in XML format. It lists information
073        * such as total files and blocks, total capacity, total used/freed spaces,etc.
074        * accorss cluster reported by all name nodes.
075        * It also lists information such as used space per name node.
076        */
077       final ClusterJspHelper clusterhealthjsp  = new ClusterJspHelper();
078       ClusterStatus cInfo = clusterhealthjsp.generateClusterHealthReport();
079       XMLOutputter doc = new XMLOutputter(out, "UTF-8");
080       cInfo.toXML(doc);
081
082        } catch (Throwable t) {
083          if (!(t instanceof SkipPageException)){
084            out = _jspx_out;
085            if (out != null && out.getBufferSize() != 0)
086              out.clearBuffer();
087            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
088          }
089        } finally {
090          if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
091        }
092      }
093    }


text:
syscfg_t sys_cfg;
SAVE_FLAG saveFlag;

#define EXT_CFG_LOCATION		0x0

#ifdef EXT_SPI_RAM_IS_NAND
#define EXT_SPI_RAM_SEC_SIZE	0x1000	// 4 kB block size for FLASH RAM
#else
#define EXT_SPI_RAM_SEC_SIZE	0x200	// we only need 512 bytes for config when FeRAM is used
#endif

#define SAVE_DEFER_TIME 2000
static os_timer_t config_save_timer;
char config_save_timer_running;

bool ICACHE_FLASH_ATTR
cfg_save(uint16_t *calculated_crc, uint16_t *saved_crc) {
#if !defined(IMPULSE_DEV_BOARD) && (defined(IMPULSE) && !defined(DEBUG_NO_METER))	// use internal flash if built with DEBUG_NO_METER=1
	uint32_t impulse_meter_count_temp;

	do {
		// try to save until sys_cfg.impulse_meter_count does not change
		impulse_meter_count_temp = sys_cfg.impulse_meter_count;

		// calculate checksum on sys_cfg struct without ccit_crc16
		sys_cfg.ccit_crc16 = ccit_crc16(0xffff, (uint8_t *)&sys_cfg, offsetof(syscfg_t, ccit_crc16) - offsetof(syscfg_t, cfg_holder));
		ext_spi_flash_read((EXT_CFG_LOCATION + 2) * EXT_SPI_RAM_SEC_SIZE,
		                   (uint32 *)&saveFlag, sizeof(SAVE_FLAG));

		if (saveFlag.flag == 0) {
#ifdef EXT_SPI_RAM_IS_NAND
			ext_spi_flash_erase_sector(EXT_CFG_LOCATION + 1);
#endif	// EXT_SPI_RAM_IS_NAND
			ext_spi_flash_write((EXT_CFG_LOCATION + 1) * EXT_SPI_RAM_SEC_SIZE,
							(uint32 *)&sys_cfg, sizeof(syscfg_t));
			saveFlag.flag = 1;
#ifdef EXT_SPI_RAM_IS_NAND
			ext_spi_flash_erase_sector(EXT_CFG_LOCATION + 2);
#endif	// EXT_SPI_RAM_IS_NAND
			ext_spi_flash_write((EXT_CFG_LOCATION + 2) * EXT_SPI_RAM_SEC_SIZE,
							(uint32 *)&saveFlag, sizeof(SAVE_FLAG));
		} else {
#ifdef EXT_SPI_RAM_IS_NAND
			ext_spi_flash_erase_sector(EXT_CFG_LOCATION + 0);
#endif	// EXT_SPI_RAM_IS_NAND
			ext_spi_flash_write((EXT_CFG_LOCATION + 0) * EXT_SPI_RAM_SEC_SIZE,
							(uint32 *)&sys_cfg, sizeof(syscfg_t));
			saveFlag.flag = 0;
#ifdef EXT_SPI_RAM_IS_NAND
			ext_spi_flash_erase_sector(EXT_CFG_LOCATION + 2);
#endif	// EXT_SPI_RAM_IS_NAND
			ext_spi_flash_write((EXT_CFG_LOCATION + 2) * EXT_SPI_RAM_SEC_SIZE,
							(uint32 *)&saveFlag, sizeof(SAVE_FLAG));
		}
	} while (sys_cfg.impulse_meter_count != impulse_meter_count_temp);
#else
	// calculate checksum on sys_cfg struct without ccit_crc16
	sys_cfg.ccit_crc16 = ccit_crc16(0xffff, (uint8_t *)&sys_cfg, offsetof(syscfg_t, ccit_crc16) - offsetof(syscfg_t, cfg_holder));
	system_param_save_with_protect(CFG_LOCATION, &sys_cfg, sizeof(syscfg_t));

	// check for flash memory error
	if (calculated_crc && saved_crc) {	// check if return values was requested
		*saved_crc = sys_cfg.ccit_crc16;
		cfg_load();	// reload saved config
		*calculated_crc = ccit_crc16(0xffff, (uint8_t *)&sys_cfg, offsetof(syscfg_t, ccit_crc16) - offsetof(syscfg_t, cfg_holder));
		if (*calculated_crc != *saved_crc) {
			return false;
		}
	}
#endif	// IMPULSE
	return true;
}

void ICACHE_FLASH_ATTR
cfg_load() {
	// DEBUG: we suppose nothing else is touching sys_cfg while saving otherwise checksum becomes wrong
	INFO("\r\nload ...\r\n");
#if !defined(IMPULSE_DEV_BOARD) && (defined(IMPULSE) && !defined(DEBUG_NO_METER))	// use internal flash if built with DEBUG_NO_METER=1
	ext_spi_flash_read((EXT_CFG_LOCATION + 2) * EXT_SPI_RAM_SEC_SIZE,
				   (uint32 *)&saveFlag, sizeof(SAVE_FLAG));
	if (saveFlag.flag == 0) {
		ext_spi_flash_read((EXT_CFG_LOCATION + 0) * EXT_SPI_RAM_SEC_SIZE,
					   (uint32 *)&sys_cfg, sizeof(syscfg_t));
	} else {
		ext_spi_flash_read((EXT_CFG_LOCATION + 1) * EXT_SPI_RAM_SEC_SIZE,
					   (uint32 *)&sys_cfg, sizeof(syscfg_t));
	}
#else
	system_param_load(CFG_LOCATION, 0, &sys_cfg, sizeof(syscfg_t));
#endif	// IMPULSE

	// if checksum fails...
	if (sys_cfg.ccit_crc16 != ccit_crc16(0xffff, (uint8_t *)&sys_cfg, offsetof(syscfg_t, ccit_crc16) - offsetof(syscfg_t, cfg_holder))) {
#ifdef DEBUG
		printf("config crc error, default conf loaded\n");
#endif // DEBUG
		// if first time config load default conf
		os_memset(&sys_cfg, 0x00, sizeof(syscfg_t));

		tfp_snprintf(sys_cfg.sta_ssid, 64, "%s", STA_SSID);
		tfp_snprintf(sys_cfg.sta_pwd, 64, "%s", STA_PASS);
		sys_cfg.sta_type = STA_TYPE;
		sys_cfg.ap_enabled = true;
		tfp_snprintf(sys_cfg.device_id, 16, MQTT_CLIENT_ID, system_get_chip_id());
		tfp_snprintf(sys_cfg.mqtt_host, 64, "%s", MQTT_HOST);
		sys_cfg.mqtt_port = MQTT_PORT;
		tfp_snprintf(sys_cfg.mqtt_user, 32, "%s", MQTT_USER);
		tfp_snprintf(sys_cfg.mqtt_pass, 32, "%s", MQTT_PASS);

		sys_cfg.security = DEFAULT_SECURITY;	//default non ssl

		memcpy(sys_cfg.key, key, sizeof(key));

		sys_cfg.mqtt_keepalive = MQTT_KEEPALIVE;
#ifdef IMPULSE
		tfp_snprintf(sys_cfg.impulse_meter_serial, METER_SERIAL_LEN, DEFAULT_METER_SERIAL);
		tfp_snprintf(sys_cfg.impulse_meter_units, 2, "0");
		tfp_snprintf(sys_cfg.impulses_per_unit, 4, "100");
		sys_cfg.impulse_meter_count = 0;
		sys_cfg.operating_time = 0;
#else
		sys_cfg.ac_thermo_state = 0;
		sys_cfg.offline_close_at = 0;
#ifndef NO_CRON
		memset(&sys_cfg.cron_jobs, 0, sizeof(cron_job_t));
#endif	// NO_CRON
#endif	// IMPULSE

		INFO(" default configuration\r\n");

		cfg_save(NULL, NULL);
	}
	else {
#ifdef DEBUG
		printf("config crc ok\n");
#endif // DEBUG
	}
}

void ICACHE_FLASH_ATTR
cfg_save_defered() {
	os_timer_disarm(&config_save_timer);
	os_timer_setfn(&config_save_timer, (os_timer_func_t *)config_save_timer_func, NULL);
	os_timer_arm(&config_save_timer, SAVE_DEFER_TIME, 0);
}

bool ICACHE_FLASH_ATTR cfg_save_ssid_pwd(char *ssid_pwd, uint16_t *calculated_crc, uint16_t *saved_crc) {
	// for parsing query string formatted parameters
	char *str;
	char *query_string_key, *query_string_value;
	char query_string_key_value[MQTT_MESSAGE_L];
	char *context_query_string, *context_key_value;

	char ssid_pwd_copy[COMMAND_PARAMS_L];

	strncpy(ssid_pwd_copy, ssid_pwd, COMMAND_PARAMS_L);	// make a copy since strtok_r() changes it

	str = strtok_r(ssid_pwd_copy, "&", &context_query_string);
	while (str != NULL) {
		strncpy(query_string_key_value, str, MQTT_MESSAGE_L);
		query_string_key = strtok_r(query_string_key_value, "=", &context_key_value);
		query_string_value = strtok_r(NULL, "=", &context_key_value);
		if (strncmp(query_string_key, "ssid", MQTT_MESSAGE_L) == 0) {
			// un-escape & and =
			query_string_unescape(query_string_value);

			// change sta_ssid, save if different
#ifdef DEBUG
			printf("key: %s value: %s\n", query_string_key, query_string_value);
#endif	// DEBUG
			if (strncmp(sys_cfg.sta_ssid, query_string_value, 32 - 1) != 0) {
				memset(sys_cfg.sta_ssid, 0, sizeof(sys_cfg.sta_ssid));
				strncpy(sys_cfg.sta_ssid, query_string_value, 32 - 1);
			}
		}
		else if (strncmp(query_string_key, "pwd", MQTT_MESSAGE_L) == 0) {
			// change sta_pwd, save if different
			if (query_string_value == 0) {
				// there is no value - no password used, use null string
#ifdef DEBUG
				printf("key: %s value: %s\n", query_string_key, "null");
#endif	// DEBUG
				if (strncmp(sys_cfg.sta_pwd, "", 1) != 0) {
					memset(sys_cfg.sta_pwd, 0, sizeof(sys_cfg.sta_pwd));
					strncpy(sys_cfg.sta_pwd, "", 1);
				}
			}
			else {
				// un-escape & and =
				query_string_unescape(query_string_value);
#ifdef DEBUG
				printf("key: %s value: %s\n", query_string_key, query_string_value);
#endif	// DEBUG
				if (strncmp(sys_cfg.sta_pwd, query_string_value, 64 - 1) != 0) {
					memset(sys_cfg.sta_pwd, 0, sizeof(sys_cfg.sta_pwd));
					strncpy(sys_cfg.sta_pwd, query_string_value, 64 - 1);
				}
			}
		}
		str = strtok_r(NULL, "&", &context_query_string);
	}
	return cfg_save(calculated_crc, saved_crc);
}

ICACHE_FLASH_ATTR
void config_save_timer_func(void *arg) {
	if (config_save_timer_running) {
		// reschedule
		os_timer_disarm(&config_save_timer);
		os_timer_setfn(&config_save_timer, (os_timer_func_t *)config_save_timer_func, NULL);
		os_timer_arm(&config_save_timer, SAVE_DEFER_TIME, 0);
	}
	else {
		// stop timer
		os_timer_disarm(&config_save_timer);
		config_save_timer_running = 0;

		cfg_save(NULL, NULL);
	}
}


text:
module Deltacloud::Client
  class Blob < Base

    include Deltacloud::Client::Methods::Blob
    include Deltacloud::Client::Methods::Bucket

    # Inherited attributes: :_id, :name, :description

    # Custom attributes:
    #
    attr_reader :bucket_id
    attr_reader :content_length
    attr_reader :content_type
    attr_reader :last_modified
    attr_reader :user_metadata

    # Blob model methods
    #

    def bucket
      super(bucket_id)
    end

    # Parse the Blob entity from XML body
    #
    # - xml_body -> Deltacloud API XML representation of the blob
    #
    def self.parse(xml_body)
      {
        :bucket_id => xml_body.text_at(:bucket_id) || xml_body.text_at(:bucket), # FIXME: DC bug
        :content_length => xml_body.text_at(:content_length),
        :content_type => xml_body.text_at(:content_type),
        :last_modified => xml_body.text_at(:last_modified),
        :user_metadata => xml_body.xpath('user_metadata/entry').inject({}) { |r,e|
          r[e['key']] = e.text.strip
          r
        }
      }
    end
  end
end


text:
using RayTracer.Objects;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Numerics;
using System.Threading.Tasks;

namespace RayTracer
{
    /// <summary>
    /// The scene camera, contains all relevant rendering methods and algorithms.
    /// </summary>
    public class Camera : SceneObjectBase
    {
        private Vector3 forward, up, right;
        private Vector3 screenPosition;
        private float fieldOfView;
        public float FieldOfView
        {
            get { return fieldOfView; }
            set
            {
                fieldOfView = value;
                RecalculateFieldOfView();
            }
        }
        private float yRatio;

        public int ReflectionDepth { get; set; }
        private Size renderSize;
        public Size RenderSize { get { return renderSize; } set { renderSize = value; OnRenderSizeChanged(); } }

        private void OnRenderSizeChanged()
        {
            this.yRatio = (float)renderSize.Height / (float)renderSize.Width;
        }

        public Camera() : this(Vector3.Zero, Util.ForwardVector, Util.UpVector, 70f, new Size(640, 480)) { }

        public Camera(Vector3 position, Vector3 forward, Vector3 worldUp, float fieldOfView, Size renderSize)
            : base(position)
        {
            this.ReflectionDepth = 5;
            this.forward = forward.Normalized();
            this.right = Util.CrossProduct(worldUp, forward).Normalized();
            this.up = -Util.CrossProduct(right, forward).Normalized();
            this.fieldOfView = fieldOfView;
            this.RenderSize = renderSize;

            RecalculateFieldOfView();
        }

        private void RecalculateFieldOfView()
        {
            var screenDistance = 1f / (float)Math.Tan(Util.DegreesToRadians(fieldOfView) / 2f);

            this.screenPosition = this.Position + forward * new Vector3(screenDistance);
        }

        private Ray GetRay(float viewPortX, float viewPortY)
        {
            var rayWorldPosition = screenPosition + ((new Vector3(viewPortX) * right) + (new Vector3(viewPortY) * up * new Vector3(yRatio)));
            var direction = rayWorldPosition - this.Position;
            return new Ray(rayWorldPosition, direction);
        }

        private Ray GetReflectionRay(Vector3 origin, Vector3 normal, Vector3 impactDirection)
        {
            float c1 = Vector3.Dot(-normal, impactDirection);
            Vector3 reflectionDirection = impactDirection + (normal * new Vector3(2 * c1));
            return new Ray(origin + reflectionDirection * new Vector3(.01f), reflectionDirection); // Ensures the ray starts "just off" the reflected surface
        }

        private Ray GetRefractionRay(Vector3 origin, Vector3 normal, Vector3 previousDirection, float refractivity)
        {
            float c1 = Vector3.Dot(normal, previousDirection);
            float c2 = 1 - refractivity * refractivity * (1 - c1 * c1);
            if (c2 < 0)
                c2 = (float)Math.Sqrt(c2);
            Vector3 refractionDirection = (normal * new Vector3((refractivity * c1 - c2)) - previousDirection * new Vector3(refractivity)) * new Vector3(-1);
            return new Ray(origin, refractionDirection.Normalized()); // no refraction
        }

        /// <summary>
        /// Renders the given scene to a bitmap, using one thread per line of pixels in the image.
        /// </summary>
        /// <param name="scene">The scene to render</param>
        /// <returns>A bitmap of the rendered scene.</returns>
        public async Task<Bitmap> RenderSceneToBitmapThreaded(Scene scene, int width = -1, int height = -1)
        {
            if (width == -1 || height == -1)
            {
                width = renderSize.Width;
                height = renderSize.Height;
            }
            else
            {
                renderSize = new Size(width, height);
            }

            var before = DateTime.UtcNow;
            Bitmap bitmap = new Bitmap(width, height);

            List<Task> tasks = new List<Task>();

            Color[,] colors = new Color[width, height];

            for (int xCounter = 0; xCounter < width; xCounter++)
            {
                var x = xCounter;
                var task = Task.Run(() =>
                    {
                        for (int yCounter = 0; yCounter < height; yCounter++)
                        {
                            var y = yCounter;
                            var viewPortX = ((2 * x) / (float)width) - 1;
                            var viewPortY = ((2 * y) / (float)height) - 1;
                            var color = TraceRayAgainstScene(GetRay(viewPortX, viewPortY), scene);
                            colors[x, y] = color;
                        }
                    });

                tasks.Add(task);
            }

            await Task.WhenAll(tasks);

            // Copy all pixel data into bitmap.
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bitmap.SetPixel(x, height - y - 1, colors[x, y]);
                }
            }

            var after = DateTime.UtcNow;
            System.Diagnostics.Debug.WriteLine("Total render time: " + (after - before).TotalMilliseconds + " ms");
            return bitmap;
        }

        /// <summary>
        /// Renders the given scene in a background thread. Uses a single thread for rendering.
        /// </summary>
        /// <param name="scene">The scene to render</param>
        /// <returns>A bitmap of the rendered scene.</returns>
        public async Task<Bitmap> RenderSceneToBitmap(Scene scene, int width = -1, int height = -1)
        {
            if (width == -1 || height == -1)
            {
                width = renderSize.Width;
                height = renderSize.Height;
            }
            else
            {
                renderSize = new Size(width, height);
            }

            var before = DateTime.UtcNow;

            Bitmap bitmap = new Bitmap(width, height);

            var task = Task.Run(() =>
                {

                    for (int x = 0; x < width; x++)
                    {
                        for (int y = 0; y < height; y++)
                        {
                            var viewPortX = ((2 * x) / (float)width) - 1;
                            var viewPortY = ((2 * y) / (float)height) - 1;
                            var color = TraceRayAgainstScene(GetRay(viewPortX, viewPortY), scene);
                            bitmap.SetPixel(x, height - y - 1, color);
                        }
                    }
                });

            await task;

            var after = DateTime.UtcNow;
            System.Diagnostics.Debug.WriteLine("Total render time: " + (after - before).TotalMilliseconds + " ms");
            return bitmap;
        }

        /// <summary>
        /// Renders the given scene, providing a callback for each individual line rendered. Each line is rendered on a separate thread.
        /// </summary>
        /// <param name="width">The width of the rendered image</param>
        /// <param name="width">The height of the rendered image</param>
        /// <param name="scene">The scene to render</param>
        /// <param name="callback">The delegate invoked when a thread completes rendering a line</param>
        public void RenderSceneLinesThreaded(Scene scene, int width, int height, LineFinishedHandler callback)
        {
            if (width == -1 || height == -1)
            {
                width = renderSize.Width;
                height = renderSize.Height;
            }
            else
            {
                renderSize = new Size(width, height);
            }

            var before = DateTime.UtcNow;
            List<Task> tasks = new List<Task>();

            for (int yCounter = height - 1; yCounter >= 0; yCounter--)
            {
                var y = yCounter;
                Color[] colors = new Color[width];
                Task.Run(() =>
                {
                    for (int xCounter = 0; xCounter < width; xCounter++)
                    {
                        var x = xCounter;
                        var viewPortX = ((2 * x) / (float)width) - 1;
                        var viewPortY = ((2 * y) / (float)height) - 1;
                        var color = TraceRayAgainstScene(GetRay(viewPortX, viewPortY), scene);
                        colors[x] = color;
                    }
                    callback(y, colors);
                });
            }

            var after = DateTime.UtcNow;
            System.Diagnostics.Debug.WriteLine("Total render time: " + (after - before).TotalMilliseconds + " ms");
        }

        /// <summary>
        /// Renders the given scene, providing a callback for each individual line rendered. Uses a single background thread.
        /// </summary>
        /// <param name="width">The width of the rendered image</param>
        /// <param name="height">The height of the rendered image</param>
        /// <param name="scene">The scene to render</param>
        /// <param name="callback">The delegate invoked when a thread completes rendering a line</param>
        public void RenderSceneLines(Scene scene, int width, int height, LineFinishedHandler callback)
        {
            if (width == -1 || height == -1)
            {
                width = renderSize.Width;
                height = renderSize.Height;
            }
            else
            {
                renderSize = new Size(width, height);
            }

            var before = DateTime.UtcNow;

            Task.Run(() => // Even single-threaded method should run in the background to avoid freezing UI.
                {
                    for (int y = height - 1; y >= 0; y--)
                    {
                        var colors = new Color[width];
                        for (int x = 0; x < width; x++)
                        {
                            var viewPortX = ((2 * x) / (float)width) - 1;
                            var viewPortY = ((2 * y) / (float)height) - 1;
                            var color = TraceRayAgainstScene(GetRay(viewPortX, viewPortY), scene);
                            colors[x] = color;
                        }
                        callback(y, colors);
                    }
                });
            var after = DateTime.UtcNow;
            System.Diagnostics.Debug.WriteLine("Total render time: " + (after - before).TotalMilliseconds + " ms");
        }

        private Color TraceRayAgainstScene(Ray ray, Scene scene)
        {
            Intersection intersection;
            if (TryCalculateIntersection(ray, scene, null, out intersection))
            {
                return CalculateRecursiveColor(intersection, scene, 0);
            }
            else
            {
                return scene.BackgroundColor;
            }
        }

        /// <summary>
        /// Recursive algorithm base
        /// </summary>
        /// <param name="intersection">The intersection the recursive step started from</param>
        /// <param name="ray">The ray, starting from the intersection</param>
        /// <param name="scene">The scene to trace</param>
        private Color CalculateRecursiveColor(Intersection intersection, Scene scene, int depth)
        {
            // Ambient light:
            var color = Color.Lerp(Color.Black, intersection.Color * scene.AmbientLightColor, scene.AmbientLightIntensity);

            foreach (Light light in scene.Lights)
            {
                var lightContribution = new Color();
                var towardsLight = (light.Position - intersection.Point).Normalized();
                var lightDistance = Util.Distance(intersection.Point, light.Position);

                // Accumulate diffuse lighting:
                var lightEffectiveness = Vector3.Dot(towardsLight, intersection.Normal);
                if (lightEffectiveness > 0.0f)
                {
                    lightContribution = lightContribution + (intersection.Color * light.GetIntensityAtDistance(lightDistance) * light.Color * lightEffectiveness);
                }

                // Render shadow
                var shadowRay = new Ray(intersection.Point, towardsLight);
                Intersection shadowIntersection;
                if (TryCalculateIntersection(shadowRay, scene, intersection.ObjectHit, out shadowIntersection) && shadowIntersection.Distance < lightDistance)
                {
                    var transparency = shadowIntersection.ObjectHit.Material.Transparency;
                    var lightPassThrough = Util.Lerp(.25f, 1.0f, transparency);
                    lightContribution = Color.Lerp(lightContribution, Color.Zero, 1 - lightPassThrough);
                }

                color += lightContribution;
            }

            if (depth < ReflectionDepth)
            {
                // Reflection ray
                var objectReflectivity = intersection.ObjectHit.Material.Reflectivity;
                if (objectReflectivity > 0.0f)
                {
                    var reflectionRay = GetReflectionRay(intersection.Point, intersection.Normal, intersection.ImpactDirection);
                    Intersection reflectionIntersection;
                    if (TryCalculateIntersection(reflectionRay, scene, intersection.ObjectHit, out reflectionIntersection))
                    {
                        color = Color.Lerp(color, CalculateRecursiveColor(reflectionIntersection, scene, depth + 1), objectReflectivity);
                    }
                }

                // Refraction ray
                var objectRefractivity = intersection.ObjectHit.Material.Refractivity;
                if (objectRefractivity > 0.0f)
                {
                    var refractionRay = GetRefractionRay(intersection.Point, intersection.Normal, intersection.ImpactDirection, objectRefractivity);
                    Intersection refractionIntersection;
                    if (TryCalculateIntersection(refractionRay, scene, intersection.ObjectHit, out refractionIntersection))
                    {
                        var refractedColor = CalculateRecursiveColor(refractionIntersection, scene, depth + 1);
                        color = Color.Lerp(color, refractedColor, 1 - (intersection.ObjectHit.Material.Opacity));
                    }
                }
            }

            color = color.Limited;
            return color;
        }

        /// <summary>
        /// Determines whether a given ray intersects with any scene objects (other than excludedObject)
        /// </summary>
        /// <param name="ray">The ray to test</param>
        /// <param name="scene">The scene to test</param>
        /// <param name="excludedObject">An object that is not tested for intersections</param>
        /// <param name="intersection">If the intersection test succeeds, contains the closest intersection</param>
        /// <returns>A value indicating whether or not any scene object intersected with the ray</returns>
        private bool TryCalculateIntersection(Ray ray, Scene scene, DrawableSceneObject excludedObject, out Intersection intersection)
        {
            var closestDistance = float.PositiveInfinity;
            var closestIntersection = new Intersection();
            foreach (var sceneObject in scene.DrawableObjects)
            {
                Intersection i;
                if (sceneObject != excludedObject && sceneObject.TryCalculateIntersection(ray, out i))
                {
                    if (i.Distance < closestDistance)
                    {

                        closestDistance = i.Distance;
                        closestIntersection = i;
                    }
                }
            }

            if (closestDistance == float.PositiveInfinity)
            {
                intersection = new Intersection();
                return false;
            }
            else
            {
                intersection = closestIntersection;
                return true;
            }
        }
    }

    public delegate void LineFinishedHandler(int rowNumber, Color[] lineColors);
}


text:
"""
Tests For Distributed Scheduler.
"""

import json

import nova.db

from nova import context
from nova import exception
from nova import rpc
from nova import test
from nova.compute import api as compute_api
from nova.scheduler import distributed_scheduler
from nova.scheduler import least_cost
from nova.scheduler import zone_manager
from nova.tests.scheduler import fake_zone_manager as ds_fakes

class FakeEmptyZoneManager(zone_manager.ZoneManager):
    def __init__(self):
        self.service_states = {}

    def get_host_list_from_db(self, context):
        return []

    def _compute_node_get_all(*args, **kwargs):
        return []

    def _instance_get_all(*args, **kwargs):
        return []

def fake_call_zone_method(context, method, specs, zones):
    return [
        (1, [
            dict(weight=2, blob='AAAAAAA'),
            dict(weight=4, blob='BBBBBBB'),
            dict(weight=6, blob='CCCCCCC'),
            dict(weight=8, blob='DDDDDDD'),
        ]),
        (2, [
            dict(weight=10, blob='EEEEEEE'),
            dict(weight=12, blob='FFFFFFF'),
            dict(weight=14, blob='GGGGGGG'),
            dict(weight=16, blob='HHHHHHH'),
        ]),
        (3, [
            dict(weight=18, blob='IIIIIII'),
            dict(weight=20, blob='JJJJJJJ'),
            dict(weight=22, blob='KKKKKKK'),
            dict(weight=24, blob='LLLLLLL'),
        ]),
    ]

def fake_zone_get_all(context):
    return [
        dict(id=1, api_url='zone1',
             username='admin', password='password',
             weight_offset=0.0, weight_scale=1.0),
        dict(id=2, api_url='zone2',
             username='admin', password='password',
             weight_offset=1000.0, weight_scale=1.0),
        dict(id=3, api_url='zone3',
             username='admin', password='password',
             weight_offset=0.0, weight_scale=1000.0),
    ]

class DistributedSchedulerTestCase(test.TestCase):
    """Test case for Distributed Scheduler."""

    def test_adjust_child_weights(self):
        """Make sure the weights returned by child zones are
        properly adjusted based on the scale/offset in the zone
        db entries.
        """
        sched = ds_fakes.FakeDistributedScheduler()
        child_results = fake_call_zone_method(None, None, None, None)
        zones = fake_zone_get_all(None)
        weighted_hosts = sched._adjust_child_weights(child_results, zones)
        scaled = [130000, 131000, 132000, 3000]
        for weighted_host in weighted_hosts:
            w = weighted_host.weight
            if weighted_host.zone == 'zone1':  # No change
                self.assertTrue(w < 1000.0)
            if weighted_host.zone == 'zone2':  # Offset +1000
                self.assertTrue(w >= 1000.0 and w < 2000)
            if weighted_host.zone == 'zone3':  # Scale x1000
                self.assertEqual(scaled.pop(0), w)

    def test_run_instance_no_hosts(self):
        """
        Ensure empty hosts & child_zones result in NoValidHosts exception.
        """
        def _fake_empty_call_zone_method(*args, **kwargs):
            return []

        sched = ds_fakes.FakeDistributedScheduler()
        sched.zone_manager = FakeEmptyZoneManager()
        self.stubs.Set(sched, '_call_zone_method',
                       _fake_empty_call_zone_method)
        self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)

        fake_context = context.RequestContext('user', 'project')
        request_spec = dict(instance_type=dict(memory_mb=1, local_gb=1))
        self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
                          fake_context, request_spec)

    def test_run_instance_with_blob_hint(self):
        """
        Check the local/child zone routing in the run_instance() call.
        If the zone_blob hint was passed in, don't re-schedule.
        """
        self.schedule_called = False
        self.from_blob_called = False
        self.locally_called = False
        self.child_zone_called = False

        def _fake_schedule(*args, **kwargs):
            self.schedule_called = True
            return least_cost.WeightedHost(1, host='x')

        def _fake_make_weighted_host_from_blob(*args, **kwargs):
            self.from_blob_called = True
            return least_cost.WeightedHost(1, zone='x', blob='y')

        def _fake_provision_resource_locally(*args, **kwargs):
            self.locally_called = True
            return 1

        def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
            self.child_zone_called = True
            return 2

        sched = ds_fakes.FakeDistributedScheduler()
        self.stubs.Set(sched, '_schedule', _fake_schedule)
        self.stubs.Set(sched, '_make_weighted_host_from_blob',
                       _fake_make_weighted_host_from_blob)
        self.stubs.Set(sched, '_provision_resource_locally',
                       _fake_provision_resource_locally)
        self.stubs.Set(sched, '_ask_child_zone_to_create_instance',
                       _fake_ask_child_zone_to_create_instance)
        request_spec = {
                'instance_properties': {},
                'instance_type': {},
                'filter_driver': 'nova.scheduler.host_filter.AllHostsFilter',
                'blob': "Non-None blob data",
            }

        fake_context = context.RequestContext('user', 'project')
        instances = sched.schedule_run_instance(fake_context, request_spec)
        self.assertTrue(instances)
        self.assertFalse(self.schedule_called)
        self.assertTrue(self.from_blob_called)
        self.assertTrue(self.child_zone_called)
        self.assertFalse(self.locally_called)
        self.assertEquals(instances, [2])

    def test_run_instance_non_admin(self):
        """Test creating an instance locally using run_instance, passing
        a non-admin context.  DB actions should work."""
        self.was_admin = False

        def fake_schedule(context, *args, **kwargs):
            # make sure this is called with admin context, even though
            # we're using user context below
            self.was_admin = context.is_admin
            return []

        sched = ds_fakes.FakeDistributedScheduler()
        self.stubs.Set(sched, '_schedule', fake_schedule)

        fake_context = context.RequestContext('user', 'project')

        self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
                          fake_context, {})
        self.assertTrue(self.was_admin)

    def test_schedule_bad_topic(self):
        """Parameter checking."""
        sched = ds_fakes.FakeDistributedScheduler()
        self.assertRaises(NotImplementedError, sched._schedule, None, "foo",
                          {})

    def test_schedule_no_instance_type(self):
        """Parameter checking."""
        sched = ds_fakes.FakeDistributedScheduler()
        self.assertRaises(NotImplementedError, sched._schedule, None,
                          "compute", {})

    def test_schedule_happy_day(self):
        """_schedule() has no branching logic beyond basic input parameter
        checking. Just make sure there's nothing glaringly wrong by doing
        a happy day pass through."""

        self.next_weight = 1.0

        def _fake_filter_hosts(topic, request_info, unfiltered_hosts,
                                                                options):
            return unfiltered_hosts

        def _fake_weighted_sum(functions, hosts, options):
            self.next_weight += 2.0
            host, hostinfo = hosts[0]
            return least_cost.WeightedHost(self.next_weight, host=host,
                                           hostinfo=hostinfo)

        sched = ds_fakes.FakeDistributedScheduler()
        fake_context = context.RequestContext('user', 'project')
        sched.zone_manager = ds_fakes.FakeZoneManager()
        self.stubs.Set(sched, '_filter_hosts', _fake_filter_hosts)
        self.stubs.Set(least_cost, 'weighted_sum', _fake_weighted_sum)
        self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
        self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method)

        instance_type = dict(memory_mb=512, local_gb=512)
        request_spec = dict(num_instances=10, instance_type=instance_type)
        weighted_hosts = sched._schedule(fake_context, 'compute',
                                         request_spec)
        self.assertEquals(len(weighted_hosts), 10)
        for weighted_host in weighted_hosts:
            # We set this up so remote hosts have even weights ...
            if int(weighted_host.weight) % 2 == 0:
                self.assertTrue(weighted_host.zone != None)
                self.assertTrue(weighted_host.host == None)
            else:
                self.assertTrue(weighted_host.host != None)
                self.assertTrue(weighted_host.zone == None)

    def test_decrypt_blob(self):
        """Test that the decrypt method works."""

        fixture = ds_fakes.FakeDistributedScheduler()
        test_data = {'weight': 1, 'host': 'x', 'blob': 'y', 'zone': 'z'}

        class StubDecryptor(object):
            def decryptor(self, key):
                return lambda blob: blob

        self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())

        weighted_host = fixture._make_weighted_host_from_blob(
                                                        json.dumps(test_data))
        self.assertTrue(isinstance(weighted_host, least_cost.WeightedHost))
        self.assertEqual(weighted_host.to_dict(), dict(weight=1, host='x',
                         blob='y', zone='z'))

    def test_get_cost_functions(self):
        fixture = ds_fakes.FakeDistributedScheduler()
        fns = fixture.get_cost_functions()
        self.assertEquals(len(fns), 1)
        weight, fn = fns[0]
        self.assertEquals(weight, 1.0)
        hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
        self.assertEquals(1000, fn(hostinfo))


text:
A [webpack](https://webpack.github.io/) plugin that starts and reloads [Nodemon](https://nodemon.io/) and [Browsersync](https://www.browsersync.io/).  It is useful when developing web applications that leverage both server-side rendered HTML pages and webpack bundles.

Initially based on [Va1/browser-sync-webpack-plugin](https://github.com/Va1/browser-sync-webpack-plugin)

## Installation
Install the plugin with npm:

```shell
$ npm install nodemon-browsersync-webpack-plugin --save-dev
```

## Usage

```shell
$ webpack --watch
```

### Basic

Pass [Nodemon options](https://github.com/remy/nodemon/blob/master/doc/requireable.md) and [BrowserSync options](https://browsersync.io/docs/options/) into the plugin in that order.

```javascript
const NodemonBrowsersyncPlugin = require('nodemon-browsersync-webpack-plugin');

module.exports = {
  entry: './src/js/entry.js',
  output: {
    path: './public/assets',
    filename: 'bundle.js'
  },
  plugins: [
    new NodemonBrowsersyncPlugin({
      script: 'server.js',
      ignore: [
          "src/*",
          "public/*"
      ],
      ext: 'js json',
      verbose: true
    }, {
      proxy: 'localhost:8001'
    )
  ]
};
```

In the example above, Browsersync will wrap your vhost with a _proxy_ URL to view your site.

*NOTE:* For reusabilty, a `nodemon.json` configuration file is recommended rather than embedding Nodemon options in the plugin.  Checkout the [sample nodemon.json](https://github.com/remy/nodemon/blob/master/doc/sample-nodemon.md) for further details.

## Contributing

Feel free to open issues to propose stuff and participate. Pull requests are also welcome.

## License

[MIT]()


text:
angular.module("umbraco")
    .controller("Umbraco.Editors.MediaEntryEditorController",
        function ($scope, localizationService, entityResource, editorService, overlayService, eventsService, mediaHelper) {

            var unsubscribe = [];

            const vm = this;

            vm.loading = true;
            vm.model = $scope.model;
            vm.mediaEntry = vm.model.mediaEntry;
            vm.currentCrop = null;
            vm.title = "";

            vm.focalPointChanged = focalPointChanged;
            vm.onImageLoaded = onImageLoaded;
            vm.openMedia = openMedia;
            vm.repickMedia = repickMedia;
            vm.selectCrop = selectCrop;
            vm.deselectCrop = deselectCrop;
            vm.resetCrop = resetCrop;
            vm.submitAndClose = submitAndClose;
            vm.close = close;

            function init() {

                localizationService.localizeMany([
                  vm.model.createFlow ? "general_cancel" : "general_close",
                  vm.model.createFlow ? "general_create" : "buttons_submitChanges"
                ]).then(data => {
                  vm.closeLabel = data[0];
                  vm.submitLabel = data[1];
                });

                updateMedia();

                unsubscribe.push(eventsService.on("editors.media.saved", function(name, args) {
                    // if this media item uses the updated media type we want to reload the media file
                    if(args && args.media && args.media.key === vm.mediaEntry.mediaKey) {
                        updateMedia();
                    }
                }));
            }

            function updateMedia() {

                vm.loading = true;

                entityResource.getById(vm.mediaEntry.mediaKey, "Media").then(function (mediaEntity) {
                    vm.media = mediaEntity;
                    vm.imageSrc = mediaHelper.resolveFileFromEntity(mediaEntity, true);
                    vm.loading = false;
                    vm.hasDimensions = false;
                    vm.isCroppable = false;

                    localizationService.localize("mediaPicker_editMediaEntryLabel", [vm.media.name, vm.model.documentName]).then(data => {
                        vm.title = data;
                    });
                }, function () {
                    localizationService.localize("mediaPicker_deletedItem").then(localized => {
                        vm.media = {
                            name: localized,
                            icon: "icon-picture",
                            trashed: true
                        };
                        vm.loading = false;
                        vm.hasDimensions = false;
                        vm.isCroppable = false;
                    });
                });
            }

            function onImageLoaded(isCroppable, hasDimensions) {
                vm.isCroppable = isCroppable;
                vm.hasDimensions = hasDimensions;
            }

            function repickMedia() {
                vm.model.propertyEditor.changeMediaFor(vm.model.mediaEntry, onMediaReplaced);
            }

            function onMediaReplaced() {

                // mark we have changes:
                vm.imageCropperForm.$setDirty();

                // un-select crop:
                vm.currentCrop = null;

                //
                updateMedia();
            }

            function openMedia() {

                const mediaEditor = {
                    id: vm.mediaEntry.mediaKey,
                    submit: () => {
                        editorService.close();
                    },
                    close: () => {
                        editorService.close();
                    }
                };

                editorService.mediaEditor(mediaEditor);
            }

            function focalPointChanged(left, top) {
                //update the model focalpoint value
                vm.mediaEntry.focalPoint = {
                    left: left,
                    top: top
                };

                //set form to dirty to track changes
                setDirty();
            }

            function selectCrop(targetCrop) {
                vm.currentCrop = targetCrop;
                setDirty();
                // TODO: start watchin values of crop, first when changed set to dirty.
            }

            function deselectCrop() {
                vm.currentCrop = null;
            }

            function resetCrop() {
                if (vm.currentCrop) {
                    $scope.$evalAsync( () => {
                        vm.model.propertyEditor.resetCrop(vm.currentCrop);
                        vm.forceUpdateCrop = Math.random();
                    });
                }
            }

            function setDirty() {
                vm.imageCropperForm.$setDirty();
            }

            function submitAndClose() {
                if (vm.model && vm.model.submit) {
                    vm.model.submit(vm.model);
                }
            }

            function close() {
                if (vm.model && vm.model.close)
                {
                    if (vm.model.createFlow === true || vm.imageCropperForm.$dirty === true)
                    {
                      const labelKeys = vm.model.createFlow === true
                          ? ["mediaPicker_confirmCancelMediaEntryCreationHeadline", "mediaPicker_confirmCancelMediaEntryCreationMessage"]
                          : ["prompt_discardChanges", "mediaPicker_confirmCancelMediaEntryHasChanges"];

                        localizationService.localizeMany(labelKeys).then(localizations => {
                            const confirm = {
                                title: localizations[0],
                                view: "default",
                                content: localizations[1],
                                submitButtonLabelKey: "general_discard",
                                submitButtonStyle: "danger",
                                closeButtonLabelKey: "prompt_stay",
                                submit: () => {
                                    overlayService.close();
                                    vm.model.close(vm.model);
                                },
                                close: () => {
                                    overlayService.close();
                                }
                            };
                            overlayService.open(confirm);
                        });
                    } else {
                        vm.model.close(vm.model);
                    }

                }
            }

            init();

            $scope.$on("$destroy", function () {
                unsubscribe.forEach(x => x());
            });

        }
    );


text:
export * from './numericals';
export * from './lcm_and_hcf';
export * from './work_and_time';
export * from './time_and_distance';


text:
{% extends "base.html" %}
{% block content %}

Create new text set

    <form action="" method="post" name="create" enctype="multipart/form-data">
        {{ form.hidden_tag() }}
        {{ form.csrf_token }}

            Name
            {{ form.name(class="form-control",
            placeholder="enter a unique name to identify the dataset")}}

            Description
            {{ form.description(class="form-control", rows=3,
            placeholder="enter the objective of this dataset and the meaning of data")}}

            Source
            {{ form.source(class="form-control",
            placeholder="origin or source of the dataset")}}

            URL
            {{ form.url(class="form-control",
            placeholder="url of the description dataset")}}

            Data access mode
            {{ form.mode_file(class="form-control", **{"onchange":"changeModeFile(this.value)"}) }}

            Text file

                {{ form.filename(class="form-control",
                placeholder="optional file with description of the columns")}}

                {{ form.file_text(class="form-control") }}

                    Cancel

                    <button class="btn btn-primary">Save</button>

    </form>

{% endblock %}


text:
from msrest.serialization import Model

class ResourceSkuCosts(Model):
    """Describes metadata for retrieving price info.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar meter_id: Used for querying price from commerce.
    :vartype meter_id: str
    :ivar quantity: The multiplier is needed to extend the base metered cost.
    :vartype quantity: long
    :ivar extended_unit: An invariant to show the extended unit.
    :vartype extended_unit: str
    """

    _validation = {
        'meter_id': {'readonly': True},
        'quantity': {'readonly': True},
        'extended_unit': {'readonly': True},
    }

    _attribute_map = {
        'meter_id': {'key': 'meterID', 'type': 'str'},
        'quantity': {'key': 'quantity', 'type': 'long'},
        'extended_unit': {'key': 'extendedUnit', 'type': 'str'},
    }

    def __init__(self):
        super(ResourceSkuCosts, self).__init__()
        self.meter_id = None
        self.quantity = None
        self.extended_unit = None


text:
package com.puppycrawl.tools.checkstyle.checks.javadoc;

import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.JAVADOC_MISSED_HTML_CLOSE;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.JAVADOC_WRONG_SINGLETON_TAG;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.PARSE_ERROR_MESSAGE_KEY;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.UNRECOGNIZED_ANTLR_ERROR_MESSAGE_KEY;

import org.junit.Test;

import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.TreeWalker;
import com.puppycrawl.tools.checkstyle.api.DetailNode;

public class AbstractJavadocCheckTest extends BaseCheckTestSupport {

    @Test
    public void testNumberFormatException() throws Exception {
        final DefaultConfiguration checkConfig = createCheckConfig(TempCheck.class);
        final String[] expected = {
            "3: " + getCheckMessage(PARSE_ERROR_MESSAGE_KEY, 52, "no viable "
                + "alternative at input '

a' {@link EntityEntry} (by way of {@link #;' "
                + "while parsing HTML_TAG"),
        };
        verify(checkConfig, getPath("javadoc/InputTestNumberFomatException.java"), expected);
    }

    @Test
    public void testCustomTag() throws Exception {
        final DefaultConfiguration checkConfig = createCheckConfig(TempCheck.class);
        final String[] expected = {
            "4: " + getCheckMessage(UNRECOGNIZED_ANTLR_ERROR_MESSAGE_KEY, 4, "null"),
        };
        verify(checkConfig, getPath("javadoc/InputCustomTag.java"), expected);
    }

    @Test
    public void testParsingErrors() throws Exception {
        final DefaultConfiguration checkConfig = createCheckConfig(TempCheck.class);
        final String[] expected = {
            "4: " + getCheckMessage(JAVADOC_MISSED_HTML_CLOSE, 4, "unclosedTag"),
            "8: " + getCheckMessage(JAVADOC_WRONG_SINGLETON_TAG, 35, "img"),
        };
        verify(checkConfig, getPath("javadoc/InputParsingErrors.java"), expected);
    }

    @Test
    public void testWithMultipleChecks() throws Exception {
        final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
        final DefaultConfiguration checksConfig = createCheckConfig(TreeWalker.class);
        checksConfig.addChild(createCheckConfig(AtclauseOrderCheck.class));
        checksConfig.addChild(createCheckConfig(JavadocParagraphCheck.class));
        checkerConfig.addChild(checksConfig);
        final Checker checker = new Checker();
        checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
        checker.configure(checkerConfig);

        final String[] expected = {
        };
        verify(checker, getPath("javadoc/InputCorrectJavaDocParagraphCheck.java"), expected);
    }

    public static class TempCheck extends AbstractJavadocCheck {

        @Override
        public int[] getDefaultJavadocTokens() {
            return null;
        }

        @Override
        public void visitJavadocToken(DetailNode ast) {
            // do nothing
        }
    }
}


text:
/*! \file ArrayContainer */

#ifndef ARRAY_CONTAINER_H
#define ARRAY_CONTAINER_H

#include "numlib-config.h"
#include "debug_tools.h"

namespace numlib{

//! A simple, generic, implementation of a resizable array
/*!
 *	This implements a very simple array container with the usual
 *	element access operators and iterators. This container is
 *	a compliment to the standard STL containers in that it
 *	assumes the array size remains fixed once initialized. This
 *	assumption allows this container to be very lightweight
 *	and implement fast iterators and element lookup.
 *
 *	If you need dynamic resizing (e.g. element insertion, deletion, etc)
 *	then you should use one of the STL containers. STL containers are
 *	very well designed, and some compilers can better optimize STL containers
 *	since they can safely make assumptions regarding their usage.
 *
 *	This class does not provide any arithmetic operators or related member
 *	functions. The purpose of this class is limited to memory management and
 *	element access. However, this class may be used as a foundation for
 *	defining numerical arrays and other field types.
 *
 */
template<class T>
class ArrayContainer
{
protected:

	T* data; //*!< internal data array */

	Size n; //*!< number of elements in the array */

	//! Bidirectional iterator template
	template<class NodeType>
	class IteratorBase
	{
	public:

		//! Constructs a non-associated iterator
		IteratorBase():d_ptr(NULL){}

		//! Constructs an iterator and associates it with the address `start'
		IteratorBase(T* start):d_ptr(start){}

		//! Copies internal reference (shallow copy)
		IteratorBase(const IteratorBase& other){ d_ptr = other.d_ptr; }

		~IteratorBase(){}

		//! Assigns internal ref held by `other' iterator (shallow copy)
		IteratorBase& operator=(const IteratorBase& other)
		{
			if(&other==this) return *this;
			d_ptr = other.d_ptr;
			return *this;
		}

		//! Comparison operator; true when both iterators point to the same element
		bool operator==(const IteratorBase& other) const { return d_ptr==other.d_ptr; }

		//! Returns false when both iterators point to the same element
		bool operator!=(const IteratorBase& other) const {return d_ptr!=other.d_ptr; }

		//! pre-fix increment: ++it
		IteratorBase& operator++()
		{
			ASSERT(d_ptr);
			++d_ptr;
			return *this;
		}

		//! pre-fix decriment: --it
		IteratorBase& operator--()
		{
			ASSERT(d_ptr);
			--d_ptr;
			return *this;
		}

		//! post-fix increment: it++
		IteratorBase operator++(int)
		{
			IteratorBase tmp(*this);
			++(*this);
			return tmp;
		}

		//! post-fix decriment: it--
		IteratorBase operator--(int)
		{
			ASSERT(d_ptr);
			IteratorBase tmp(*this);
			--(*this);
			return *this;
		}

		//! Dereference operator
		NodeType& operator*()
		{
			ASSERT(d_ptr);
			return *d_ptr;
		}

	private:

		NodeType* d_ptr;

	};

public:

	typedef T ValueType;
	typedef IteratorBase<T>       Iterator;
	typedef IteratorBase<const T> ConstIterator;

	/*------------------------------------------------------------------------*/
	/*                                         INITIALIZATION AND DUPLICATION */

	//! Initializes an array for n elements (default 0)
	ArrayContainer(const Size size=0):
		n(size),
		data(NULL)
	{
		data = new T[n];
	}

	//! Deep copy initialization
	ArrayContainer(const ArrayContainer& other):data(NULL)
	{
		ASSERT( other.data );
		n = other.n;
		data = new T[n];
		for(Index i=0; i<n; ++i)
			data[i] = other.data[i];
	}

	virtual
	~ArrayContainer()
	{
		delete[] data;
	}

	//! Deep copy assignment
	ArrayContainer& operator=(const ArrayContainer& other)
	{
		if(&other==this) return *this;
		// Free old data...
		n = other.n;
		delete[] data;
		// Allocate memory for new data...
		n = other.n;
		data = new T[n];
		// Copy data over from other...
		for(Index i=0; i<n; ++i)
			data[i] = other.data[i];
		// Return reference to this object...
		return *this;
	}

	/*------------------------------------------------------------------------*/
	/*                                                         ELEMENT ACCESS */

	//! Returns number of elements in the array
	const Size size() const {return n;}

	//! Resizes the array to hold n elements
	/*!
	 *	This does not preserve contents!
	 */
	void resize(const Size size)
	{
		delete[] data;
		n = size;
		data = new T[n];
	}

	//! Mutable element access
	T& operator()(const Index i)
	{
		ASSERT( i < n );
		return data[i];
	}

	//! Immutable element access
	const T& operator()(const Index i) const
	{
		ASSERT( i < n );
		return data[i];
	}

	//! Returns iterator pointing to the first element
	Iterator begin() {return Iterator(data);}

	//! Returns an iterator pointing to +1 past end
	Iterator end() {return Iterator(data+n);}

	//! Returns an iterator pointing to the last element
	Iterator rbegin() {return Iterator(data+n-1);}

	//! Returns an iterator pointing to +1 before the first element
	Iterator rend() {return Iterator(data-1);}

	//! Returns const iterator pointing to the first element
	ConstIterator begin() const {return ConstIterator(data);}

	//! Returns const iterator pointing to +1 past end
	ConstIterator end() const {return ConstIterator(data+n);}

	//! Returns const iterator pointing to the last element
	ConstIterator rbegin() const {return ConstIterator(data+n-1);}

	//! Returns const iterator pointing to +1 before the first element
	ConstIterator rend() const {return ConstIterator(data-1);}

};

}//::numlib

#endif


text:
namespace ITravex.Client
{
    using System;
    using System.Collections.Generic;

    public partial class ImageBinaryExtension
    {
        public long ID { get; set; }
        public long BinaryID { get; set; }
        public byte[] Data { get; set; }
        public short Width { get; set; }
        public short Height { get; set; }
    }
}


text:
"""Fichier contenant l'action eteindre."""

from primaires.scripting.action import Action
from primaires.scripting.instruction import ErreurExecution

class ClasseAction(Action):

    """Eteint la lumière d'une salle"""

    @classmethod
    def init_types(cls):
        cls.ajouter_types(cls.eteindre_salle, "Salle")

    @staticmethod
    def eteindre_salle(salle):
        """Éteint la lumière d'une salle.

        Paramètres à préciser :

          * salle : la salle qui doit voir son illumination désactivée

        Cette fonction éteint une salle, c'est-à-dire modifie
        son flag 'illuminée'. Si la salle n'est pas illuminée, rien
        ne sera fait. Une salle illuminée peut être vue par tous,
        qu'ils aient des torches ou non. En combinaison avec l'action
        'allumer', cette action permet de faire varier le flag
        illuminée d'une salle, ce qui peut être utile par exemple
        si un marchand entre dans son magasin au matin et
        allume les lampes.

        NOTE : cette action ne modifie pas le statut des personnages
        présents. Ils pourront toujours s'éclairer grâce à des torches,
        des sorts ou autre. Si ils sont nyctalopes, ils y verront
        toujours. Si il y a un feu dans la salle, le feu continuera
        d'éclairer les lieux.

        Exemple d'utilisation :

          eteindre salle

        """
        salle.illuminee = False


text:
namespace SynoDuplicateFolders.Controls
{
    partial class VolumeHistoricChart
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            //
            // chart1
            //
            chartArea1.Name = "ChartArea1";
            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(0, 0);
            this.chart1.Name = "chart1";
            series1.ChartArea = "ChartArea1";
            series1.Legend = "Legend1";
            series1.Name = "Series1";
            this.chart1.Series.Add(series1);
            this.chart1.Size = new System.Drawing.Size(1030, 576);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            this.chart1.GetToolTipText += new System.EventHandler<System.Windows.Forms.DataVisualization.Charting.ToolTipEventArgs>(this.chart1_GetToolTipText);
            this.chart1.PostPaint += new System.EventHandler<System.Windows.Forms.DataVisualization.Charting.ChartPaintEventArgs>(this.chart1_PostPaint);
            this.chart1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.chart1_MouseClick);
            //
            // VolumeHistoricChart
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.chart1);
            this.Name = "VolumeHistoricChart";
            this.Size = new System.Drawing.Size(1030, 576);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataVisualization.Charting.Chart chart1;
    }
}


text:
#ifndef MODULES_AUDIO_CODING_NETEQ_CROSS_CORRELATION_H_
#define MODULES_AUDIO_CODING_NETEQ_CROSS_CORRELATION_H_

#include "common_types.h"  // NOLINT(build/include)

namespace webrtc {

// The function calculates the cross-correlation between two sequences
// |sequence_1| and |sequence_2|. |sequence_1| is taken as reference, with
// |sequence_1_length| as its length. |sequence_2| slides for the calculation of
// cross-correlation. The result will be saved in |cross_correlation|.
// |cross_correlation_length| correlation points are calculated.
// The corresponding lag starts from 0, and increases with a step of
// |cross_correlation_step|. The result is without normalization. To avoid
// overflow, the result will be right shifted. The amount of shifts will be
// returned.
//
// Input:
//     - sequence_1     : First sequence (reference).
//     - sequence_2     : Second sequence (sliding during calculation).
//     - sequence_1_length : Length of |sequence_1|.
//     - cross_correlation_length : Number of cross-correlations to calculate.
//     - cross_correlation_step : Step in the lag for the cross-correlation.
//
// Output:
//      - cross_correlation : The cross-correlation in Q(-right_shifts)
//
// Return:
//      Number of right shifts in cross_correlation.

int CrossCorrelationWithAutoShift(const int16_t* sequence_1,
                                  const int16_t* sequence_2,
                                  size_t sequence_1_length,
                                  size_t cross_correlation_length,
                                  int cross_correlation_step,
                                  int32_t* cross_correlation);

}  // namespace webrtc

#endif  // MODULES_AUDIO_CODING_NETEQ_CROSS_CORRELATION_H_


text:
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash's](https://lodash.com/) internal `baseDifference` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.

## Installation

Using npm:

```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash._basedifference
```

In Node.js/io.js:

```js
var baseDifference = require('lodash._basedifference');
```

See the [package source](https://github.com/lodash/lodash/blob/3.0.2-npm-packages/lodash._basedifference) for more details.