text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Chi-Square Test for the Standard Deviation</title>
<link rel="stylesheet" href="../../../../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../index.html" title="Math Toolkit 1.9.0">
<link rel="up" href="../cs_eg.html" title="Chi Squared Distribution Examples">
<link rel="prev" href="chi_sq_intervals.html" title="Confidence Intervals on the Standard Deviation">
<link rel="next" href="chi_sq_size.html" title="Estimating the Required Sample Sizes for a Chi-Square Test for the Standard Deviation">

Home
Libraries
People
FAQ
More

Chi-Square
          Test for the Standard Deviation

            We use this test to determine whether the standard deviation of a sample
            differs from a specified value. Typically this occurs in process change
            situations where we wish to compare the standard deviation of a new process
            to an established one.

            The code for this example is contained in chi_square_std_dev_test.cpp,
            and we'll begin by defining the procedure that will print out the test
            statistics:

void chi_squared_test(
    double Sd,     // Sample std deviation
    double D,      // True std deviation
    unsigned N,    // Sample size
    double alpha)  // Significance level
{

            The procedure begins by printing a summary of the input data:

using namespace std;
using namespace boost::math;

// Print header:
cout <<
   "______________________________________________\n"
   "Chi Squared test for sample standard deviation\n"
   "______________________________________________\n\n";
cout << setprecision(5);
cout << setw(55) << left << "Number of Observations" << "=  " << N << "\n";
cout << setw(55) << left << "Sample Standard Deviation" << "=  " << Sd << "\n";
cout << setw(55) << left << "Expected True Standard Deviation" << "=  " << D << "\n\n";

            The test statistic (T) is simply the ratio of the sample and "true"
            standard deviations squared, multiplied by the number of degrees of freedom
            (the sample size less one):

double t_stat = (N - 1) * (Sd / D) * (Sd / D);
cout << setw(55) << left << "Test Statistic" << "=  " << t_stat << "\n";

            The distribution we need to use, is a Chi Squared distribution with N-1
            degrees of freedom:

chi_squared dist(N - 1);

            The various hypothesis that can be tested are summarised in the following
            table:

<colgroup>
<col>
<col>
</colgroup>

                      Hypothesis

                      Test

                      The null-hypothesis: there is no difference in standard deviation
                      from the specified value

                      Reject if T < χ2(1-alpha/2; N-1) or T > χ2(alpha/2; N-1)

                      The alternative hypothesis: there is a difference in standard
                      deviation from the specified value

                      Reject if χ2(1-alpha/2; N-1) >= T >= χ2(alpha/2; N-1)

                      The alternative hypothesis: the standard deviation is less
                      than the specified value

                      Reject if χ2(1-alpha; N-1) <= T

                      The alternative hypothesis: the standard deviation is greater
                      than the specified value

                      Reject if χ2(alpha; N-1) >= T

            Where χ2(alpha; N-1) is the upper critical value of the Chi Squared distribution,
            and χ2(1-alpha; N-1) is the lower critical value.

            Recall that the lower critical value is the same as the quantile, and
            the upper critical value is the same as the quantile from the complement
            of the probability, that gives us the following code to calculate the
            critical values:

double ucv = quantile(complement(dist, alpha));
double ucv2 = quantile(complement(dist, alpha / 2));
double lcv = quantile(dist, alpha);
double lcv2 = quantile(dist, alpha / 2);
cout << setw(55) << left << "Upper Critical Value at alpha: " << "=  "
   << setprecision(3) << scientific << ucv << "\n";
cout << setw(55) << left << "Upper Critical Value at alpha/2: " << "=  "
   << setprecision(3) << scientific << ucv2 << "\n";
cout << setw(55) << left << "Lower Critical Value at alpha: " << "=  "
   << setprecision(3) << scientific << lcv << "\n";
cout << setw(55) << left << "Lower Critical Value at alpha/2: " << "=  "
   << setprecision(3) << scientific << lcv2 << "\n\n";

            Now that we have the critical values, we can compare these to our test
            statistic, and print out the result of each hypothesis and test:

cout << setw(55) << left <<
   "Results for Alternative Hypothesis and alpha" << "=  "
   << setprecision(4) << fixed << alpha << "\n\n";
cout << "Alternative Hypothesis              Conclusion\n";

cout << "Standard Deviation != " << setprecision(3) << fixed << D << "            ";
if((ucv2 < t_stat) || (lcv2 > t_stat))
   cout << "ACCEPTED\n";
else
   cout << "REJECTED\n";

cout << "Standard Deviation  < " << setprecision(3) << fixed << D << "            ";
if(lcv > t_stat)
   cout << "ACCEPTED\n";
else
   cout << "REJECTED\n";

cout << "Standard Deviation  > " << setprecision(3) << fixed << D << "            ";
if(ucv < t_stat)
   cout << "ACCEPTED\n";
else
   cout << "REJECTED\n";
cout << endl << endl;

            To see some example output we'll use the gear
            data from the NIST/SEMATECH
            e-Handbook of Statistical Methods.. The data represents measurements
            of gear diameter from a manufacturing process. The program output is
            deliberately designed to mirror the DATAPLOT output shown in the NIST
            Handbook Example.

______________________________________________
Chi Squared test for sample standard deviation
______________________________________________

Number of Observations                                 =  100
Sample Standard Deviation                              =  0.00628
Expected True Standard Deviation                       =  0.10000

Test Statistic                                         =  0.39030
CDF of test statistic:                                 =  1.438e-099
Upper Critical Value at alpha:                         =  1.232e+002
Upper Critical Value at alpha/2:                       =  1.284e+002
Lower Critical Value at alpha:                         =  7.705e+001
Lower Critical Value at alpha/2:                       =  7.336e+001

Results for Alternative Hypothesis and alpha           =  0.0500

Alternative Hypothesis              Conclusion
Standard Deviation != 0.100            ACCEPTED
Standard Deviation  < 0.100            ACCEPTED
Standard Deviation  > 0.100            REJECTED

            In this case we are testing whether the sample standard deviation is
            0.1, and the null-hypothesis is rejected, so we conclude that the standard
            deviation is not 0.1.

            For an alternative example, consider the silicon
            wafer data again from the NIST/SEMATECH
            e-Handbook of Statistical Methods.. In this scenario a supplier
            of 100 ohm.cm silicon wafers claims that his fabrication process can
            produce wafers with sufficient consistency so that the standard deviation
            of resistivity for the lot does not exceed 10 ohm.cm. A sample of N =
            10 wafers taken from the lot has a standard deviation of 13.97 ohm.cm,
            and the question we ask ourselves is "Is the suppliers claim correct?".

            The program output now looks like this:

______________________________________________
Chi Squared test for sample standard deviation
______________________________________________

Number of Observations                                 =  10
Sample Standard Deviation                              =  13.97000
Expected True Standard Deviation                       =  10.00000

Test Statistic                                         =  17.56448
CDF of test statistic:                                 =  9.594e-001
Upper Critical Value at alpha:                         =  1.692e+001
Upper Critical Value at alpha/2:                       =  1.902e+001
Lower Critical Value at alpha:                         =  3.325e+000
Lower Critical Value at alpha/2:                       =  2.700e+000

Results for Alternative Hypothesis and alpha           =  0.0500

Alternative Hypothesis              Conclusion
Standard Deviation != 10.000            REJECTED
Standard Deviation  < 10.000            REJECTED
Standard Deviation  > 10.000            ACCEPTED

            In this case, our null-hypothesis is that the standard deviation of the
            sample is less than 10: this hypothesis is rejected in the analysis above,
            and so we reject the manufacturers claim.

Copyright © 2006-2010, 2012, 2013 Nikhar Agrawal, Anton Bikineev,
      Paul A. Bristow, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock,
      Johan Råde, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker
      and Xiaogang Zhang

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
import numpy as np

readfile = open("example-1-results.txt", 'r')
workfile = open("workfile.txt", "w")

dims = (1, 1, 5)

pressureData = np.loadtxt(readfile)

pressureDist = pressureData[23].reshape(dims)

newPressureDist = np.zeros(dims, dtype=float)

for zIndx in range(dims[0]):
    newPressureDist[zIndx] = pressureDist[dims[0]-zIndx-1]

print(pressureDist)

printThis = "["

for i in range(1000):
    printThis += "3000"
    if(i < 1000-1):
        printThis += ", "

printThis += "];"

print(newPressureDist.reshape(dims[0]*dims[1]*dims[2]).__str__(), file=workfile)

workfile.close()
readfile.close()

redpajama_set_name: RedPajamaGithub


text:
@implementation SMContentLabel

- (instancetype)init {
    if (self = [super init]) {
        self.font = [SMStyle fontNormal];
    }
    return self;
}

@end


text:
/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 */
package org.eclipse.ceylon.ant;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Commandline;

public class CeylonP2AntTask extends OutputRepoUsingCeylonAntTask {

    static final String FAIL_MSG = "P2 generation failed; see the error output for details.";

    private final ModuleSet moduleSet = new ModuleSet();
    private String categories;
    private String categoryPrefix;
    private String repositoryName;
    private boolean verbose;

    public CeylonP2AntTask() {
        super("p2");
    }

    public boolean getVerbose() {
        return verbose;
    }

    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    public void setCategories(String categories){
        this.categories = categories;
    }

    public String getCategories(){
        return categories;
    }

    public void setRepositoryName(String repositoryName){
        this.repositoryName = repositoryName;
    }

    public String getRepositoryName(){
        return repositoryName;
    }

    public void setCategoryPrefix(String categoryPrefix){
        this.categoryPrefix = categoryPrefix;
    }

    public String getCategoryPrefix(){
        return categoryPrefix;
    }

    public void addConfiguredModuleSet(ModuleSet moduleset) {
        this.moduleSet.addConfiguredModuleSet(moduleset);
    }

    /**
     * Adds a module to compile
     * @param module the module name to compile
     */
    public void addConfiguredModule(Module module) {
        this.moduleSet.addConfiguredModule(module);
    }

    public void addConfiguredSourceModules(SourceModules sourceModules) {
        this.moduleSet.addConfiguredSourceModules(sourceModules);
    }

    /**
     * Check that all required attributes have been set and nothing silly has
     * been entered.
     *
     * @exception BuildException if an error occurs
     */
    protected void checkParameters() throws BuildException {
        if (this.moduleSet.getModules().isEmpty()) {
            throw new BuildException("You must specify a <module> or <moduleset>");
        }
    }

    /**
     * Perform the compilation.
     */
    protected void completeCommandline(Commandline cmd) {
        super.completeCommandline(cmd);

        if (verbose) {
            appendOption(cmd, "--verbose");
        }
        if (categories != null) {
            appendOptionArgument(cmd, "--categories", getCategories());
        }
        if (categoryPrefix != null) {
            appendOptionArgument(cmd, "--category-prefix", getCategoryPrefix());
        }
        if (repositoryName != null) {
            appendOptionArgument(cmd, "--repository-name", getRepositoryName());
        }

        for (Module module : moduleSet.getModules()) {
            log("Adding module: "+module, Project.MSG_VERBOSE);
            cmd.createArgument().setValue(module.toSpec());
        }
    }

    @Override
    protected String getFailMessage() {
        return FAIL_MSG;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Globalization;
using NumericalCalculator.Translations;
using NumericalCalculator.Logic;

namespace NumericalCalculator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowLogic logic;

        public MainWindow()
        {
            InitializeComponent();

            //Utworzenie logiki
            ObjectDataProvider odp = (ObjectDataProvider)Application.Current.Resources.MergedDictionaries.Where(s => s.Source.OriginalString == "Resources.xaml").Single()["Language"];

            logic = new MainWindowLogic(this, odp);

            //Poustawianie GUI
            logic.RadioButtonChanged();

            //Data context
            pnlMainWindow.DataContext = logic;

            //Focus na funkcji
            txtFunction.Focus();
        }

        private void miClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void miMean_Click(object sender, RoutedEventArgs e)
        {
            MeanWindow mw = new MeanWindow();
            mw.Show();
        }

        private void miGraph_Click(object sender, RoutedEventArgs e)
        {

        }

        private void miLanguage_Click(object sender, RoutedEventArgs e)
        {
            Translation.ToggleLanguage();
        }

        private void miClick_OpenWindow(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;

            //Wybranie okna
            Window window = null;

            if (mi.Name == miLinearEquations.Name)
                window = new LinearEquationWindow();
            else if (mi.Name == miInterpolation.Name)
            {
                window = new InterpolationWindow();
                (window as InterpolationWindow).FunctionAccepted += new InterpolationWindow.FunctionAcceptedEventHandler(MainWindow_FunctionAccepted);
            }
            else if (mi.Name == miProportion.Name)
                window = new ProportionWindow();
            else if (mi.Name == miMean.Name)
                window = new MeanWindow();
            else if (mi.Name == miAbout.Name)
                window = new AboutWindow();
            else if (mi.Name == miFunctions.Name)
                window = new FunctionsWindow();

            //Pokazanie okna
            if (window != null)
                window.Show();
        }

        void MainWindow_FunctionAccepted(string function)
        {
            txtFunction.Text = function;
        }

        private void btnSpecialFunction_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(Translation.GetString("MessageBox_btnSpecialFunction_Click"), Translation.GetString("MessageBox_btnSpecialFunction_Click_Caption"), MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btnHelp_Click(object sender, RoutedEventArgs e)
        {
            FunctionsWindow fw = new FunctionsWindow();
            fw.Show();
        }

        private void rb_Clicked(object sender, RoutedEventArgs e)
        {
            if (logic != null)
                logic.RadioButtonChanged();
        }

        private void cmbSpecialFunction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (logic != null)
                logic.ComboSpecialChanged();
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            logic.ClearGraph();
        }

        private void btnCompute_Click(object sender, RoutedEventArgs e)
        {
            logic.Compute();
        }

        private void btnDraw_Click(object sender, RoutedEventArgs e)
        {
            logic.DrawGraph();
        }

        //Przesuwanie wykresu
        private void picGraph_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && (!string.IsNullOrEmpty(logic.Function) || rbSpecialFunction.IsChecked.GetValueOrDefault(false)))
            {
                logic.startingPoint = e.GetPosition(picGraph);
                logic.graphMovingStarted = true;
            }
        }

        private void picGraph_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && logic.graphMovingStarted && (!string.IsNullOrEmpty(logic.Function) || rbSpecialFunction.IsChecked.GetValueOrDefault(false)))
            {
                if (!NumericalCalculator.Properties.Settings.Default.chkMiGraphPreviewMoving_Checked)
                    logic.ChartMouseMove(e.GetPosition(picGraph));

                logic.graphMovingStarted = false;
                logic.endPoint = e.GetPosition(picGraph);
            }
        }

        private void picGraph_MouseMove(object sender, MouseEventArgs e)
        {
            if (NumericalCalculator.Properties.Settings.Default.chkMiGraphPreviewMoving_Checked)
                logic.ChartMouseMove(e.GetPosition(picGraph));
        }

        private void picGraph_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            logic.ChartMouseWheel(e.Delta);
        }

        private void picGraph_MouseLeave(object sender, MouseEventArgs e)
        {
            if (logic.graphMovingStarted && (!string.IsNullOrEmpty(logic.Function) || rbSpecialFunction.IsChecked.GetValueOrDefault(false)))
            {
                logic.graphMovingStarted = false;
                logic.endPoint = e.GetPosition(picGraph);
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (logic.IsFunctionDrawn && NumericalCalculator.Properties.Settings.Default.chkMiGraphPreviewScaling_Checked)
                logic.DrawGraph(false);
            else
                logic.ClearGraph();
        }

        private void txtFunction_TextChanged(object sender, TextChangedEventArgs e)
        {
            logic.IsFunctionDrawn = false;
        }

        private void txtFrom_TextChanged(object sender, TextChangedEventArgs e)
        {
            logic.ConditionIIPoint.Text = logic.ConditionPoint.Text;
        }

        private void cmClick_SaveAsText(object sender, RoutedEventArgs e)
        {
            logic.ChartToText();
        }

        private void cmClick_Save(object sender, RoutedEventArgs e)
        {
            logic.ChartToFile();
        }

        private void cmClick_Copy(object sender, RoutedEventArgs e)
        {
            logic.ChartToClipboard();
        }
    }
}


text:
<?php

namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\Extension;

use Symfony\Component\HttpFoundation\Request;

use Oro\Component\Layout\LayoutContext;

use Oro\Bundle\LayoutBundle\Layout\Extension\RouteContextConfigurator;

class RouteContextConfiguratorTest extends \PHPUnit_Framework_TestCase
{
    /** @var RouteContextConfigurator */
    protected $configurator;

    protected function setUp()
    {
        $this->configurator = new RouteContextConfigurator();
    }

    protected function tearDown()
    {
        unset($this->configurator);
    }

    public function testConfigureContextWithOutRequest()
    {
        $context = new LayoutContext();

        $this->configurator->configureContext($context);

        $context->resolve();
        $this->assertSame(null, $context->get('route_name'));
    }

    public function testConfigureContextWithRequest()
    {
        $context = new LayoutContext();

        $request = Request::create('');
        $request->attributes->set('_route', 'testRoteName');

        $this->configurator->setRequest($request);
        $this->configurator->configureContext($context);

        $context->resolve();
        $this->assertSame('testRoteName', $context->get('route_name'));
    }

    public function testConfigureContextWithSubRequest()
    {
        $context = new LayoutContext();

        $request = Request::create('');
        $request->attributes->set('_master_request_route', 'testRoteName');

        $this->configurator->setRequest($request);
        $this->configurator->configureContext($context);

        $context->resolve();
        $this->assertSame('testRoteName', $context->get('route_name'));
    }

    public function testConfigureContextWithRequestAndDataSetInContext()
    {
        $context = new LayoutContext();
        $context->set('route_name', 'routeShouldNotBeOverridden');

        $request = Request::create('');
        $request->attributes->set('_route', 'testRoteName');

        $this->configurator->setRequest($request);
        $this->configurator->configureContext($context);

        $context->resolve();
        $this->assertSame('routeShouldNotBeOverridden', $context->get('route_name'));
    }

    public function testRequestSetterSynchronized()
    {
        $request = Request::create('');

        $this->configurator->setRequest($request);
        $this->configurator->setRequest(null);
    }
}


text:
//-----------------------------------------------------------------------------

#ifndef TRAIN_NODE_HPP
#define TRAIN_NODE_HPP

#include "prop.hpp"

namespace drvq {

using namespace ivl;
using namespace std;
using ivl::min;
using ivl::max;
using ivl::find;
using ivl::rand;

//-----------------------------------------------------------------------------

template <typename T>
class train_node : public node <T>, public train_tree <T>
{
	typedef typename tree <T>::lab lab;                 // label type
	typedef typename tree <T>::pos pos;                 // position type
	typedef typename tree <T>::data data;               // data type
	typedef typename train_tree <T>::count count;       // count type
	typedef typename train_tree <T>::book book;         // codeword type
	typedef sample_search_generator <count> generator;  // random generator type

	const size_t D, D0, D1, L;        // dimensions, child dimensions, level
	using node <T>::K;                // number of centroids
	using node <T>::J;                // number of children centroids
	using node <T>::dim0;             // left child dimension ranges
	using node <T>::dim1;             // right child dimension ranges
	train_tree <T> *child0, *child1;  // children
	array <array <T> > cen;           // centroids (vectors)
	using node <T>::code0;            // positions of left centroids on grid
	using node <T>::code1;            // positions of right centroids on grid
	using node <T>::source;           // centroid label per bin
	using node <T>::edge;             // edges between neighboring centroids
	using node <T>::weight;           // edge weights
	array <lab> label;                // centroid label per data point

	// temporary
	array_2d <count> b_pop;           // population per bin
	array_2d <T> distance;            // distance from centroid on grid
	generator gen;                    // random sample generator
	array_2d <char> chosen;           // is each bin chosen as a sample?  // TODO: char -> bool

//-----------------------------------------------------------------------------

	void train
	(
		const data& X,          // data points
		const size_array& at,   // dimension range
		const train_options& opt  // training options
	)
	{
		// trivial cases
		if(K < 2) return;

		// recurse
		// TODO: X, at[dim_] -> X[dim_]
		child0 = drvq::train(X, at[dim0], opt);
		child1 = drvq::train(X, at[dim1], opt);
		node <T>::child0 = static_cast <tree <T>*> (child0);
		node <T>::child1 = static_cast <tree <T>*> (child1);

		// children centroids
		const array <array <T> > &cen0 = child0 -> centroids(),
		                         &cen1 = child1 -> centroids();

		bool detail = J >= 512;                // detailed messages
		msg::level(info, L, at, K, J, detail);
		msg::nl(info, detail);

		// initialize
		if (detail) msg::in_line(info, "initializing");
		const size_t B = J * J;                // number of bins on grid
		const size_array grid = idx(J, J);     // grid dimensions
		size_array zero, nz;                   // empty and non-empty bins

		// quantize data points into bins
		array <count> pop(K, 1);               // population per centroid
		b_pop.init(grid, count(0));            // population per bin
		array <pos> code =                     // nearest bin per data point
			(child0 -> labels()) + J * (child1 -> labels());
		b_pop[code]++;
		size_array dom = find(b_pop);          // domain to visit

		// initialize centroids
		cen.init(D);                           // centroids (vectors)
		for (size_t d = 0; d < D; d++)
			cen[d].init(K, T());
		gen = sample_search(b_pop);            // generator on bin distribution
		chosen.init(grid, false);              // is each bin chosen as a sample?
		sample();

		// initialize assignments
		assign(true, types::t_false(), opt, detail);
		array_2d <lab> prev = source;          // bin labels @ previous iteration

		for (size_t it = 0; ; it++)
		{
			if (detail) msg::iter(info, it);

			// update populations
			pop[_] = 0;
			pop[source[dom]] += b_pop[dom];
			(_, zero, nz) = split++(pop == count(0));

			// update centroids
			for (size_t d = 0; d < D; d++)
			{
				cen[d][nz] = T();
				if (d < D0) cen[d][source[dom]] += b_pop[dom] * cen0[d]     [dom % J];
				else        cen[d][source[dom]] += b_pop[dom] * cen1[d - D0][dom / J];
			}
			for (size_t d = 0; d < D; d++)
				cen[d][nz] /= pop[nz];

			// re-sample empty centroids
			sample(zero);

			// update assignments
			assign(false, types::t_false(), opt, detail);

			// OPTIONAL: total distortion (sum of square residuals)
			// T distortion = sum(b_pop * distance);

			// terminate?
			double ratio = opt.theta * _[it * .01] ->* 2;
			if (find((source != prev)[dom]).length() < dom.length() * ratio)
			{
				if (!detail) msg::term(info, it);
				break;
			}
			prev = source;
		}

		if (detail) msg::in_line(info, "terminating");

		// re-sample empty centroids
		sample(zero);

		// re-assign, generating edges, and check for empty
		assign(true, types::t_true(), opt, detail);
		msg::zero(check, K, source[dom], b_pop[dom]);
		if (detail) msg::edge(check, weight, opt.range);

		// store data labels, release children
		label = source[code];
		child0 -> release();
		child1 -> release();

		// clear temporaries
		b_pop.init(idx(0, 0));     // TODO: init()
		distance.init(idx(0, 0));  // TODO: init()
		gen.clear();
		chosen.init(idx(0, 0));    // TODO: init()
	}

//-----------------------------------------------------------------------------

	void sample()
	{
		array <pos> samp = gen(K, chosen);  // samples with replacement
		code0 = samp % J;                   // positions of centroids on grid
		code1 = samp / J;
	}

	void sample(const size_array& which)
	{
		size_t k = which.length();
		array <pos> samp = gen(k, chosen);  // samples with replacement
		code0[which] = samp % J;            // positions of centroids on grid
		code1[which] = samp / J;
	}

//-----------------------------------------------------------------------------

	template <typename TERM>
	void assign(bool quantized, const TERM term,
					const train_options& opt, bool detail)
	{
		if (opt.hash)
			assign(quantized, term, types::t_true(), opt, detail);
		else
			assign(quantized, term, types::t_false(), opt, detail);
	}

	template <typename TERM, typename HASH>
	void assign(bool quantized, TERM term, HASH,
					const train_options& opt, bool detail)
	{
		// find distances between centroids and child centroids
		array_2d <T> dist0 = quantized ? child0 -> dist2(code0) :
		                                 child0 -> dist2(cen, dim0);
		array_2d <T> dist1 = quantized ? child1 -> dist2(code1) :
		                                 child1 -> dist2(cen, dim1);

		// quantize centroids
		if (!quantized)
		{
			for (size_t k = 0; k < K; k++)
			{
				code0[k] = arg_min(dist0.as_rows()[k]);  // TODO: code0 = arg_min[1](dist0);
				code1[k] = arg_min(dist1.as_rows()[k]);
			}
			chosen[code0 + J * code1] = true;
		}

		// get child edges
		const array <array <lab> > &edge0 = child0 -> edges(),
		                           &edge1 = child1 -> edges();
		const array <array <T> > &weight0 = child0 -> weights(),
		                         &weight1 = child1 -> weights();

		// propagate
		prop <T, lab, pos, count, HASH>
			P(source, distance, edge, weight,
		     code0, code1, dist0, dist1,
		     edge0, edge1, weight0, weight1,
		     b_pop, opt);

		P(gen, chosen, term, detail);
	}

//-----------------------------------------------------------------------------

public:

	train_node
	(
		const data& X,            // data points
		const size_array& at,     // dimension range
		const train_options& opt  // training options
	) :
		node <T>
		(
			// TODO: at -> X
			opt.cap[min(opt.cap.length() - 1, log2_(at.length()))],      // K
			opt.cap[min(opt.cap.length() - 1, log2_(at.length()) - 1)],  // J
			(0, _, at.length() / 2 - 1),                                 // dim0
			(at.length() / 2, _, at.length() - 1)                        // dim1
		),
		// TODO: at -> X
		D(at.length()), D0(D / 2), D1(D - D0), L(log2_(D))
	{
		// TODO: X, at -> X
		this->train(X, at, opt);
	}

//-----------------------------------------------------------------------------

	virtual void write(std::ostream& s) const
	{
		char type = 1;
		ivl::write(type, s);
		ivl::write(K, s);
		ivl::write(J, s);
		write_array(dim0, s);
		write_array(dim1, s);
		write_array(code0, s);
		write_array(code1, s);
		write_array_2d(source, s);
		write_array(edge, s);
		write_array(weight, s);

		child0 -> write(s);
		child1 -> write(s);
	}

//-----------------------------------------------------------------------------

	virtual size_t size() const { return K; }

	virtual const array <lab>&
	labels() const { return label; }

	virtual const array <array <T> >&
	centroids() const { return cen; }

	virtual const array <array <lab> >&
	edges() const { return edge; }

	virtual const array <array <T> >&
	weights() const { return weight; }

	virtual void release() { cen.init(); label.init(); }

//-----------------------------------------------------------------------------

	virtual array <lab> quant(const data& X, const size_array& at) const
	{
		return node <T>::quant(X, at);
	}

	virtual array <lab> quant(const data& X, const size_array& at,
									  const T range) const
	{
		return node <T>::quant(X, at, range);
	}

	virtual array_2d <T> dist2(const data& X, const size_array& at) const
	{
		return node <T>::dist2(X, at);
	}

	virtual array <T> dist2(const data& X, const size_array& at,
									const array <lab>& c) const
	{
		return node <T>::dist2(X, at, c);
	}

	virtual array <array <T> > dist2(const data& X, const size_array& at,
												const array <array <lab> >& c) const
	{
		return node <T>::dist2(X, at, c);
	}

	virtual array_2d <T> dist2(const size_array& c) const
	{
		return (child0 -> dist2(code0[c])) (_, cast <size_t> (code0)) +
		       (child1 -> dist2(code1[c])) (_, cast <size_t> (code1));
	}

//-----------------------------------------------------------------------------

	virtual void flat(data& C, const size_array& at, const array <lab>& c)
	{
		node <T>::flat(C, at, c);
	}

};

//-----------------------------------------------------------------------------

}  // namespace drvq

#endif  // TRAIN_NODE_HPP


text:
package admin;

import java.util.Collection;

/**
 * The authenticated identities for the caller of an operation.
 */
public interface Subject {
   public Collection<Identity> getAuthenticatedIdentities();
}


text:
import pytest

from api_tests.utils import create_test_file

from osf.management.commands.transfer_quickfiles_to_projects import (
    remove_quickfiles,
    reverse_remove_quickfiles,
    QUICKFILES_DESC
)
from osf.models import NodeLog
from osf.models.quickfiles import QuickFilesNode, get_quickfiles_project_title

from osf_tests.factories import AuthUserFactory

@pytest.mark.django_db
class TestTransferQuickfilesToProjects:

    @pytest.fixture()
    def user_with_quickfiles(self):
        user = AuthUserFactory()
        qfnode = QuickFilesNode.objects.create_for_user(user)
        create_test_file(target=qfnode, user=user)
        return user

    def test_tranfer_quickfiles_to_projects(self, user_with_quickfiles):
        remove_quickfiles()

        assert not QuickFilesNode.objects.all()
        node = user_with_quickfiles.nodes.get(
            title=get_quickfiles_project_title(user_with_quickfiles),
            logs__action=NodeLog.MIGRATED_QUICK_FILES,
            description=QUICKFILES_DESC
        )
        assert node.files.all()

    def test_reverse_tranfer_quickfiles_to_projects(self, user_with_quickfiles):
        remove_quickfiles()
        reverse_remove_quickfiles()

        quickfiles_node = QuickFilesNode.objects.get_for_user(user_with_quickfiles)
        assert QuickFilesNode.objects.all().get() == quickfiles_node
        assert quickfiles_node.files.exists()


text:
/* vim: set ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

let tempScope = {}
Cu.import("resource:///modules/devtools/CssRuleView.jsm", tempScope);
let CssRuleView = tempScope.CssRuleView;
let _ElementStyle = tempScope._ElementStyle;
let _editableField = tempScope._editableField;
let inplaceEditor = tempScope._getInplaceEditorForSpan;

let doc;
let ruleDialog;
let ruleView;
let testElement;

function startTest()
{
  let style = '' +
    '#testid {' +
    '  background-color: blue;' +
    '} ' +
    '.testclass {' +
    '  background-color: green;' +
    '}';

  let styleNode = addStyle(doc, style);
  doc.body.innerHTML = '
Styled Node
';
  testElement = doc.getElementById("testid");

  let elementStyle = 'margin-top: 1px; padding-top: 5px;'
  testElement.setAttribute("style", elementStyle);

  ruleDialog = openDialog("chrome://browser/content/devtools/cssruleview.xul",
                          "cssruleviewtest",
                          "width=200,height=350");
  ruleDialog.addEventListener("load", function onLoad(evt) {
    ruleDialog.removeEventListener("load", onLoad);
    let doc = ruleDialog.document;
    ruleView = new CssRuleView(doc);
    doc.documentElement.appendChild(ruleView.element);
    ruleView.highlight(testElement);
    waitForFocus(testRuleChanges, ruleDialog);
  }, true);
}

function testRuleChanges()
{
  let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
  is(selectors.length, 3, "Three rules visible.");
  is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
  is(selectors[1].textContent.indexOf("#testid"), 0, "Second item is id rule.");
  is(selectors[2].textContent.indexOf(".testclass"), 0, "Third item is class rule.");

  // Change the id and refresh.
  testElement.setAttribute("id", "differentid");
  ruleView.nodeChanged();

  let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
  is(selectors.length, 2, "Three rules visible.");
  is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
  is(selectors[1].textContent.indexOf(".testclass"), 0, "Second item is class rule.");

  testElement.setAttribute("id", "testid");
  ruleView.nodeChanged();

  // Put the id back.
  let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
  is(selectors.length, 3, "Three rules visible.");
  is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
  is(selectors[1].textContent.indexOf("#testid"), 0, "Second item is id rule.");
  is(selectors[2].textContent.indexOf(".testclass"), 0, "Third item is class rule.");

  testPropertyChanges();
}

function validateTextProp(aProp, aEnabled, aName, aValue, aDesc)
{
  is(aProp.enabled, aEnabled, aDesc + ": enabled.");
  is(aProp.name, aName, aDesc + ": name.");
  is(aProp.value, aValue, aDesc + ": value.");

  is(aProp.editor.enable.hasAttribute("checked"), aEnabled, aDesc + ": enabled checkbox.");
  is(aProp.editor.nameSpan.textContent, aName, aDesc + ": name span.");
  is(aProp.editor.valueSpan.textContent, aValue, aDesc + ": value span.");
}

function testPropertyChanges()
{
  // Add a second margin-top value, just to make things interesting.
  let ruleEditor = ruleView._elementStyle.rules[0].editor;
  ruleEditor.addProperty("margin-top", "5px", "");

  let rule = ruleView._elementStyle.rules[0];

  // Set the element style back to a 1px margin-top.
  testElement.setAttribute("style", "margin-top: 1px; padding-top: 5px");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
  validateTextProp(rule.textProps[0], true, "margin-top", "1px", "First margin property re-enabled");
  validateTextProp(rule.textProps[2], false, "margin-top", "5px", "Second margin property disabled");

  // Now set it back to 5px, the 5px value should be re-enabled.
  testElement.setAttribute("style", "margin-top: 5px; padding-top: 5px;");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
  validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
  validateTextProp(rule.textProps[2], true, "margin-top", "5px", "Second margin property disabled");

  // Set the margin property to a value that doesn't exist in the editor.
  // Should reuse the currently-enabled element (the second one.)
  testElement.setAttribute("style", "margin-top: 15px; padding-top: 5px;");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
  validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
  validateTextProp(rule.textProps[2], true, "margin-top", "15px", "Second margin property disabled");

  // Remove the padding-top attribute.  Should disable the padding property but not remove it.
  testElement.setAttribute("style", "margin-top: 5px;");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
  validateTextProp(rule.textProps[1], false, "padding-top", "5px", "Padding property disabled");

  // Put the padding-top attribute back in, should re-enable the padding property.
  testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
  validateTextProp(rule.textProps[1], true, "padding-top", "25px", "Padding property enabled");

  // Add an entirely new property.
  testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px; padding-left: 20px;");
  ruleView.nodeChanged();
  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 4, "Added a property");
  validateTextProp(rule.textProps[3], true, "padding-left", "20px", "Padding property enabled");

  finishTest();
}

function finishTest()
{
  ruleView.clear();
  ruleDialog.close();
  ruleDialog = ruleView = null;
  doc = null;
  gBrowser.removeCurrentTab();
  finish();
}

function test()
{
  waitForExplicitFinish();
  gBrowser.selectedTab = gBrowser.addTab();
  gBrowser.selectedBrowser.addEventListener("load", function(evt) {
    gBrowser.selectedBrowser.removeEventListener(evt.type, arguments.callee, true);
    doc = content.document;
    waitForFocus(startTest, content);
  }, true);

  content.location = "data:text/html,basic style inspector tests";
}


text:
package org.apache.storm.security.auth.sasl;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;

/**
 * A client callback handler that supports a single username and password.
 */
public class SimpleSaslClientCallbackHandler implements CallbackHandler {
    private final String username;
    private final String password;

    /**
     * Constructor.
     *
     * @param username the username to use.
     * @param password the password to use.
     */
    public SimpleSaslClientCallbackHandler(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
        for (Callback c : callbacks) {
            if (c instanceof NameCallback) {
                NameCallback nc = (NameCallback) c;
                nc.setName(username);
            } else if (c instanceof PasswordCallback) {
                PasswordCallback pc = (PasswordCallback) c;
                if (password != null) {
                    pc.setPassword(password.toCharArray());
                }
            } else if (c instanceof AuthorizeCallback) {
                AuthorizeCallback ac = (AuthorizeCallback) c;
                String authid = ac.getAuthenticationID();
                String authzid = ac.getAuthorizationID();
                if (authid.equals(authzid)) {
                    ac.setAuthorized(true);
                } else {
                    ac.setAuthorized(false);
                }
                if (ac.isAuthorized()) {
                    ac.setAuthorizedID(authzid);
                }
            } else if (c instanceof RealmCallback) {
                RealmCallback rc = (RealmCallback) c;
                ((RealmCallback) c).setText(rc.getDefaultText());
            } else {
                throw new UnsupportedCallbackException(c);
            }
        }
    }
}


text:
var lib = process.env.POMELO_RPC_COV ? 'lib-cov' : 'lib';
var Acceptor = require('../../' + lib + '/rpc-server/acceptor');
var should = require('should');
var Client = require('./client/mock-client');

var WAIT_TIME = 100;

var port = 3333;

describe('acceptor', function() {

  describe('#listen', function() {
    it('should be ok when listen a valid port and emit a closed event when it closed', function(done) {
      var errorCount = 0;
      var closeCount = 0;
      var acceptor = Acceptor.create(null, function(tracer, msg, cb) {});

      should.exist(acceptor);
      acceptor.on('error', function(err) {
        errorCount++;
      });
      acceptor.on('closed', function() {
        closeCount++;
      });

      acceptor.listen(port);
      acceptor.close();

      setTimeout(function() {
        errorCount.should.equal(0);
        closeCount.should.equal(1);
        done();
      }, WAIT_TIME);
    });

    it('should emit an error when listen a port in use', function(done) {
      var errorCount = 0;
      var acceptor = Acceptor.create(null, function(tracer, msg, cb) {});

      should.exist(acceptor);
      acceptor.on('error', function(err) {
        should.exist(err);
        errorCount++;
      });

      acceptor.listen(80);

      setTimeout(function() {
        errorCount.should.equal(1);
        acceptor.close();
        done();
      }, WAIT_TIME);
    });
  });

  describe('#new message callback', function() {
    it('should invoke the callback function with the same msg and return response to remote client by cb', function(done) {
      var callbackCount = 0;
      var clientCallbackCount = 0;
      var orgMsg = {
        service: 'xxx.yyy.zzz',
        method: 'someMethod',
        args: [1, 'a', {param: 100}]
      };

      var acceptor = Acceptor.create(null, function(tracer, msg, cb) {
        msg.should.eql(orgMsg);
        callbackCount++;
        cb(msg);
      });

      should.exist(acceptor);
      acceptor.listen(port);

      var client = Client.create();
      client.connect('127.0.0.1', port, function() {
        client.send(orgMsg, function(backMsg) {
          backMsg.should.eql(orgMsg);
          clientCallbackCount++;
        });
      });

      setTimeout(function() {
        callbackCount.should.equal(1);
        clientCallbackCount.should.equal(1);
        client.close();
        acceptor.close();
        done();
      }, WAIT_TIME);
    });

    it('should keep the relationship with request and response in batch rpc calls', function(done) {
      var callbackCount = 0;
      var clientCallbackCount = 0;
      var orgMsg1 = {
        service: 'xxx.yyy.zzz1',
        method: 'someMethod1',
        args: [1, 'a', {param: 100}]
      };
      var orgMsg2 = {
        service: 'xxx.yyy.zzz2',
        method: 'someMethod2',
        args: [2, 'a', {param: 100}]
      };

      var acceptor = Acceptor.create(null, function(tracer, msg, cb) {
        callbackCount++;
        cb(msg);
      });
      should.exist(acceptor);
      acceptor.listen(port);

      var client = Client.create();
      client.connect('127.0.0.1', port, function() {
        client.send(orgMsg1, function(backMsg) {
          backMsg.should.eql(orgMsg1);
          clientCallbackCount++;
        });
        client.send(orgMsg2, function(backMsg) {
          backMsg.should.eql(orgMsg2);
          clientCallbackCount++;
        });
      });

      setTimeout(function() {
        callbackCount.should.equal(2);
        clientCallbackCount.should.equal(2);
        client.close();
        acceptor.close();
        done();
      }, WAIT_TIME);
    });
  });
});


text:
package no.kantega.publishing.admin.content.action;

import no.kantega.commons.client.util.RequestParameters;
import no.kantega.publishing.admin.AdminSessionAttributes;
import no.kantega.publishing.common.data.Content;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class SelectContentAction implements Controller {
    private String view;

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> model = new HashMap<>();

        RequestParameters param = new RequestParameters(request);
        if (param.getBoolean("selectContentId", false)) {
            model.put("selectContentId", Boolean.TRUE);
        }

        model.put("multiple", param.getBoolean("multiple", false));
        model.put("contentTemplate", param.getString("contentTemplate"));

        int currentId = -1;
        Content currentContent = (Content)request.getSession().getAttribute(AdminSessionAttributes.CURRENT_EDIT_CONTENT);
        if (currentContent != null) {
            if (currentContent.isNew()) {
                currentId = currentContent.getAssociation().getParentAssociationId();
            } else {
                currentId = currentContent.getAssociation().getAssociationId();
            }
        }
        model.put("currentId", currentId);
        model.put("startId", param.getInt("startId"));

        return new ModelAndView(view, model);
    }

    public void setView(String view) {
        this.view = view;
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chromium_linker_test_apk;

import org.chromium.base.Log;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.library_loader.Linker;

/**
 * A class that is only used in linker test APK to perform runtime checks
 * in the current process.
 */
@JNINamespace("content")
public class LinkerTests implements Linker.TestRunner {
    private static final String TAG = "LinkerTest";

    public LinkerTests() {}

    @Override
    public boolean runChecks(int memoryDeviceConfig,
                             boolean isBrowserProcess) {
        boolean checkSharedRelro;
        if (isBrowserProcess) {
            Linker linker = Linker.getInstance();
            int linkerImplementation = linker.getImplementationForTesting();

            if (linkerImplementation == Linker.LINKER_IMPLEMENTATION_LEGACY) {
                // LegacyLinker may share RELROs in the browser.
                switch (Linker.BROWSER_SHARED_RELRO_CONFIG) {
                    case Linker.BROWSER_SHARED_RELRO_CONFIG_NEVER:
                        checkSharedRelro = false;
                        break;
                    case Linker.BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
                        // A shared RELRO should only be used on low-end devices.
                        checkSharedRelro =
                                (memoryDeviceConfig == Linker.MEMORY_DEVICE_CONFIG_LOW);
                        break;
                    case Linker.BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
                        // Always check for a shared RELRO.
                        checkSharedRelro = true;
                        break;
                    default:
                        Log.e(TAG, "Invalid shared RELRO linker configuration: "
                                + Linker.BROWSER_SHARED_RELRO_CONFIG);
                        return false;
                }

            } else if (linkerImplementation == Linker.LINKER_IMPLEMENTATION_MODERN) {
                // ModernLinker never shares RELROs in the browser.
                checkSharedRelro = false;

            } else {
                Log.e(TAG, "Unknown linker: " + linker.getClass().getName());
                return false;
            }
        } else {
            // Service processes should always use a shared RELRO section.
            checkSharedRelro = true;
        }

        if (checkSharedRelro) {
            return nativeCheckForSharedRelros(isBrowserProcess);
        } else {
            return nativeCheckForNoSharedRelros(isBrowserProcess);
        }
    }

    // Check that there are shared RELRO sections in the current process,
    // and that they are properly mapped read-only. Returns true on success.
    private static native boolean nativeCheckForSharedRelros(boolean isBrowserProcess);

    // Check that there are no shared RELRO sections in the current process,
    // return true on success.
    private static native boolean nativeCheckForNoSharedRelros(boolean isBrowserProcess);
}


text:
package com.rackspace.cableway;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;

import java.util.Map;

public class CorrelationBolt extends BaseRichBolt {
    OutputCollector _collector;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
        _collector = outputCollector;
    }

    @Override
    public void execute(Tuple tuple) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var EndGate;
(function (EndGate) {
    (function (Graphics) {
        /// <reference path="../../Assets/Vectors/Vector2d.ts" />
        /// <reference path="../Graphic2d.ts" />
        (function (Abstractions) {
            /**
            * Abstract drawable shape type that is used create customizable drawable graphics.
            */
            var Shape = (function (_super) {
                __extends(Shape, _super);
                function Shape(position, color) {
                    _super.call(this, position);
                    this._type = "Shape";

                    this._fill = false;
                    this._stroke = false;

                    if (typeof color !== "undefined") {
                        this.Color = color;
                    }
                }
                Object.defineProperty(Shape.prototype, "Color", {
                    get: /**
                    * Gets or sets the current shape color.  Valid colors are strings like "red" or "rgb(255,0,0)".
                    */
                    function () {
                        return this._State.FillStyle;
                    },
                    set: function (color) {
                        this._fill = true;
                        this._State.FillStyle = color;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "BorderThickness", {
                    get: /**
                    * Gets or sets the current border thickness.
                    */
                    function () {
                        return this._State.LineWidth;
                    },
                    set: function (thickness) {
                        this._State.LineWidth = thickness;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "BorderColor", {
                    get: /**
                    * Gets or sets the current border color.  Valid colors are strings like "red" or "rgb(255,0,0)".
                    */
                    function () {
                        return this._State.StrokeStyle;
                    },
                    set: function (color) {
                        this._stroke = true;
                        this._State.StrokeStyle = color;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "ShadowColor", {
                    get: /**
                    * Gets or sets the current shadow color.  Valid colors are strings like "red" or "rgb(255,0,0)".
                    */
                    function () {
                        return this._State.ShadowColor;
                    },
                    set: function (color) {
                        this._fill = true;
                        this._State.ShadowColor = color;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "ShadowX", {
                    get: /**
                    * Gets or sets the current horizontal shadow position.
                    */
                    function () {
                        return this._State.ShadowOffsetX;
                    },
                    set: function (x) {
                        this._State.ShadowOffsetX = x;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "ShadowY", {
                    get: /**
                    * Gets or sets the current vertical shadow position.
                    */
                    function () {
                        return this._State.ShadowOffsetY;
                    },
                    set: function (y) {
                        this._State.ShadowOffsetY = y;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "ShadowBlur", {
                    get: /**
                    * Gets or sets the current shadow blur.
                    */
                    function () {
                        return this._State.ShadowBlur;
                    },
                    set: function (blur) {
                        this._State.ShadowBlur = blur;
                    },
                    enumerable: true,
                    configurable: true
                });

                Object.defineProperty(Shape.prototype, "Opacity", {
                    get: /**
                    * Gets or sets the current opacity.  Value is between 0 and 1.
                    */
                    function () {
                        return this._State.GlobalAlpha;
                    },
                    set: function (alpha) {
                        this._State.GlobalAlpha = alpha;
                    },
                    enumerable: true,
                    configurable: true
                });

                /**
                * Sets the current borders thickness and color.
                * @param thickness The new border thickness in pixels.
                * @param color The new border color.  Can be valid color strings, like "red" or "rgb(255,0,0)".
                */
                Shape.prototype.Border = function (thickness, color) {
                    this.BorderThickness = thickness;
                    this.BorderColor = color;
                };

                Shape.prototype.Shadow = function (x, y, color, blur) {
                    this.ShadowX = x;
                    this.ShadowY = y;
                    this.ShadowColor = color;
                    this.ShadowBlur = blur;
                };

                Shape.prototype._StartDraw = function (context) {
                    _super.prototype._StartDraw.call(this, context);
                    context.beginPath();
                };

                Shape.prototype._EndDraw = function (context) {
                    if (this._fill) {
                        context.fill();
                    }

                    if (this._stroke) {
                        context.stroke();
                    } else {
                        context.closePath();
                    }

                    _super.prototype._EndDraw.call(this, context);
                };

                // This should be overridden if you want to build a proper shape
                Shape.prototype._BuildPath = function (context) {
                };

                /**
                * Draws the shape onto the given context.  If this shape is part of a scene the Draw function will be called automatically.
                * @param context The canvas context to draw the shape onto.
                */
                Shape.prototype.Draw = function (context) {
                    this._StartDraw(context);
                    this._BuildPath(context);
                    this._EndDraw(context);
                };
                return Shape;
            })(Abstractions.Graphic2d);
            Abstractions.Shape = Shape;
        })(Graphics.Abstractions || (Graphics.Abstractions = {}));
        var Abstractions = Graphics.Abstractions;
    })(EndGate.Graphics || (EndGate.Graphics = {}));
    var Graphics = EndGate.Graphics;
})(EndGate || (EndGate = {}));


text:
package com.bbn.kbp.events2014;

import com.bbn.bue.common.TextGroupPublicImmutable;
import com.bbn.bue.common.symbols.Symbol;

import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;

import org.immutables.func.Functional;
import org.immutables.value.Value;

import java.util.Iterator;

import static com.bbn.kbp.events2014.CorpusQuery2016Functions.id;
import static com.google.common.base.Preconditions.checkArgument;

/**
 * A collection of {@link CorpusQuery2016}. All IDs are guaranteed to be unique.
 */
@TextGroupPublicImmutable
@Value.Immutable
@Functional
abstract class _CorpusQuerySet2016 implements Iterable<CorpusQuery2016> {

  @Value.Parameter
  public abstract ImmutableSet<CorpusQuery2016> queries();

  public final Iterator<CorpusQuery2016> iterator() {
    return queries().iterator();
  }

  @Value.Check
  protected void check() {
    final ImmutableSet<Symbol> allIds = FluentIterable.from(queries()).transform(id()).toSet();
    checkArgument(allIds.size() == queries().size(), "All query IDs in a query set must be unique");
  }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Spark.CSharp.Core;
using Microsoft.Spark.CSharp.Interop;
using Microsoft.Spark.CSharp.Interop.Ipc;

namespace Microsoft.Spark.CSharp.Proxy.Ipc
{
    [ExcludeFromCodeCoverage] //IPC calls to JVM validated using validation-enabled samples - unit test coverage not reqiured
    internal class StatusTrackerIpcProxy : IStatusTrackerProxy
    {
        private readonly JvmObjectReference jvmStatusTrackerReference;
        public StatusTrackerIpcProxy(JvmObjectReference jStatusTracker)
        {
            jvmStatusTrackerReference = jStatusTracker;
        }

        public int[] GetJobIdsForGroup(string jobGroup)
        {
            return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobIdsForGroup", new object[] { jobGroup });
        }
        public int[] GetActiveStageIds()
        {
            return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveStageIds");
        }
        public int[] GetActiveJobsIds()
        {
            return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveJobsIds");
        }

        public SparkJobInfo GetJobInfo(int jobId)
        {
            var jobInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobInfo", new object[] { jobId });
            if (jobInfoId == null)
                return null;

            JvmObjectReference jJobInfo = new JvmObjectReference((string)jobInfoId);
            int[] stageIds = (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "stageIds");
            string statusString = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "status").ToString();
            var status = (JobExecutionStatus) Enum.Parse(typeof(JobExecutionStatus), statusString, true);

            return new SparkJobInfo(jobId, stageIds, status);
        }
        public SparkStageInfo GetStageInfo(int stageId)
        {
            var stageInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getStageInfo", new object[] { stageId });
            if (stageInfoId == null)
                return null;

            JvmObjectReference jStageInfo = new JvmObjectReference((string)stageInfoId);
            int currentAttemptId = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "currentAttemptId");
            int submissionTime = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "submissionTime");
            string name = (string)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "name");
            int numTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numTasks");
            int numActiveTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numActiveTasks");
            int numCompletedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numCompletedTasks");
            int numFailedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numFailedTasks");

            return new SparkStageInfo(stageId, currentAttemptId, (long)submissionTime, name, numTasks, numActiveTasks, numCompletedTasks, numFailedTasks);
        }
    }
}


text:
'use strict'

import NSObject from '../ObjectiveC/NSObject'

/**
 * dummy class for NSKeyedArchiver/Unarchiver
 * @access public
 * @extends {NSObject}
 */
export default class NSData extends NSObject {
  /**
   * @access public
   * @param {NSCoder} coder -
   * @returns {_Buffer} -
   */
  static initWithCoder(coder) {
    const data = coder.decodeBytesForKeyReturnedLength('NS.data', null)
    if(typeof data !== 'undefined'){
      return data
    }
    const bytes = coder.decodeBytesForKeyReturnedLength('NS.bytes', null)
    if(typeof bytes !== 'undefined'){
      return bytes
    }
    return null
  }
}


text:
import fetchJsonp from 'fetch-jsonp'

import { getHashValue, getQueryStringValue, parseAsURL, rslError } from '../utils'

const INSTAGRAM_API = 'https://api.instagram.com/v1'

let instagramAuth
let instagramAccessToken

/**
 * @param {string} appId
 * @param {string} redirect
 * @param {array|string} scope
 * Fake Instagram SDK loading (needed to trick RSL into thinking its loaded).
 */
const load = ({ appId, redirect, scope }) => new Promise((resolve, reject) => {
  const _redirect = parseAsURL(redirect)
  const searchParams = 'rslCallback=instagram'
  let instagramScopes = [ 'user_profile' ]

  if (Array.isArray(scope)) {
    instagramScopes = instagramScopes.concat(scope)
  } else if (typeof scope === 'string' && scope) {
    instagramScopes = instagramScopes.concat(scope.split(','))
  }

  instagramScopes = instagramScopes.reduce((acc, item) => {
    if (typeof item === 'string' && acc.indexOf(item) === -1) {
      acc.push(item.trim())
    }

    return acc
  }, []).join('+')

  _redirect.search = _redirect.search ? _redirect.search + '&' + searchParams : '?' + searchParams

  instagramAuth = `https://api.instagram.com/oauth/authorize/?client_id=${appId}&scope=${instagramScopes}&redirect_uri=${encodeURIComponent(_redirect.toString())}&response_type=code`

  if (getQueryStringValue('rslCallback') === 'instagram') {
    if (getQueryStringValue('error')) {
      return reject(rslError({
        provider: 'instagram',
        type: 'auth',
        description: 'Authentication failed',
        error: {
          error_reason: getQueryStringValue('error_reason'),
          error_description: getQueryStringValue('error_description')
        }
      }))
    } else {
      instagramAccessToken = getHashValue('access_token')
    }
  }

  return resolve(instagramAccessToken)
})

/**
 * Checks if user is logged in to app through Instagram.
 * @see https://www.instagram.com/developer/endpoints/users/#get_users_self
 */
const checkLogin = (autoLogin = false) => {
  if (autoLogin) {
    return login()
  }

  if (!instagramAccessToken) {
    return Promise.reject(rslError({
      provider: 'instagram',
      type: 'access_token',
      description: 'No access token available',
      error: null
    }))
  }

  return new Promise((resolve, reject) => {
    fetchJsonp(`${INSTAGRAM_API}/users/self/?access_token=${instagramAccessToken}`)
      .then((response) => response.json())
      .then((json) => {
        if (json.meta.code !== 200) {
          return reject(rslError({
            provider: 'instagram',
            type: 'check_login',
            description: 'Failed to fetch user data',
            error: json.meta
          }))
        }

        return resolve({ data: json.data, accessToken: instagramAccessToken })
      })
      .catch((err) => reject({ // eslint-disable-line prefer-promise-reject-errors
        fetchErr: true,
        err: rslError({
          provider: 'instagram',
          type: 'check_login',
          description: 'Failed to fetch user data due to fetch error',
          error: err
        })
      }))
  })
}

/**
 * Trigger Instagram login process.
 * This code only triggers login request, response is handled by a callback handled on SDK load.
 * @see https://www.instagram.com/developer/authentication/
 */
const login = () => new Promise((resolve, reject) => {
  checkLogin()
    .then((response) => resolve(response))
    .catch((err) => {
      if (!err.fetchErr) {
        window.open(instagramAuth, '_self')
      } else {
        return reject(err.err)
      }
    })
})

/**
 * Fake Instagram logout.
 */
const logout = () => new Promise((resolve) => {
  instagramAccessToken = undefined

  return resolve()
})

/**
 * Helper to generate user account data.
 * @param {Object} data
 * @see About token expiration: https://www.instagram.com/developer/authentication/
 * @see Instagram API doesn't provide email: https://www.instagram.com/developer/endpoints/users/#get_users_self
 */
const generateUser = (data) => ({
  profile: {
    id: data.data.id,
    name: data.data.full_name,
    firstName: data.data.full_name,
    lastName: data.data.full_name,
    email: undefined,
    profilePicURL: data.data.profile_picture
  },
  token: {
    accessToken: data.accessToken,
    expiresAt: Infinity
  }
})

export default {
  checkLogin,
  generateUser,
  load,
  login,
  logout
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<JPanel xmlns="org.aswing"
        xmlns:haxe="http://haxe.org/"
        xmlns:geom="org.aswing.geom"
        xmlns:ext="org.aswing.ext"
        xmlns:view="demo.view"
        xmlns:jive="jive"
        xmlns:border="org.aswing.border"
        xmlns:e="empty"
        >
    <layout>
        <BorderLayout hgap="30" vgap="30"/>
    </layout>

    <SoftBox constraints="org.aswing.BorderLayout.CENTER">
        <JLabel text="'Download'" horizontalAlignment="org.aswing.AsWingConstants.LEFT" constraints="org.aswing.BorderLayout.NORTH">

                <ASFont name="'assets/Lato-Bold.ttf'" size="30"/>

            <border>
                <border:EmptyBorder bottom="30"/>
            </border>
        </JLabel>

        <JPanel>
            <JLabel text="'From haxelib:'">

                    <ASFont name="'assets/Lato-Bold.ttf'" size="16"/>

            </JLabel>
            <JLabel text="'haxelib install jive'" selectable="true"/>
        </JPanel>

        <JPanel>
            <JLabel text="'Development version from GitHub:'" selectable="false">

                    <ASFont name="'assets/Lato-Bold.ttf'" size="16"/>

            </JLabel>
            <JLabel text="'haxelib git jive https://github.com/ngrebenshikov/jive'" selectable="true"/>
        </JPanel>

        <JPanel>
            <JLabel text="'Download manually from GitHub:'">

                    <ASFont name="'assets/Lato-Bold.ttf'" size="16"/>

            </JLabel>
            <JLabelButton text="'Download the archive'">
                <command>
                    <jive:OpenLinkCommand url="'https://github.com/ngrebenshikov/jive/archive/master.zip'"/>
                </command>
            </JLabelButton>
            <JLabel text="', extract files and use [haxelib dev] command.'"/>
        </JPanel>

        <JPanel>
            <JLabel text="'Dependencies:'">

                    <ASFont name="'assets/Lato-Bold.ttf'" size="16"/>

            </JLabel>
            <JLabel text="'haxelib git hml https://github.com/profelis/hml'" selectable="true"/>
        </JPanel>

    </SoftBox>
</JPanel>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>edu.umn.biomedicus.tokenization</title>
<meta name="date" content="2018-07-03">
<meta name="keywords" content="edu.umn.biomedicus.tokenization package">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

edu.umn.biomedicus.tokenization

Interfaces

Token

Classes

DetectParseTokens

DetectTokenCandidates

MergeTermTokens

MimicFastTextPreprocessor

MimicFastTextPreprocessorKt

ParseToken

TermToken

TermTokenMerger

TokenCandidate

TokenizationModule

WordIndex


text:
"""
VXLAN packet parser/serializer

RFC 7348
VXLAN Header:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|R|R|R|R|I|R|R|R|            Reserved                           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                VXLAN Network Identifier (VNI) |   Reserved    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

- Flags (8 bits): where the I flag MUST be set to 1 for a valid
  VXLAN Network ID (VNI).  The other 7 bits (designated "R") are
  reserved fields and MUST be set to zero on transmission and
  ignored on receipt.

- VXLAN Segment ID/VXLAN Network Identifier (VNI): this is a
  24-bit value used to designate the individual VXLAN overlay
  network on which the communicating VMs are situated.  VMs in
  different VXLAN overlay networks cannot communicate with each
  other.

- Reserved fields (24 bits and 8 bits): MUST be set to zero on
  transmission and ignored on receipt.
"""

import struct
import logging

from . import packet_base

LOG = logging.getLogger(__name__)

UDP_DST_PORT = 4789
UDP_DST_PORT_OLD = 8472  # for backward compatibility like Linux

class vxlan(packet_base.PacketBase):
    """VXLAN (RFC 7348) header encoder/decoder class.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    ============== ====================
    Attribute      Description
    ============== ====================
    vni            VXLAN Network Identifier
    ============== ====================
    """

    # Note: Python has no format character for 24 bits field.
    # we use uint32 format character instead and bit-shift at serializing.
    _PACK_STR = '!II'
    _MIN_LEN = struct.calcsize(_PACK_STR)

    def __init__(self, vni):
        super(vxlan, self).__init__()
        self.vni = vni

    @classmethod
    def parser(cls, buf):
        (flags_reserved, vni_rserved) = struct.unpack_from(cls._PACK_STR, buf)

        # Check VXLAN flags is valid
        assert (1 << 3) == (flags_reserved >> 24)

        # Note: To avoid cyclic import, import ethernet module here
        from ryu.lib.packet import ethernet
        return cls(vni_rserved >> 8), ethernet.ethernet, buf[cls._MIN_LEN:]

    def serialize(self, payload, prev):
        return struct.pack(self._PACK_STR,
                           1 << (3 + 24), self.vni << 8)


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:ror="http://rorweb.com/0.1/" >
<channel>
  <title>ROR Sitemap for http://blogs.faadudeveloper.com/</title>
  <link>http://blogs.faadudeveloper.com/</link>

<item>
     <link>http://blogs.faadudeveloper.com/</link>
     <title>Blogs – Vinay Prajapati : Blogs</title>
     <description>Vinay has 5+ years of experience in different technologies and platforms e.g.Franchising, Cloud, Marketing . He is overall having knowledge of Java, gradle, springboot, groovy, jsp, gsp, grails, junit, spock, restful webservices, json, html, css, javascript,jquery, mysql, mongo, docker, spring, hibernate, windows, ubuntu, linux, JIRA, bitbucket & Trello etc.</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>0</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/tagCloud/</link>
     <title>Tag Cloud – Vinay Prajapati : Blogs</title>
     <description>Vinay has 5+ years of experience in different technologies and platforms e.g.Franchising, Cloud, Marketing . He is overall having knowledge of Java, gradle, springboot, groovy, jsp, gsp, grails, junit, spock, restful webservices, json, html, css, javascript,jquery, mysql, mongo, docker, spring, hibernate, windows, ubuntu, linux, JIRA, bitbucket & Trello etc.</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/categories/</link>
     <title>Category – Vinay Prajapati : Blogs</title>
     <description>Vinay has 5+ years of experience in different technologies and platforms e.g.Franchising, Cloud, Marketing . He is overall having knowledge of Java, gradle, springboot, groovy, jsp, gsp, grails, junit, spock, restful webservices, json, html, css, javascript,jquery, mysql, mongo, docker, spring, hibernate, windows, ubuntu, linux, JIRA, bitbucket & Trello etc.</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/about/</link>
     <title>Contact Us – Vinay Prajapati : Blogs</title>
     <description>Vinay has 5+ years of experience in different technologies and platforms e.g.Franchising, Cloud, Marketing . He is overall having knowledge of Java, gradle, springboot, groovy, jsp, gsp, grails, junit, spock, restful webservices, json, html, css, javascript,jquery, mysql, mongo, docker, spring, hibernate, windows, ubuntu, linux, JIRA, bitbucket & Trello etc.</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/functional-interfaces/</link>
     <title>Functional Interface for Lambda expressions Java 8 – Vinay Prajapati : Blogs</title>
     <description>Lambda Expressions are used to support functional programming in Java. The default behaviour of Lambda expressions is to accept only those interfaces as reference variables which have only one abstract method. We call such interfaces Functional Interfaces.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/Type-Inference-java8/</link>
     <title>Type Inference in Lambda Expressions : Java 8 – Vinay Prajapati : Blogs</title>
     <description>Type Inference means that the data type of any expression (e.g. method return type or parameter type) can be deduced automatically by the compiler. Groovy language is a good example of programming languages supporting Type Inference.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/fp-lambda-expressions/</link>
     <title>Functional Programming in Java 8 Using Lambda Expressions – Vinay Prajapati : Blogs</title>
     <description>Lambda expressions are the most talked feature of Java 8. Lambda expressions drastically change the way we write the code in Java 8 as compared to what we used to, in older versions.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/fi-api-generic-fi/</link>
     <title>Generic Functional Interfaces and Functional Interface API for Lambda Expressions: Java 8 – Vinay Prajapati : Blogs</title>
     <description>Lambda expressions come with a standard rule that they can only be assigned to a reference variable which is a Functional Interface i.e. an interface having one and only one abstract method.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/springboot-using-cli/</link>
     <title>Quick start with Springboot using CLI – Vinay Prajapati : Blogs</title>
     <description>SpringBoot is one of the main projects of Spring community which takes opinionated view of production ready applications. It helps you getting up and running a production grade spring application.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/dependencies-json-schema/</link>
     <title>Using "dependencies" in json schema (version : draft-v4) – Vinay Prajapati : Blogs</title>
     <description>Json Schema has another interesting feature which allows value of some property of json schema to depend upon other fields value. This could be done using "dependencies" which allows specifying dependent object / property on the basis of value of the field which is using dependencies keyword.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/using-definitions-json-schema/</link>
     <title>Using definitions internal to json schema and external to json schema (version – draft -04) – Vinay Prajapati : Blogs</title>
     <description>There could be times when you end with a generously large schema with lots of redundant properties due to certain business requirements.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/grails-non-persistent-domains/</link>
     <title>Making a domain non-persistent – Vinay Prajapati : Blogs</title>
     <description>In grails app, there might come scenarios where one need to create a non-persistent domain rather than creating a command obejct or POJO / POGO.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/spread-operator/</link>
     <title>Spread Operator in groovy – Vinay Prajapati : Blogs</title>
     <description>The Spread Operator is used to invoke an action on all items of an aggregate object. It is equivalent to calling the action on each item and collecting the result into a list:

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/compile-groovy-statically/</link>
     <title>Compiling groovy code statically – Vinay Prajapati : Blogs</title>
     <description>Groovy by default uses dynamic dispatch. Dynamic Dispatch could be defined as the capability of adding or replacing units of code at run time. For example, we can change the definition of a method or we can add new methods to a class at run time using metaprogramming in Groovy.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/operators-in-groovy/</link>
     <title>Groovy shorthand operators – Vinay Prajapati : Blogs</title>
     <description>Every language have shorthand operators that allows multi line operations to be performed in single line. For example ?: is a ternary operator used in scenarios where condition and  the code inside condition is very small and specific to comparison operands.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
<item>
     <link>http://blogs.faadudeveloper.com/Using-SimpleDateFormat/</link>
     <title>Working with SimpleDateFormat – Vinay Prajapati : Blogs</title>
     <description>SimpleDateFormat class implementation of DateFormat could be used to convert date string to date.

</description>
     <ror:updatePeriod>always</ror:updatePeriod>
     <ror:sortOrder>1</ror:sortOrder>
     <ror:resourceOf>sitemap</ror:resourceOf>
</item>
</channel>
</rss>


text:
@implementation MKSHorizontalLineProgressView

#pragma mark - View Life cycle method

- (id)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];

    if(self){

        [self initalSetup];
    }

    return self;}

- (id)initWithCoder:(NSCoder *)aDecoder{

   self = [super initWithCoder:aDecoder];

    if(self){
        [self initalSetup];
    }

    return self;
}

- (void) drawRect:(CGRect)rect{
    [self drawProgressView];
}

#pragma mark - Intial Setup
- (void)initalSetup{
    self.barColor = [UIColor redColor];
    self.trackColor = [UIColor redColor];
    self.barThickness = self.frame.size.height;
    self.barPadding = 0.0f;
    self.trackPadding = 0.0f;
    self.progressValue = 0.0f;
    self.progressPercentageTextColor = [UIColor whiteColor];
    self.showPercentageText = NO;

    self.progressPercentageFont = [UIFont fontWithName:@"Helvetica" size:14];
    self.progressBarDirection = MKSProgressBarDirectionFromLeftToRight;
}

#pragma mark - DrawLine Progress View

// Draws the progress bar and track
- (void)drawProgressView{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    // Progres Bar Track
    CGContextSetStrokeColorWithColor(context, self.trackColor.CGColor);
    CGContextBeginPath(context);
    CGContextSetLineWidth(context, self.barThickness + self.trackPadding);
    CGContextMoveToPoint(context, self.barPadding, self.frame.size.height / 2);
    CGContextAddLineToPoint(context, self.frame.size.width - self.barPadding, self.frame.size.height / 2);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextStrokePath(context);

    // Progress Bar
    CGFloat xStartPoint = (self.progressBarDirection == MKSProgressBarDirectionFromLeftToRight) ?
                          self.barPadding : self.frame.size.width - self.barPadding;
    CGFloat xEndPoint   = (self.progressBarDirection == MKSProgressBarDirectionFromLeftToRight) ?
                          self.barPadding + [self progressPercentage] :
                          self.frame.size.width - self.barPadding - [self progressPercentage];
    CGContextSetStrokeColorWithColor(context, self.barColor.CGColor);
    CGContextSetLineWidth(context, self.barThickness);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, xStartPoint, self.frame.size.height / 2);
    CGContextAddLineToPoint(context, xEndPoint , self.frame.size.height / 2);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextStrokePath(context);

    if(self.isShowPercentageText){

        int progressValue = [self progressValue];
        int progressStringWidth = [self progressPercentage];

        //boundry condition
        if(progressStringWidth >= self.frame.size.width)
            progressStringWidth = self.frame.size.width-10;

        CGFloat tentativeProgressStringWidth  = (progressStringWidth>20?progressStringWidth:20);

        CGFloat xPos = (self.progressBarDirection == MKSProgressBarDirectionFromLeftToRight) ?
        (self.barPadding + [self progressPercentage] - tentativeProgressStringWidth) : (self.frame.size.width - self.barPadding - [self progressPercentage]);
        CGRect textRect = CGRectMake(xPos, (self.frame.size.height - 21)/2, progressStringWidth, 21);

        NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
        textStyle.alignment = (self.progressBarDirection == MKSProgressBarDirectionFromLeftToRight) ? NSTextAlignmentRight : NSTextAlignmentLeft;
        NSDictionary* textFontAttributes = @{NSFontAttributeName: self.progressPercentageFont, NSForegroundColorAttributeName: self.progressPercentageTextColor, NSParagraphStyleAttributeName: textStyle};

        [[NSString stringWithFormat:@"%d %@",progressValue,@"%"] drawInRect: textRect withAttributes: textFontAttributes];
    }

    CGContextRestoreGState(context);

}

#pragma mark - Progress calculation
- (CGFloat) progressPercentage {
    CGFloat screenWidth = self.frame.size.width - (self.barPadding * 2);
    CGFloat progress = ((self.progressValue / 100) * screenWidth);
    return progress < 0 ? self.barPadding : progress;
}

#pragma mark - Update progress value
- (void)setProgressValue:(CGFloat)progressValue{
    _progressValue = progressValue;

    if(progressValue <= 0)
        self.barColor = [self trackColor];

    [self setNeedsDisplay];
}

@end


text:
#import <PhotosUI/PUValueFilter.h>

@interface PUChangeDirectionValueFilter : PUValueFilter
{
    double _threshold;
    double _minimumChangeValue;
}

@property(nonatomic) double minimumChangeValue; // @synthesize minimumChangeValue=_minimumChangeValue;
- (double)updatedValue:(double)arg1 withTargetValue:(double)arg2;

@end


text:
layout: pattern
title: Command
folder: command
permalink: /patterns/command/
categories: Behavioral
tags:
 - Gang of Four
---

## Also known as

Action, Transaction

## Intent

Encapsulate a request as an object, thereby letting you parameterize clients with different
requests, queue or log requests, and support undoable operations.

## Explanation
Real world example

> There is a wizard casting spells on a goblin. The spells are executed on the goblin one by one.
> The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses
> the spells one by one. Each spell here is a command object that can be undone.

In plain words

> Storing requests as command objects allows performing an action or undoing it at a later time.

Wikipedia says

> In object-oriented programming, the command pattern is a behavioral design pattern in which an
> object is used to encapsulate all information needed to perform an action or trigger an event at
> a later time.

**Programmatic Example**

Here's the sample code with wizard and goblin. Let's start from the `Wizard` class.

```java
public class Wizard {

  private final Deque<Command> undoStack = new LinkedList<>();
  private final Deque<Command> redoStack = new LinkedList<>();

  public Wizard() {}

  public void castSpell(Runnable runnable) {
    runnable.run();
    undoStack.offerLast(runnable);
  }

  public void undoLastSpell() {
    if (!undoStack.isEmpty()) {
      var previousSpell = undoStack.pollLast();
      redoStack.offerLast(previousSpell);
      previousSpell.run();
    }
  }

  public void redoLastSpell() {
    if (!redoStack.isEmpty()) {
      var previousSpell = redoStack.pollLast();
      undoStack.offerLast(previousSpell);
      previousSpell.run();
    }
  }

  @Override
  public String toString() {
    return "Wizard";
  }
}
```

Next, we have the goblin who's the target of the spells.

```java
public abstract class Target {

  private static final Logger LOGGER = LoggerFactory.getLogger(Target.class);

  private Size size;

  private Visibility visibility;

  public Size getSize() {
    return size;
  }

  public void setSize(Size size) {
    this.size = size;
  }

  public Visibility getVisibility() {
    return visibility;
  }

  public void setVisibility(Visibility visibility) {
    this.visibility = visibility;
  }

  @Override
  public abstract String toString();

  public void printStatus() {
    LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility());
  }
}

public class Goblin extends Target {

  public Goblin() {
    setSize(Size.NORMAL);
    setVisibility(Visibility.VISIBLE);
  }

  @Override
  public String toString() {
    return "Goblin";
  }

  public void changeSize() {
    var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL;
    setSize(oldSize);
  }

  public void changeVisibility() {
    var visible = getVisibility() == Visibility.INVISIBLE
          ? Visibility.VISIBLE : Visibility.INVISIBLE;
    setVisibility(visible);
  }
}
```

Finally we have the wizard in main function who casts spell

```java
public static void main(String[] args) {
  var wizard = new Wizard();
  var goblin = new Goblin();

  // casts shrink/unshrink spell
  wizard.castSpell(goblin::changeSize);

  // casts visible/invisible spell
  wizard.castSpell(goblin::changeVisibility);

  // undo and redo casts
   wizard.undoLastSpell();
   wizard.redoLastSpell();
```

Here's the whole example in action.

```java
var wizard = new Wizard();
var goblin = new Goblin();

goblin.printStatus();
wizard.castSpell(goblin::changeSize);
goblin.printStatus();

wizard.castSpell(goblin::changeVisibility);
goblin.printStatus();

wizard.undoLastSpell();
goblin.printStatus();

wizard.undoLastSpell();
goblin.printStatus();

wizard.redoLastSpell();
goblin.printStatus();

wizard.redoLastSpell();
goblin.printStatus();
```

Here's the program output:

```java
Goblin, [size=normal] [visibility=visible]
Goblin, [size=small] [visibility=visible]
Goblin, [size=small] [visibility=invisible]
Goblin, [size=small] [visibility=visible]
Goblin, [size=normal] [visibility=visible]
Goblin, [size=small] [visibility=visible]
Goblin, [size=small] [visibility=invisible]
```

## Class diagram

![alt text](./etc/command.png "Command")

## Applicability

Use the Command pattern when you want to:

* Parameterize objects by an action to perform. You can express such parameterization in a
procedural language with a callback function, that is, a function that's registered somewhere to be
called at a later point. Commands are an object-oriented replacement for callbacks.
* Specify, queue, and execute requests at different times. A Command object can have a lifetime
independent of the original request. If the receiver of a request can be represented in an address
space-independent way, then you can transfer a command object for the request to a different process
and fulfill the request there.
* Support undo. The Command's execute operation can store state for reversing its effects in the
command itself. The Command interface must have an added un-execute operation that reverses the
effects of a previous call to execute. The executed commands are stored in a history list.
Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling
un-execute and execute, respectively.
* Support logging changes so that they can be reapplied in case of a system crash. By augmenting the
Command interface with load and store operations, you can keep a persistent log of changes.
Recovering from a crash involves reloading logged commands from disk and re-executing them with
the execute operation.
* Structure a system around high-level operations build on primitive operations. Such a structure is
common in information systems that support transactions. A transaction encapsulates a set of changes
to data. The Command pattern offers a way to model transactions. Commands have a common interface,
letting you invoke all transactions the same way. The pattern also makes it easy to extend the
system with new transactions.

## Typical Use Case

* To keep a history of requests
* Implement callback functionality
* Implement the undo functionality

## Real world examples

* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)
* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java)
* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki)
* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html)

## Credits

* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94)


text:
<application>
  <component name="IntentionManagerSettings">
    <ignoreAction name="ActionScript/Create Event Handler" />
    <ignoreAction name="ActionScript/Create Getter" />
    <ignoreAction name="ActionScript/Create Getter and Setter" />
    <ignoreAction name="ActionScript/Create Setter" />
    <ignoreAction name="ActionScript/Create Subclass or Implement Interface" />
    <ignoreAction name="Android/Add Parcelable Implementation" />
    <ignoreAction name="Android/Add URL" />
    <ignoreAction name="Android/Create onClick event handler" />
    <ignoreAction name="Android/Extract dimension resource" />
    <ignoreAction name="Android/Extract string resource" />
    <ignoreAction name="Android/Override Resource in Other Configuration..." />
    <ignoreAction name="Android/Remove Parcelable Implementation" />
    <ignoreAction name="Android/Replace Parcelable Implementation" />
  </component>
</application>