text:
package com.alorma.github.ui.fragment.repos;

import android.os.Bundle;

import com.alorma.github.R;
import com.alorma.github.sdk.services.repos.GithubReposClient;
import com.alorma.github.sdk.services.repos.UserReposClient;

public class ReposFragment extends BaseReposListFragment {

    private String username;

    public static ReposFragment newInstance() {
        return new ReposFragment();
    }

    public static ReposFragment newInstance(String username) {
        ReposFragment reposFragment = new ReposFragment();
        if (username != null) {
            Bundle bundle = new Bundle();
            bundle.putString(USERNAME, username);

            reposFragment.setArguments(bundle);
        }
        return reposFragment;
    }

    @Override
    protected void loadArguments() {
        if (getArguments() != null) {
            username = getArguments().getString(USERNAME);
        }
    }

    @Override
    protected void executeRequest() {
        super.executeRequest();

        GithubReposClient client = new UserReposClient(getActivity(), username);
        client.setOnResultCallback(this);
        client.execute();
    }

    @Override
    protected void executePaginatedRequest(int page) {
        super.executePaginatedRequest(page);
        UserReposClient client = new UserReposClient(getActivity(), username, page);
        client.setOnResultCallback(this);
        client.execute();
    }

    @Override
    protected int getNoDataText() {
        return R.string.no_repositories;
    }

}


text:
package com.ghgande.j2mod.modbus.utils;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.facade.ModbusUDPMaster;
import com.ghgande.j2mod.modbus.io.ModbusUDPTransaction;
import com.ghgande.j2mod.modbus.msg.*;
import com.ghgande.j2mod.modbus.net.ModbusUDPListener;
import com.ghgande.j2mod.modbus.net.UDPMasterConnection;
import com.ghgande.j2mod.modbus.procimg.SimpleRegister;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;

import static org.junit.Assert.fail;

/**
 * All the master unit tests extend this class so that the system will automatically
 * create a test slave to work with and tear it down after a run
 *
 * @author Steve O'Hara (4energy)
 * @version 2.0 (March 2016)
 */
public class AbstractTestModbusUDPMaster extends AbstractTestModbus {

    private static final Logger logger = LoggerFactory.getLogger(AbstractTestModbusUDPMaster.class);
    protected static ModbusUDPMaster master;

    @BeforeClass
    public static void setUpSlave() {
        try {
            listener = createUDPSlave();
            master = new ModbusUDPMaster(TestUtils.getFirstIp4Address(), PORT);
            master.connect();
        }
        catch (Exception e) {
            tearDownSlave();
            fail(String.format("Cannot initialise tests - %s", e.getMessage()));
        }
    }

    @AfterClass
    public static void tearDownSlave() {
        if (master != null) {
            master.disconnect();
        }
        if (listener != null && listener.isListening()) {
            listener.stop();
        }
    }

    /**
     * Creates a Slave to use for testing
     *
     * @return Listener of the slave
     *
     * @throws IOException
     */
    public static ModbusUDPListener createUDPSlave() throws Exception {
        ModbusUDPListener listener = null;
        try {
            // Create the test data
            getSimpleProcessImage();

            // Create a UDP listener on the 'all interfaces' address 0.0.0.0
            listener = new ModbusUDPListener();
            listener.setListening(true);
            listener.setPort(PORT);
            listener.setTimeout(5000);
            new Thread(listener).start();

            // Wait here a moment and then check to see if the listener actually started
            Thread.sleep(100);
            if (!listener.isListening()) {
                throw new Exception(listener.getError());
            }
        }
        catch (Exception x) {
            if (listener != null) {
                listener.stop();
            }
            throw new Exception(x.getMessage());
        }
        return listener;
    }

    /**
     * Executes a read transaction using the function code, register and count
     *
     * @param functionCode Function code to use
     * @param register     Register number
     * @param count        Number of registers
     *
     * @return Response object
     */
    protected static ModbusResponse readRequest(int functionCode, int register, int count) {
        ModbusUDPTransaction trans;
        UDPMasterConnection connection = null;
        try {
            // Prepare the connection

            connection = new UDPMasterConnection(InetAddress.getByName(TestUtils.getFirstIp4Address()));
            connection.setPort(PORT);
            connection.connect();
            connection.setTimeout(500);
            ModbusRequest req = null;

            // Prepare the request
            switch (functionCode) {
                case Modbus.READ_COILS:
                    req = new ReadCoilsRequest(register, count);
                    break;
                case Modbus.READ_INPUT_DISCRETES:
                    req = new ReadInputDiscretesRequest(register, count);
                    break;
                case Modbus.READ_INPUT_REGISTERS:
                    req = new ReadInputRegistersRequest(register, count);
                    break;
                case Modbus.READ_HOLDING_REGISTERS:
                    req = new ReadMultipleRegistersRequest(register, count);
                    break;
                default:
                    fail(String.format("Request type %d is not supported by the test harness", functionCode));
            }
            req.setUnitID(UNIT_ID);

            // Prepare the transaction
            trans = new ModbusUDPTransaction(connection);
            trans.setRequest(req);

            // Execute the transaction
            trans.execute();
            return trans.getResponse();
        }
        catch (Exception e) {
            logger.debug(e.getMessage());
        }
        finally {
            if (connection != null) {
                connection.close();
            }
        }
        return null;
    }

    /**
     * Executes a write transaction using the function code, register and value
     *
     * @param functionCode Function code to use
     * @param register     Register number
     * @param value        Value to apply
     *
     * @return Response object
     */
    protected static ModbusResponse writeRequest(int functionCode, int register, int value) {
        ModbusUDPTransaction trans;
        UDPMasterConnection connection = null;
        try {
            // Prepare the connection
            connection = new UDPMasterConnection(InetAddress.getByName(TestUtils.getFirstIp4Address()));
            connection.setPort(Modbus.DEFAULT_PORT);
            connection.setPort(PORT);
            connection.connect();
            connection.setTimeout(500);
            ModbusRequest req = null;

            // Prepare the request
            switch (functionCode) {
                case Modbus.WRITE_COIL:
                    req = new WriteCoilRequest(register, value != 0);
                    break;
                case Modbus.WRITE_SINGLE_REGISTER:
                    req = new WriteSingleRegisterRequest(register, new SimpleRegister(value));
                    break;
                default:
                    fail(String.format("Request type %d is not supported by the test harness", functionCode));
            }
            req.setUnitID(UNIT_ID);

            // Prepare the transaction
            trans = new ModbusUDPTransaction(connection);
            trans.setRequest(req);

            // Execute the transaction
            trans.execute();
            return trans.getResponse();
        }
        catch (Exception e) {
            logger.debug(e.getMessage());
        }
        finally {
            if (connection != null) {
                connection.close();
            }
        }
        return null;
    }

}

redpajama_set_name: RedPajamaGithub


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

namespace Fearfry {
    public delegate void Interact();
    public abstract class InSceneObject {
        public event Interact InteractEvent;
        public abstract void Update();
        public abstract void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch batch);
    }
}


text:
package io.crate.expression.tablefunctions;

import org.junit.Test;

public class GenerateSeriesTest extends AbstractTableFunctionsTest {

    @Test
    public void testFrom3To4WithDefaultStep() {
        assertExecute(
            "generate_series(3, 4)",
            "3\n" +
            "4\n"
        );
    }

    @Test
    public void test_generate_series_can_be_addressed_via_pg_catalog_schema() {
        assertExecute(
            "pg_catalog.generate_series(3, 4)",
            "3\n" +
            "4\n"
        );
    }

    @Test
    public void from2To8With2AsStep() {
        assertExecute(
            "generate_series(2, 8, 2)",
            "2\n" +
            "4\n" +
            "6\n" +
            "8\n"
        );
    }

    @Test
    public void testGenerateSeriesWithIntegerArguments() {
        assertExecute("generate_series(1::int, 3::int)", "1\n2\n3\n");
    }

    @Test
    public void testResultIsEmptyIfStartIsNull() {
        assertExecute("generate_series(null, 10)", "");
    }

    @Test
    public void testResultIsEmptyIfStopIsNull() {
        assertExecute("generate_series(1, null)", "");
    }

    @Test
    public void testResultIsEmptyIfStepIsNull() {
        assertExecute("generate_series(1, 2, null)", "");
    }

    @Test
    public void testStartIsReturnedIfStepIsBiggerThanStop() {
        assertExecute(
            "generate_series(1, 4, 8)",
            "1\n"
        );
    }

    @Test
    public void testEmptyOutputIfStartIsHigherThanStopWithDefaultStep() {
        assertExecute("generate_series(10, 1)", "");
    }

    @Test
    public void testNegativeStepsWorkIfStartIsHigherThanStop() {
        assertExecute(
            "generate_series(4, 1, -1)",
            "4\n" +
            "3\n" +
            "2\n" +
            "1\n");
    }

    @Test
    public void testNegativeStartToPositiveEnd() {
        assertExecute(
            "generate_series(-2, 2, 1)",
            "-2\n" +
            "-1\n" +
            "0\n" +
            "1\n" +
            "2\n"
        );
    }

    @Test
    public void test_generate_interval_from_start_date_to_end_date_with_10_hours_interval() {
        assertExecute(
            "generate_series('2008-03-01 00:00'::timestamp, '2008-03-04 12:00'::timestamp, '10 hours'::interval)",
            "1204329600000\n" +
            "1204365600000\n" +
            "1204401600000\n" +
            "1204437600000\n" +
            "1204473600000\n" +
            "1204509600000\n" +
            "1204545600000\n" +
            "1204581600000\n" +
            "1204617600000\n"
        );
    }

    @Test
    public void test_generate_interval_from_start_date_to_end_date_with_minus_10_hours_interval() {
        assertExecute(
            "generate_series('2008-03-05 00:00'::timestamp, '2008-03-04 12:00'::timestamp, '-10 hours'::interval)",
            "1204675200000\n" +
            "1204639200000\n"
        );
    }

    @Test
    public void test_generate_series_with_interval_and_null_values_results_in_empty_result() {
        assertExecute(
            "generate_series(null::timestamp, '2019-03-04'::timestamp, '1 days'::interval)",
            ""
        );
    }

    @Test
    public void test_generate_series_with_start_after_end_and_positive_step_returns_empty_result() {
        assertExecute(
            "generate_series('2020-01-01'::timestamp, '2019-03-04'::timestamp, '1 days -4 hours'::interval)",
            ""
        );
    }

    @Test
    public void test_step_is_mandatory_for_timestamps() {
        expectedException.expectMessage(
            "generate_series(start, stop) has type `timestamp with time zone` for start, but requires long/int values for start and stop, or if used with timestamps, it requires a third argument for the step (interval)");
        assertExecute("generate_series(null::timestamp, '2019-03-04'::timestamp)", "");
    }
}


text:
title: "Best Time to Buy and Sell Stock"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "python"]
categories: ["algorithm"]
date: 2018-09-06T23:37:49+08:00
draft: false
archive: false
---
Say you have an array for which the `ith` element is the price of a given stock on day `i`.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

### Example 1
```python
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.
```
### Example 2
```python
Input: [7,6,4,3,1]
Output: 0
```
### Explanation In this case, no transaction is done, i.e. max profit = 0.

### Solution
```python
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit, minPrice = 0, 0

        for i in range(len(prices)):
            if i == 0:
                minPrice = prices[i]
            else:
                if (prices[i] < minPrice):
                    minPrice = prices[i]
                elif (prices[i] - minPrice > profit):
                    profit = prices[i] - minPrice

        return profit
```


text:
package bootstrap

import (
	"fmt"
	"github.com/google/blueprint"
	"github.com/google/blueprint/pathtools"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

const bootstrapDir = ".bootstrap"

var (
	pctx = blueprint.NewPackageContext("github.com/google/blueprint/bootstrap")

	gcCmd   = pctx.StaticVariable("gcCmd", "$goToolDir/${goChar}g")
	linkCmd = pctx.StaticVariable("linkCmd", "$goToolDir/${goChar}l")

	// Ninja only reinvokes itself once when it regenerates a .ninja file. For
	// the re-bootstrap process we need that to happen more than once, so we
	// invoke an additional Ninja process from the rebootstrap rule.
	// Unfortunately this seems to cause "warning: bad deps log signature or
	// version; starting over" messages from Ninja. This warning can be
	// avoided by having the bootstrap and non-bootstrap build manifests have
	// a different builddir (so they use different log files).
	//
	// This workaround can be avoided entirely by making a simple change to
	// Ninja that would allow it to rebuild the manifest multiple times rather
	// than just once.  If the Ninja being used is capable of this, then the
	// workaround we're doing can be disabled by setting the
	// BLUEPRINT_NINJA_HAS_MULTIPASS environment variable to a true value.
	runChildNinja = pctx.VariableFunc("runChildNinja",
		func(config interface{}) (string, error) {
			if ninjaHasMultipass(config) {
				return "", nil
			} else {
				return " && ninja", nil
			}
		})

	gc = pctx.StaticRule("gc",
		blueprint.RuleParams{
			Command: "GOROOT='$goRoot' $gcCmd -o $out -p $pkgPath -complete " +
				"$incFlags -pack $in",
			Description: "${goChar}g $out",
		},
		"pkgPath", "incFlags")

	link = pctx.StaticRule("link",
		blueprint.RuleParams{
			Command:     "GOROOT='$goRoot' $linkCmd -o $out $libDirFlags $in",
			Description: "${goChar}l $out",
		},
		"libDirFlags")

	cp = pctx.StaticRule("cp",
		blueprint.RuleParams{
			Command:     "cp $in $out",
			Description: "cp $out",
		},
		"generator")

	bootstrap = pctx.StaticRule("bootstrap",
		blueprint.RuleParams{
			Command:     "$bootstrapCmd -i $in",
			Description: "bootstrap $in",
			Generator:   true,
		})

	rebootstrap = pctx.StaticRule("rebootstrap",
		blueprint.RuleParams{
			Command:     "$bootstrapCmd -i $in$runChildNinja",
			Description: "re-bootstrap $in",
			Generator:   true,
		})

	// Work around a Ninja issue.  See https://github.com/martine/ninja/pull/634
	phony = pctx.StaticRule("phony",
		blueprint.RuleParams{
			Command:     "# phony $out",
			Description: "phony $out",
			Generator:   true,
		},
		"depfile")

	BinDir     = filepath.Join(bootstrapDir, "bin")
	minibpFile = filepath.Join(BinDir, "minibp")
)

type goPackageProducer interface {
	GoPkgRoot() string
	GoPackageTarget() string
}

func isGoPackageProducer(module blueprint.Module) bool {
	_, ok := module.(goPackageProducer)
	return ok
}

func isBootstrapModule(module blueprint.Module) bool {
	_, isPackage := module.(*goPackage)
	_, isBinary := module.(*goBinary)
	return isPackage || isBinary
}

func isBootstrapBinaryModule(module blueprint.Module) bool {
	_, isBinary := module.(*goBinary)
	return isBinary
}

func generatingBootstrapper(config interface{}) bool {
	bootstrapConfig, ok := config.(Config)
	if ok {
		return bootstrapConfig.GeneratingBootstrapper()
	}
	return false
}

// ninjaHasMultipass returns true if Ninja will perform multiple passes
// that can regenerate the build manifest.
func ninjaHasMultipass(config interface{}) bool {
	envString := os.Getenv("BLUEPRINT_NINJA_HAS_MULTIPASS")
	envValue, err := strconv.ParseBool(envString)
	if err != nil {
		return false
	}
	return envValue
}

// A goPackage is a module for building Go packages.
type goPackage struct {
	properties struct {
		PkgPath string
		Srcs    []string
	}

	// The root dir in which the package .a file is located.  The full .a file
	// path will be "packageRoot/PkgPath.a"
	pkgRoot string

	// The path of the .a file that is to be built.
	archiveFile string
}

var _ goPackageProducer = (*goPackage)(nil)

func newGoPackageModule() (blueprint.Module, []interface{}) {
	module := &goPackage{}
	return module, []interface{}{&module.properties}
}

func (g *goPackage) GoPkgRoot() string {
	return g.pkgRoot
}

func (g *goPackage) GoPackageTarget() string {
	return g.archiveFile
}

func (g *goPackage) GenerateBuildActions(ctx blueprint.ModuleContext) {
	name := ctx.ModuleName()

	if g.properties.PkgPath == "" {
		ctx.ModuleErrorf("module %s did not specify a valid pkgPath", name)
		return
	}

	g.pkgRoot = packageRoot(ctx)
	g.archiveFile = filepath.Clean(filepath.Join(g.pkgRoot,
		filepath.FromSlash(g.properties.PkgPath)+".a"))

	// We only actually want to build the builder modules if we're running as
	// minibp (i.e. we're generating a bootstrap Ninja file).  This is to break
	// the circular dependence that occurs when the builder requires a new Ninja
	// file to be built, but building a new ninja file requires the builder to
	// be built.
	if generatingBootstrapper(ctx.Config()) {
		buildGoPackage(ctx, g.pkgRoot, g.properties.PkgPath, g.archiveFile,
			g.properties.Srcs)
	} else {
		phonyGoTarget(ctx, g.archiveFile, g.properties.Srcs, nil)
	}
}

// A goBinary is a module for building executable binaries from Go sources.
type goBinary struct {
	properties struct {
		Srcs           []string
		PrimaryBuilder bool
	}
}

func newGoBinaryModule() (blueprint.Module, []interface{}) {
	module := &goBinary{}
	return module, []interface{}{&module.properties}
}

func (g *goBinary) GenerateBuildActions(ctx blueprint.ModuleContext) {
	var (
		name        = ctx.ModuleName()
		objDir      = moduleObjDir(ctx)
		archiveFile = filepath.Join(objDir, name+".a")
		aoutFile    = filepath.Join(objDir, "a.out")
		binaryFile  = filepath.Join(BinDir, name)
	)

	// We only actually want to build the builder modules if we're running as
	// minibp (i.e. we're generating a bootstrap Ninja file).  This is to break
	// the circular dependence that occurs when the builder requires a new Ninja
	// file to be built, but building a new ninja file requires the builder to
	// be built.
	if generatingBootstrapper(ctx.Config()) {
		buildGoPackage(ctx, objDir, name, archiveFile, g.properties.Srcs)

		var libDirFlags []string
		ctx.VisitDepsDepthFirstIf(isGoPackageProducer,
			func(module blueprint.Module) {
				dep := module.(goPackageProducer)
				libDir := dep.GoPkgRoot()
				libDirFlags = append(libDirFlags, "-L "+libDir)
			})

		linkArgs := map[string]string{}
		if len(libDirFlags) > 0 {
			linkArgs["libDirFlags"] = strings.Join(libDirFlags, " ")
		}

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:      link,
			Outputs:   []string{aoutFile},
			Inputs:    []string{archiveFile},
			Implicits: []string{"$linkCmd"},
			Args:      linkArgs,
		})

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    cp,
			Outputs: []string{binaryFile},
			Inputs:  []string{aoutFile},
		})
	} else {
		intermediates := []string{aoutFile, archiveFile}
		phonyGoTarget(ctx, binaryFile, g.properties.Srcs, intermediates)
	}
}

func buildGoPackage(ctx blueprint.ModuleContext, pkgRoot string,
	pkgPath string, archiveFile string, srcs []string) {

	srcDir := moduleSrcDir(ctx)
	srcFiles := pathtools.PrefixPaths(srcs, srcDir)

	var incFlags []string
	deps := []string{"$gcCmd"}
	ctx.VisitDepsDepthFirstIf(isGoPackageProducer,
		func(module blueprint.Module) {
			dep := module.(goPackageProducer)
			incDir := dep.GoPkgRoot()
			target := dep.GoPackageTarget()
			incFlags = append(incFlags, "-I "+incDir)
			deps = append(deps, target)
		})

	gcArgs := map[string]string{
		"pkgPath": pkgPath,
	}

	if len(incFlags) > 0 {
		gcArgs["incFlags"] = strings.Join(incFlags, " ")
	}

	ctx.Build(pctx, blueprint.BuildParams{
		Rule:      gc,
		Outputs:   []string{archiveFile},
		Inputs:    srcFiles,
		Implicits: deps,
		Args:      gcArgs,
	})
}

func phonyGoTarget(ctx blueprint.ModuleContext, target string, srcs []string,
	intermediates []string) {

	var depTargets []string
	ctx.VisitDepsDepthFirstIf(isGoPackageProducer,
		func(module blueprint.Module) {
			dep := module.(goPackageProducer)
			target := dep.GoPackageTarget()
			depTargets = append(depTargets, target)
		})

	moduleDir := ctx.ModuleDir()
	srcs = pathtools.PrefixPaths(srcs, filepath.Join("$srcDir", moduleDir))

	ctx.Build(pctx, blueprint.BuildParams{
		Rule:      phony,
		Outputs:   []string{target},
		Inputs:    srcs,
		Implicits: depTargets,
	})

	// If one of the source files gets deleted or renamed that will prevent the
	// re-bootstrapping happening because it depends on the missing source file.
	// To get around this we add a build statement using the built-in phony rule
	// for each source file, which will cause Ninja to treat it as dirty if its
	// missing.
	for _, src := range srcs {
		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    blueprint.Phony,
			Outputs: []string{src},
		})
	}

	// If there is no rule to build the intermediate files of a bootstrap go package
	// the cleanup phase of the primary builder will delete the intermediate files,
	// forcing an unnecessary rebuild.  Add phony rules for all of them.
	for _, intermediate := range intermediates {
		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    blueprint.Phony,
			Outputs: []string{intermediate},
		})
	}

}

type singleton struct{}

func newSingleton() blueprint.Singleton {
	return &singleton{}
}

func (s *singleton) GenerateBuildActions(ctx blueprint.SingletonContext) {
	// Find the module that's marked as the "primary builder", which means it's
	// creating the binary that we'll use to generate the non-bootstrap
	// build.ninja file.
	var primaryBuilders []*goBinary
	var allGoBinaries []string
	ctx.VisitAllModulesIf(isBootstrapBinaryModule,
		func(module blueprint.Module) {
			binaryModule := module.(*goBinary)
			binaryModuleName := ctx.ModuleName(binaryModule)
			binaryModulePath := filepath.Join(BinDir, binaryModuleName)
			allGoBinaries = append(allGoBinaries, binaryModulePath)
			if binaryModule.properties.PrimaryBuilder {
				primaryBuilders = append(primaryBuilders, binaryModule)
			}
		})

	var primaryBuilderName, primaryBuilderExtraFlags string
	switch len(primaryBuilders) {
	case 0:
		// If there's no primary builder module then that means we'll use minibp
		// as the primary builder.  We can trigger its primary builder mode with
		// the -p flag.
		primaryBuilderName = "minibp"
		primaryBuilderExtraFlags = "-p"

	case 1:
		primaryBuilderName = ctx.ModuleName(primaryBuilders[0])

	default:
		ctx.Errorf("multiple primary builder modules present:")
		for _, primaryBuilder := range primaryBuilders {
			ctx.ModuleErrorf(primaryBuilder, "<-- module %s",
				ctx.ModuleName(primaryBuilder))
		}
		return
	}

	primaryBuilderFile := filepath.Join(BinDir, primaryBuilderName)

	// Get the filename of the top-level Blueprints file to pass to minibp.
	// This comes stored in a global variable that's set by Main.
	topLevelBlueprints := filepath.Join("$srcDir",
		filepath.Base(topLevelBlueprintsFile))

	mainNinjaFile := filepath.Join(bootstrapDir, "main.ninja.in")
	mainNinjaDepFile := mainNinjaFile + ".d"
	bootstrapNinjaFile := filepath.Join(bootstrapDir, "bootstrap.ninja.in")

	if generatingBootstrapper(ctx.Config()) {
		// We're generating a bootstrapper Ninja file, so we need to set things
		// up to rebuild the build.ninja file using the primary builder.

		// Because the non-bootstrap build.ninja file manually re-invokes Ninja,
		// its builddir must be different than that of the bootstrap build.ninja
		// file.  Otherwise we occasionally get "warning: bad deps log signature
		// or version; starting over" messages from Ninja, presumably because
		// two Ninja processes try to write to the same log concurrently.
		ctx.SetBuildDir(pctx, bootstrapDir)

		// We generate the depfile here that includes the dependencies for all
		// the Blueprints files that contribute to generating the big build
		// manifest (build.ninja file).  This depfile will be used by the non-
		// bootstrap build manifest to determine whether it should trigger a re-
		// bootstrap.  Because the re-bootstrap rule's output is "build.ninja"
		// we need to force the depfile to have that as its "make target"
		// (recall that depfiles use a subset of the Makefile syntax).
		bigbp := ctx.Rule(pctx, "bigbp",
			blueprint.RuleParams{
				Command: fmt.Sprintf("%s %s -d %s -m $bootstrapManifest "+
					"-o $out $in", primaryBuilderFile,
					primaryBuilderExtraFlags, mainNinjaDepFile),
				Description: fmt.Sprintf("%s $out", primaryBuilderName),
				Depfile:     mainNinjaDepFile,
			})

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:      bigbp,
			Outputs:   []string{mainNinjaFile},
			Inputs:    []string{topLevelBlueprints},
			Implicits: allGoBinaries,
		})

		// When the current build.ninja file is a bootstrapper, we always want
		// to have it replace itself with a non-bootstrapper build.ninja.  To
		// accomplish that we depend on a file that should never exist and
		// "build" it using Ninja's built-in phony rule.
		//
		// We also need to add an implicit dependency on bootstrapNinjaFile so
		// that it gets generated as part of the bootstrap process.
		notAFile := filepath.Join(bootstrapDir, "notAFile")
		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    blueprint.Phony,
			Outputs: []string{notAFile},
		})

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:      bootstrap,
			Outputs:   []string{"build.ninja"},
			Inputs:    []string{mainNinjaFile},
			Implicits: []string{"$bootstrapCmd", notAFile, bootstrapNinjaFile},
		})

		// Rebuild the bootstrap Ninja file using the minibp that we just built.
		// The checkFile tells minibp to compare the new bootstrap file to the
		// current one.  If the files are the same then minibp sets the new
		// file's mtime to match that of the current one.  If they're different
		// then the new file will have a newer timestamp than the current one
		// and it will trigger a reboostrap by the non-boostrap build manifest.
		minibp := ctx.Rule(pctx, "minibp",
			blueprint.RuleParams{
				Command: fmt.Sprintf("%s -c $checkFile -m $bootstrapManifest "+
					"-d $out.d -o $out $in", minibpFile),
				Description: "minibp $out",
				Generator:   true,
				Depfile:     "$out.d",
			},
			"checkFile")

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:      minibp,
			Outputs:   []string{bootstrapNinjaFile},
			Inputs:    []string{topLevelBlueprints},
			Implicits: []string{minibpFile},
			Args: map[string]string{
				"checkFile": "$bootstrapManifest",
			},
		})
	} else {
		// We're generating a non-bootstrapper Ninja file, so we need to set it
		// up to depend on the bootstrapper Ninja file.  The build.ninja target
		// also has an implicit dependency on the primary builder and all other
		// bootstrap go binaries, which will have phony dependencies on all of
		// their sources.  This will cause any changes to a bootstrap binary's
		// sources to trigger a re-bootstrap operation, which will rebuild the
		// binary.
		//
		// On top of that we need to use the depfile generated by the bigbp
		// rule.  We do this by depending on that file and then setting up a
		// phony rule to generate it that uses the depfile.
		buildNinjaDeps := []string{"$bootstrapCmd", mainNinjaFile}
		buildNinjaDeps = append(buildNinjaDeps, allGoBinaries...)
		ctx.Build(pctx, blueprint.BuildParams{
			Rule:      rebootstrap,
			Outputs:   []string{"build.ninja"},
			Inputs:    []string{"$bootstrapManifest"},
			Implicits: buildNinjaDeps,
		})

		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    phony,
			Outputs: []string{mainNinjaFile},
			Inputs:  []string{topLevelBlueprints},
			Args: map[string]string{
				"depfile": mainNinjaDepFile,
			},
		})

		// If the bootstrap Ninja invocation caused a new bootstrapNinjaFile to be
		// generated then that means we need to rebootstrap using it instead of
		// the current bootstrap manifest.  We enable the Ninja "generator"
		// behavior so that Ninja doesn't invoke this build just because it's
		// missing a command line log entry for the bootstrap manifest.
		ctx.Build(pctx, blueprint.BuildParams{
			Rule:    cp,
			Outputs: []string{"$bootstrapManifest"},
			Inputs:  []string{bootstrapNinjaFile},
			Args: map[string]string{
				"generator": "true",
			},
		})

		if primaryBuilderName == "minibp" {
			// This is a standalone Blueprint build, so we copy the minibp
			// binary to the "bin" directory to make it easier to find.
			finalMinibp := filepath.Join("bin", primaryBuilderName)
			ctx.Build(pctx, blueprint.BuildParams{
				Rule:    cp,
				Inputs:  []string{primaryBuilderFile},
				Outputs: []string{finalMinibp},
			})
		}
	}
}

// packageRoot returns the module-specific package root directory path.  This
// directory is where the final package .a files are output and where dependant
// modules search for this package via -I arguments.
func packageRoot(ctx blueprint.ModuleContext) string {
	return filepath.Join(bootstrapDir, ctx.ModuleName(), "pkg")
}

// moduleSrcDir returns the path of the directory that all source file paths are
// specified relative to.
func moduleSrcDir(ctx blueprint.ModuleContext) string {
	return filepath.Join("$srcDir", ctx.ModuleDir())
}

// moduleObjDir returns the module-specific object directory path.
func moduleObjDir(ctx blueprint.ModuleContext) string {
	return filepath.Join(bootstrapDir, ctx.ModuleName(), "obj")
}


text:
import React from 'react'
import type { ParagraphProps } from '../..'
import { Aside, Box2, Paragraph } from '../..'
import { TreeBranch, TreeCollection } from '../../Tree'
import { LkFieldGroupTree, LkFieldViewTree } from '..'
import { FieldPickerItem } from './FieldPickerItem'

const FieldGroupHeading = (props: ParagraphProps) => (
  <Paragraph
    color="text1"
    fontSize="xxsmall"
    fontWeight="semiBold"
    pt="medium"
    pb="xxsmall"
    pl="xxsmall"
    truncate
    style={{ lineHeight: '0.75rem' }}
    {...props}
  />
)

const fields = (
  <>
    <TreeBranch>
      <FieldGroupHeading pt="none">DIMENSIONS</FieldGroupHeading>
    </TreeBranch>
    <LkFieldGroupTree color="dimension" selected label={<Box2>Created</Box2>}>
      <FieldPickerItem>Created Date</FieldPickerItem>
      <FieldPickerItem selected>Created Month</FieldPickerItem>
      <FieldPickerItem>Created Year</FieldPickerItem>
    </LkFieldGroupTree>
    <FieldPickerItem>City</FieldPickerItem>
    <FieldPickerItem selected filter>
      This is a really long field name to show that truncation is working as
      desired. It's not a realistic example but it lets our tests know that
      things are working as-desired
    </FieldPickerItem>
    <FieldPickerItem>ID</FieldPickerItem>
    <TreeBranch>
      <FieldGroupHeading color="measure">MEASURES</FieldGroupHeading>
    </TreeBranch>
    <FieldPickerItem color="measure" selected>
      Sum
    </FieldPickerItem>
    <FieldPickerItem color="measure" filter>
      Max
    </FieldPickerItem>
    <TreeBranch>
      <FieldGroupHeading color="calculation">CALCULATED</FieldGroupHeading>
    </TreeBranch>
    <FieldPickerItem pivot color="calculation">
      Calc
    </FieldPickerItem>
  </>
)

export const FieldPicker = () => (

    <TreeCollection>
      <LkFieldViewTree defaultOpen detail={3} label={Orders}>
        {fields}
      </LkFieldViewTree>
      <LkFieldViewTree label={Order Items}>
        {fields}
      </LkFieldViewTree>
      <LkFieldViewTree label={Users}>{fields}</LkFieldViewTree>
    </TreeCollection>

)


text:
package com.adaptris.core.services.jdbc.types;

import com.adaptris.jdbc.JdbcResultRow;

import junit.framework.TestCase;

public class IntegerColumnTranslatorTest extends TestCase {

  private IntegerColumnTranslator translator;
  String expected = "00123";

  public void setUp() throws Exception {
    translator = new IntegerColumnTranslator();
  }

  public void testFormattedFloat() throws Exception {
    translator.setFormat("%05d");
    Float intVal = new Float("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", intVal);

    try {
      translator.translate(row, 0);
    } catch (Exception ex) {
      // expected
    }
  }

  public void testFormattedDouble() throws Exception {
    translator.setFormat("%05d");
    Double doubleVal = new Double("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", doubleVal);

    try {
      translator.translate(row, 0);
    } catch (Exception ex) {
      // expected
    }
  }

  public void testFormattedInteger() throws Exception {
    translator.setFormat("%05d");
    Integer intVal = new Integer("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", intVal);

    String translated = translator.translate(row, 0);

    assertEquals(expected, translated);
  }

  public void testFormattedIntegerColumnName() throws Exception {
    translator.setFormat("%05d");
    Integer intVal = new Integer("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", intVal);

    String translated = translator.translate(row, "testField");

    assertEquals(expected, translated);
  }

  public void testFormattedString() throws Exception {
    translator.setFormat("%05d");
    String stringVal = new String("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", stringVal);

    String translated = translator.translate(row, 0);

    assertEquals(expected, translated);
  }

  public void testIllegalFormat() throws Exception {
    translator.setFormat("%zZX");
    Integer intVal = new Integer("123");

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", intVal);

    try {
      translator.translate(row, 0);
    } catch (Exception ex) {
      //expected
    }
  }

}


text:
package scalapb.textformat

sealed trait TValue {
  def position: Position
}

sealed trait TPrimitive extends TValue {
  def asString: String
}

final case class TField(position: Position, name: String, value: TValue)

final case class TIntLiteral(position: Position, value: BigInt) extends TPrimitive {
  def asString = value.toString()
}

final case class TLiteral(position: Position, value: String) extends TPrimitive {
  def asString = value
}

final case class TBytes(position: Position, value: String) extends TPrimitive {
  def asString = value
}

final case class TMessage(position: Position, fields: Seq[TField]) extends TValue

final case class TArray(position: Position, values: Seq[TValue]) extends TValue


text:
.class public final Lcom/android/settings/inputmethod/KeyboardLayoutDialogFragment$Keyboards;
.super Ljava/lang/Object;
.source "KeyboardLayoutDialogFragment.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settings/inputmethod/KeyboardLayoutDialogFragment;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Keyboards"
.end annotation

# instance fields
.field public current:I

.field public final keyboardLayouts:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/hardware/input/KeyboardLayout;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Lcom/android/settings/inputmethod/KeyboardLayoutDialogFragment$Keyboards;->keyboardLayouts:Ljava/util/ArrayList;

    const/4 v0, -0x1

    iput v0, p0, Lcom/android/settings/inputmethod/KeyboardLayoutDialogFragment$Keyboards;->current:I

    return-void
.end method


text:
from django.core.checks import messages
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import render, render_to_response, redirect
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import (
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Caja, CajaCajero, Remesa
from .forms import CashierForm, BoxCashierForm, ConsignmentForm, CajaChicaConsignmentForm
from .filters import ConsignmentFilter
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from django.conf import settings
from utils.middleware import validar_roles
from django.http import HttpResponseRedirect

from django.contrib.auth import authenticate
from django.http import HttpResponse
from django.db import models
from profiles.models import BaseProfile as Profile

from utils.middleware import get_current_request

from utils.views import MyLoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from utils.middleware import get_current_user, get_current_colegio
from register.models import PersonalColegio, Personal, Profile
from django.contrib.auth import get_user_model
import json

User = get_user_model()

def index(request):
    return render(request, 'cash/index.html')

#################################################
#####          CRUD DE CAJA                 #####
#################################################

class CashierListView(MyLoginRequiredMixin, ListView):
    model = Caja
    template_name = 'cashier/cashier_list.html'

    @method_decorator(permission_required('cash.Cashier_List', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):

            return super(CashierListView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def get_context_data(self, **kwargs):
        context = super(CashierListView, self).get_context_data(**kwargs)
        roles = ['administrativo', 'tesorero']
        context['es_tesorero'] = validar_roles(roles=roles)
        request = get_current_request()

        puede_editar_caja = ['tesorero']
        if validar_roles(roles=puede_editar_caja):
            puede_ver = True
        else:
            puede_ver = False

        if request.session.get('colegio'):
            id = request.session.get('colegio')
            context['idcolegio'] = id
            context['permiso_para_editar'] = puede_ver
        return context

"""
class CashierDetailView(DetailView):
    template_name = 'cashier/cashier_detail.html'
    model = Caja
"""

class CashierDetailView(UpdateView):
    model = Caja
    form_class = CashierForm
    template_name = 'cashier/cashier_detail.html'

    @method_decorator(permission_required('cash.Cashier_Detail', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):
            return super(CashierDetailView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

class CashierCreationView(CreateView):
    model = Caja
    form_class = CashierForm
    success_url = reverse_lazy('cash:cashier_list')
    template_name = 'cashier/cashier_form.html'

    @method_decorator(permission_required('cash.Cashier_Creation', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero']

        if validar_roles(roles=roles):
            return super(CashierCreationView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def form_valid(self, form):
        obj = form.save(commit=False)
        cole_id = get_current_colegio()
        numero_caja = obj.numero
        if Caja.objects.filter(colegio_id=cole_id, numero=numero_caja, eliminado=True).exists():
            return HttpResponse(
                "<script>alert('Este número de caja ya existe!!');window.history.back();</script>")

        else:
            obj.save()
            # print ('No existe, fue creado con exito ')
            # print ("====================================")
            return super(CashierCreationView, self).form_valid(form)

class CashierUpdateView(UpdateView):
    model = Caja
    form_class = CashierForm
    success_url = reverse_lazy('cash:cashier_list')
    template_name = 'cashier/cashier_form.html'

    # fields = ['id_remesa', 'id_persona', 'id_movimiento', 'fechacreacion', 'monto', 'comentario']

    @method_decorator(permission_required('cash.Cashier_Delete', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero']

        if validar_roles(roles=roles):
            return super(CashierUpdateView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

"""

class CashierDeleteView(DeleteView):
    model = Caja
    success_url = reverse_lazy('cash:cashier_list')
    template_name = 'cashier/cashier_confirm_delete.html'
"""

class CashierDeleteView(UpdateView):
    model = Caja
    form_class = CashierForm
    success_url = reverse_lazy('cash:cashier_list')
    template_name = 'cashier/cashier_confirm_delete.html'

    @method_decorator(permission_required('cash.Cashier_Delete', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero']

        if validar_roles(roles=roles):
            return super(CashierDeleteView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

#################################################
#####          CRUD DE CAJACAJERO           #####
#################################################

class BoxCashierListView(ListView):
    model = CajaCajero
    template_name = 'boxcashier/boxcashier_list.html'

    @method_decorator(permission_required('cash.Box_Cashier_List', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):
            return super(BoxCashierListView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def get_context_data(self, **kwargs):
        context = super(BoxCashierListView, self).get_context_data(**kwargs)

        roles = ['cajero']
        context['es_cajero'] = validar_roles(roles=roles)
        request = get_current_request()
        user_id = get_current_user().id
        personal_colegio_id = PersonalColegio.objects.values('pk').filter(personal_id__persona_id__user_id=user_id)[0][
            'pk']
        puede_ver_lista = ['promotor', 'director', 'tesorero']
        if validar_roles(roles=puede_ver_lista):
            puede_ver = True
        else:
            puede_ver = False

        if request.session.get('colegio'):
            id = request.session.get('colegio')
            context['idcolegio'] = id
            context['personal_id_cajero'] = personal_colegio_id
            context['permisos_valido'] = puede_ver

        return context

class BoxCashierDetailView(DetailView):
    model = CajaCajero
    template_name = 'boxcashier/boxcashier_detail.html'

    @method_decorator(permission_required('cash.Box_Cashier_Detail', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):
            return super(BoxCashierDetailView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

class BoxCashierCreationView(CreateView):
    model = CajaCajero
    form_class = BoxCashierForm

    success_url = reverse_lazy('cash:boxcashier_list')
    template_name = 'boxcashier/boxcashier_formApertura.html'

    # Paso el ID del usuario al template y en el template selecciono la opción con ese ID del usuario que crea

    def get_context_data(self, **kwargs):
        context = super(BoxCashierCreationView, self).get_context_data(**kwargs)

        usuario = get_current_user()
        if usuario is not None:
            iduser = usuario.id
        else:
            iduser = -1

        a = Profile.objects.get(user_id=iduser)
        b = Personal.objects.get(persona=a)
        #            c = PersonalColegio.objects.get(personal_id=b)
        #           d = PersonalColegio.objects.filter(personal_id=b).values('pk')
        #            print(PersonalColegio.objects.values('pk').filter(personal_id=b)[0]['pk'])

        #            print(Caja.objects.filter(colegio_id=1))
        # creacion
        # context['yolencios'] = d
        #            print(PersonalColegio.objects.values('pk').filter(personal_id=b)[0]['pk'])
        personal_colegio = PersonalColegio.objects.get(personal=b)
        context['yolencios'] = personal_colegio.id_personal_colegio
        return context

    @method_decorator(permission_required('cash.Box_Cashier_Creation', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['cajero']

        if validar_roles(roles=roles):
            usuario = get_current_user()
            perfil = Profile.objects.get(user=usuario)
            personal = Personal.objects.filter(persona=perfil)
            personal_colegio = PersonalColegio.objects.get(personal=personal)

            cajas = Caja.objects.filter(colegio__id_colegio=get_current_colegio(), eliminado=True, activo=True)

            return render(request, template_name=self.template_name, context={
                'form': self.form_class,
                'cajas': cajas,
                'yolencios': personal_colegio.id_personal_colegio
            })

        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def form_valid(self, form):
        obj = form.save(commit=False)
        # =========
        caja = Caja.objects.get(pk=obj.caja_id)
        caja.activo = False
        caja.save()
        # =========
        obj.estado = True
        obj.save()
        return super(BoxCashierCreationView, self).form_valid(form)

class BoxCashierUpdateView(UpdateView):
    model = CajaCajero
    form_class = BoxCashierForm
    success_url = reverse_lazy('cash:boxcashier_list')
    template_name = 'boxcashier/boxcashier_formCierre.html'

    # fields = ['id_remesa', 'id_persona', 'id_movimiento', 'fechacreacion', 'monto', 'comentario']

    @method_decorator(permission_required('cash.Box_Cashier_Update', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['cajero']

        if validar_roles(roles=roles):
            return super(BoxCashierUpdateView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def form_valid(self, form):
        obj = form.save(commit=False)
        # =========

        caja = Caja.objects.get(pk=obj.caja_id)
        caja.activo = True
        caja.save()
        # =========
        apertura = obj.monto_apertura
        ventas = obj.ventas
        remesa = obj.total_remesa
        cierre = obj.monto_cierre
        saldo = (((apertura + ventas) - remesa) - cierre)
        obj.saldo = saldo
        obj.estado = False
        obj.save()
        return super(BoxCashierUpdateView, self).form_valid(form)

class BoxCashierDeleteView(DeleteView):
    model = CajaCajero
    success_url = reverse_lazy('cash:boxcashier_list')
    template_name = 'boxcashier/boxcashier_confirm_delete.html'

#################################################
#####          CRUD DE REMESAS              #####
#################################################

class ConsignmentListView(ListView):
    model = Remesa
    filterset_class = ConsignmentFilter
    template_name = 'consignment/consignment_list.html'

    @method_decorator(permission_required('cash.Consigment_List', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):
            Remesa.objects.filter(movimiento__caja__colegio_id=get_current_colegio())
            return super(ConsignmentListView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def get_context_data(self, **kwargs):
        context = super(CashierListView, self).get_context_data(**kwargs)
        roles = ['cajero']
        context['es_cajero'] = validar_roles(roles=roles)
        return context

class ConsignmentDetailView(DetailView):
    model = Remesa
    template_name = 'consignment/consignment_detail.html'

    @method_decorator(permission_required('cash.Consigment_Detail', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['promotor', 'director', 'administrativo', 'tesorero', 'cajero']

        if validar_roles(roles=roles):
            return super(ConsignmentDetailView, self).get(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

class ConsignmentCreationView(SuccessMessageMixin, CreateView):
    model = Remesa
    form_class = ConsignmentForm
    success_url = reverse_lazy('cash:consignment_list')
    template_name = 'consignment/consignment_form.html'
    success_message = "La remesa fue creada con exito"

    @method_decorator(permission_required('cash.Consigment_Creation', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['cajero']

        if validar_roles(roles=roles):
            try:
                usuario = get_current_user()
                # mov = CajaCajero.objects.get(estado=False, usuario_modificacion=str(usuario.id))
                alerta = False
            except:
                alerta = True
            personal = PersonalColegio.objects.filter(colegio=get_current_colegio(), activo=True)
            return render(request, template_name=self.template_name, context={
                'form': self.form_class,
                'personal': personal,
                'alerta': alerta,
            })
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)

    def form_valid(self, form):
        # print("** Empieza el form_valid ** ")
        # print("=======")
        obj = form.save(commit=False)
        # obj.estado = False
        get_personal_id = obj.personal_colegio.pk  # IdUsuario_Segun_Persona_Encargada
        # print("IdPersonal_Seleccionado: " + str(get_personal_id))
        # print("=======")
        personal_dentro_personal_colegio = PersonalColegio.objects.values('personal_id').filter(pk=get_personal_id)[0][
            'personal_id']
        # print("Personal dentro de PersonalColegio :  " + str(personal_dentro_personal_colegio))
        # print("=======")
        persona_dentro_personal = Personal.objects.values('persona_id').filter(pk=personal_dentro_personal_colegio)[0][
            'persona_id']
        # print("Persona(profile) dentro de personal :  " + str(persona_dentro_personal))
        # print("=======")
        id_usuario_dentro_profiles = Profile.objects.values('user_id').filter(pk=persona_dentro_personal)[0]['user_id']
        # print("Id_usuario dentro de Profiles_Profiles :  " + str(id_usuario_dentro_profiles))
        # print("=======")

        user_get_id = User.objects.values('id').filter(pk=id_usuario_dentro_profiles)[0]['id']

        password_get_id = obj.pusu
        # print("Contraseña OBTENIDA ")
        # print(password_get_id)
        # print("=======")
        user = User.objects.get(id=user_get_id)
        if user.check_password(password_get_id):
            # print("Contraseña Correcta ")
            # print("=======")
            cajacajero_id = obj.movimiento_id
            get_cajacajero = CajaCajero.objects.get(pk=cajacajero_id)
            get_cajacajero.total_remesa += obj.monto
            get_cajacajero.save()
            obj.pusu = str("  ")
            obj.save()
            return super(ConsignmentCreationView, self).form_valid(form)
        else:
            # print("Contraseña Incorrecta ")
            # print("=======")
            return HttpResponse("<script>alert('Contraseña Incorrecta !!');window.history.back();</script>")
            # return render_to_response('template_name', message='asdcxzasde')
            # return redirect(reverse("cash:consignment_create"), {"alert": 'Contraseña Incorrecta !! '})
            # return HttpResponse('Contraseña Incorrecta !!')

"""
    def post(self, request, *args, **kwargs):

        a = request.POST.get('personal_colegio')
        print(a)
        #print(Profile.objects.all())
        print(Profile.objects.get(pk=a))

        #print(User.objects.get(pk=a))
        #print(User.objects.select_related('profile').get(id=a))

        return render(request, template_name=self.template_name)
"""
"""
        profile = User.objects.filter(pk=a)
        for prof in profile:

            print(profile.email)
"""

class ConsignmentUpdateView(UpdateView):
    model = Remesa
    form_class = ConsignmentForm
    success_url = reverse_lazy('cash:consignment_list')
    template_name = 'consignment/consignment_form.html'
    # fields = ['id_remesa', 'id_persona', 'id_movimiento', 'fechacreacion', 'monto', 'comentario']

class ConsignmentDeleteView(DeleteView):
    model = Remesa
    success_url = reverse_lazy('cash:consignment_list')
    template_name = 'consignment/consignment_confirm_delete.html'

#################################################
#####          FILTRADO                     #####
#################################################

def search(request):
    comentario_list = Remesa.objects.all()
    comentario_filter = ConsignmentFilter(request.GET, queryset=comentario_list)
    return render(request, 'consignment/consignment_list.html', {'filter': comentario_filter})

class RecargarCajaChicaView(CreateView):
    model = Remesa
    form_class = CajaChicaConsignmentForm
    success_url = reverse_lazy('cash:consignment_list')
    template_name = 'consignment/consignment_form_cajachica.html'

    @method_decorator(permission_required('cash.Consigment_Creation', login_url=settings.REDIRECT_PERMISOS,
                                          raise_exception=False))
    def get(self, request, *args, **kwargs):
        roles = ['cajero']

        if validar_roles(roles=roles):
            persona = Profile.objects.get(user=get_current_user())
            personal = Personal.objects.get(persona=persona)
            personal = PersonalColegio.objects.filter(personal=personal, colegio=get_current_colegio(), activo=True)
            return render(request, template_name=self.template_name, context={
                'form': self.form_class,
                'personal': personal,
            })
        else:
            return HttpResponseRedirect(settings.REDIRECT_PERMISOS)


text:
namespace Reify {

inline std::ostream &operator<<(std::ostream &out, Potassco::StringSpan str) {
    out.write(str.first, str.size);
    return out;
}

template<typename Lambda>
class ScopeGuard {
public:
    ScopeGuard(Lambda &&f) : f_(std::forward<Lambda>(f)) { }
    ~ScopeGuard() { f_(); }
private:
    Lambda f_;
};

template<typename Lambda>
ScopeGuard<Lambda> makeScopeGuard(Lambda &&f) {
    return {std::forward<Lambda>(f)};
}

template<typename T, typename ...Args>
std::unique_ptr<T> gringo_make_unique(Args&& ...args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

template<typename T>
void printValue(std::ostream &out, T const &value) {
    out << value;
}

template<typename T, typename U>
void printValue(std::ostream &out, std::pair<T, U> const &value) {
    printValue(out, value.first);
    out << ",";
    printValue(out, value.second);
}

template<typename T>
void printComma(std::ostream &out, T const &t) {
    printValue(out, t);
}

template<typename T, typename U, typename... V>
void printComma(std::ostream &out, T const &t, U const &u, V const &...v) {
    printValue(out, t);
    out << ",";
    printComma(out, u, v...);
}

template<typename T>
struct Hash : std::hash<T> { };

template<typename T, typename U>
struct Hash<std::pair<T, U>> {
    size_t operator()(std::pair<T, U> const &p) const noexcept {
        size_t hash = std::hash<T>()(p.first);
        hash ^= Hash<U>()(p.second) + 0x9e3779b9 + (hash<<6) + (hash>>2);
        return hash;
    }
};

template<typename T>
struct Hash<std::vector<T>> {
    size_t operator()(std::vector<T> const &vec) const noexcept {
        size_t hash = vec.size();
        for (auto &x : vec) {
            hash ^= Hash<typename std::vector<T>::value_type>()(x) + 0x9e3779b9 + (hash<<6) + (hash>>2);
        }
        return hash;
    }
};

template <class T>
std::vector<T> toVec(Potassco::Span<T> span) {
    return {span.first, span.first + span.size};
}

} // namespace Reify

#endif // UTIL_PROGRAM_HH


text:
var passport = require('passport');
var express = require('express');
var clone = require('clone');
var IdmCore = require('agile-idm-core');
var bodyParser = require('body-parser');
var ids = require('../../lib/util/id');
var idmcore;

function RouterApi(tokenConf, idmcore, router) {

  //enable cors
  var cors_wrapper = require('../cors_wrapper')(tokenConf);
  router.route('*').options(cors_wrapper);
  router.use("*", cors_wrapper);

  //example to call tthis one
  //  returns 200 and the list of groups group, or 403, in case of security issues. 500 in case of unexpected situations
  // curl -H "Authorization: bearer $TOKEN" 'http://localhost:3000/api/v1/group/'
  //returns entity with 200 if OK, else, it can return an empty array if the entity is not found, 401 or 403 in case of security errors or 500 in case of unexpected situations
  router.route('/group/').get(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    function (req, res) {

      idmcore.readGroups(req.user)
        .then(function (read) {
          res.json(read);
        }).catch(function (error) {
          res.statusCode = error.statusCode || 500;
          res.json({
            "error": error.message
          });
        });

    });

  //example to call tthis one
  //  returns 200 and the group, or 401 or 403, in case of security issues. 500 in case of unexpected situations
  //this line returns the group with name me, owned by bob who is authenticated with agile-local authentication type
  // curl -H "Content-type: application/json" -H "Authorization: bearer ypr24DKllIbKlV3Ph8oWmZ7Pml3Wku" 'http://localhost:3000/api/v1/user/bob!@!agile-local/group/me/'
  //returns entity with 200 if OK, else, it can return 404 if the entity is not found, 401 or 403 in case of security errors or 500 in case of unexpected situations
  router.route('/user/:owner/group/:name').get(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    function (req, res) {

      idmcore.readGroup(req.user, req.params.name, req.params.owner)
        .then(function (read) {
          res.json(read);
        }).catch(function (error) {
          res.statusCode = error.statusCode || 500;
          res.json({
            "error": error.message
          });
        });

    });

  //returns 200 and the group, or 401 or 403, in case of security issues, or 409 if the group already exists, 400 if parameters are missing. 500 in case of unexpected situations
  //curl -H "Content-type: application/json" -H "Authorization: bearer ypr24DKllIbKlV3Ph8oWmZ7Pml3Wku" -d '{"group_name":"me", "owner":"nopbyte@github"}' 'http://localhost:3000/api/v1/group/'
  router.route('/group/').post(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    bodyParser.json(),
    function (req, res) {
      var group = req.body;
      if (!req.body.group_name) {
        res.statusCode = 400;
        return res.json({
          "error": "provide group_name in the body"
        });
      } else {
        idmcore.createGroup(req.user, req.body.group_name)
          .then(function (read) {
            res.json(read);
          }).catch(function (error) {
            console.log("error when posting group " + error);
            res.statusCode = error.statusCode || 500;
            res.json({
              "error": error.message
            });
          });
      }
    });

  //example to call tthis one
  //  returns 200 if the group os deleted, or 401 or 403, in case of security issues. 500 in case of unexpected situations
  //this line returns the group with name me, owned by bob who is authenticated with agile-local authentication type
  // curl -H "Content-type: application/json" -H "Authorization: bearer FWrt4MRCEoravyzF1LkPoWzWvKfVBc" '-X DELETE http://localhost:3000/api/v1/user/bob!@!agile-local/group/me/'
  //returns entity with 200 if OK, else, it can return 404 if the entity is not found, 401 or 403 in case of security errors or 500 in case of unexpected situations
  router.route('/user/:owner/group/:name').delete(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    function (req, res) {

      idmcore.deleteGroup(req.user, req.params.name, req.params.owner)
        .then(function (read) {
          res.json(read);
        }).catch(function (error) {
          res.statusCode = error.statusCode || 500;
          res.json({
            "error": error.message
          });
        });

    });

  //returns 200 and the group, or 401 or 403, in case of security issues, or 409 if the entity is  already in the group. or 404 in case the entity or the group are not found. 400 if parameters are missing. 500 in case of unexpected situations
  //this line adds the entity of type sensor and id 1, to the group called me and owned by bob who is authenticated with agile-local
  //curl -H "Content-type: application/json" -H "Authorization: bearer ypr24DKllIbKlV3Ph8oWmZ7Pml3Wku" -X POST 'http://localhost:3000/api/v1/user/bob!@!agile-local/group/me/entities/sensor/1'
  router.route('/user/:owner/group/:name/entities/:entity_type/:id').post(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    bodyParser.json(),
    function (req, res) {

      idmcore.addEntityToGroup(req.user, req.params.name, req.params.owner, req.params.id, "/" + req.params.entity_type)
        .then(function (read) {
          res.json(read);
        }).catch(function (error) {
          console.log("error when adding membership to a  group " + error);
          res.statusCode = error.statusCode || 500;
          res.json({
            "error": error.message
          });
        });
    });

  //returns 200 and the group, or 401 or 403, in case of security issues, or 409 if the entity is not  in the group. or 404 in case the entity or the group are not found. 400 if parameters are missing. 500 in case of unexpected situations
  //this line adds the entity of type sensor and id 1, to the group called me and owned by bob who is authenticated with agile-local
  //curl -H "Content-type: application/json" -H "Authorization: bearer ypr24DKllIbKlV3Ph8oWmZ7Pml3Wku" -X DELETE 'http://localhost:3000/api/v1/user/bob!@!agile-local/group/me/entities/sensor/1'
  router.route('/user/:owner/group/:name/entities/:entity_type/:id').delete(
    passport.authenticate('agile-bearer', {
      session: false
    }),
    bodyParser.json(),
    function (req, res) {

      idmcore.removeEntityFromGroup(req.user, req.params.name, req.params.owner, req.params.id, "/" + req.params.entity_type)
        .then(function (read) {
          res.json(read);
        }).catch(function (error) {
          console.log("error when deleting membership from group " + error);
          res.statusCode = error.statusCode || 500;
          res.json({
            "error": error.message
          });
        });
    });

}
module.exports = RouterApi;


text:
function WalkontableHorizontalScrollbarNative(instance) {
  this.instance = instance;
  this.type = 'horizontal';
  this.offset = 0;
  this.init();
  this.clone = this.makeClone('left');
}

WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay();

//resetFixedPosition (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () {
  var finalLeft, finalTop;

  if (!this.instance.wtTable.holder.parentNode) {
    return; //removed from DOM
  }
  var elem = this.clone.wtTable.holder.parentNode;

  if (this.scrollHandler === window) {

    var box = this.instance.wtTable.holder.getBoundingClientRect();
    var left = Math.ceil(box.left);
    var right = Math.ceil(box.right);

    if (left < 0 && (right - elem.offsetWidth) > 0) {
      finalLeft = -left + 'px';
    } else {
      finalLeft = '0';
    }

    finalTop = this.instance.wtTable.hider.style.top;
  }
  else if(!Handsontable.freezeOverlays) {
    finalLeft = this.getScrollPosition() + "px";
    finalTop = this.instance.wtTable.hider.style.top;
  }

  Handsontable.Dom.setOverlayPosition(elem, finalLeft, finalTop);

  elem.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 'px';
  elem.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px';// + 4 + 'px';
};

WalkontableHorizontalScrollbarNative.prototype.refresh = function (fastDraw) {
  this.applyToDOM();
  WalkontableOverlay.prototype.refresh.call(this, fastDraw);
};

WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () {
  return Handsontable.Dom.getScrollLeft(this.scrollHandler);
};

WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) {
  if (this.scrollHandler === window) {
    window.scrollTo(pos, Handsontable.Dom.getWindowScrollTop());
  } else {
    this.scrollHandler.scrollLeft = pos;
  }
};

WalkontableHorizontalScrollbarNative.prototype.onScroll = function () {
  this.instance.getSetting('onScrollHorizontally');
};

WalkontableHorizontalScrollbarNative.prototype.sumCellSizes = function (from, length) {
  var sum = 0;
  while(from < length) {
    sum += this.instance.wtTable.getStretchedColumnWidth(from) || this.instance.wtSettings.defaultColumnWidth;
    from++;
  }
  return sum;
};

//applyToDOM (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
  var total = this.instance.getSetting('totalColumns');
  var headerSize = this.instance.wtViewport.getRowHeaderWidth();

  this.fixedContainer.style.width = headerSize + this.sumCellSizes(0, total) + 'px';// + 4 + 'px';

  if (typeof this.instance.wtViewport.columnsRenderCalculator.startPosition === 'number'){
    this.fixed.style.left = this.instance.wtViewport.columnsRenderCalculator.startPosition + 'px';
  }
  else if (total === 0) {
    this.fixed.style.left = '0';
  } else {
    throw  new Error('Incorrect value of the columnsRenderCalculator');
  }
  this.fixed.style.right = '';
};

/**
 * Scrolls horizontally to a column at the left edge of the viewport
 * @param sourceCol {Number}
 * @param beyondRendered {Boolean} if TRUE, scrolls according to the bottom edge (top edge is by default)
 */
WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (sourceCol, beyondRendered) {
  var newX = this.getTableParentOffset();

  if (beyondRendered) {
    newX += this.sumCellSizes(0, sourceCol + 1);
    newX -= this.instance.wtViewport.getViewportWidth();
  }
  else {
    var fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
    newX += this.sumCellSizes(fixedColumnsLeft, sourceCol);
  }

  this.setScrollPosition(newX);
};

WalkontableHorizontalScrollbarNative.prototype.getTableParentOffset = function () {
  if (this.scrollHandler === window) {
    return this.instance.wtTable.holderOffset.left;
  }
  else {
    return 0;
  }
};


text:
// Copyright 2015 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.

/**
 * @fileoverview
 * `cr-checkbox` is a button that can be either checked or unchecked. User
 * can tap the checkbox to check or uncheck it. Usually you use checkboxes
 * to allow user to select multiple options from a set. If you have a single
 * ON/OFF option, avoid using a single checkbox and use `cr-toggle-button`
 * instead.
 *
 * Example:
 *     <cr-checkbox></cr-checkbox>
 *     <cr-checkbox checked></cr-checkbox>
 *
 * @element cr-checkbox
 */
Polymer({
  is: 'cr-checkbox',

  properties: {
    /**
     * Gets or sets the state. `true` is checked and `false` is unchecked.
     */
    checked: {
      type: Boolean,
      value: false,
      notify: true,
      reflectToAttribute: true
    },

    /**
     * If true, the user cannot interact with this element.
     */
    disabled: {
      type: Boolean,
      value: false,
      reflectToAttribute: true
    },
  },

  /** @override */
  attached: function() {
    // HACK(dschuyler): paper-checkbox 1.0.6 will hide the label
    // if the content is empty.
    // TODO(dschuyler): rework settings checkbox to use content
    // rather than spans.
    this.$.checkbox.$.checkboxLabel.hidden = false;
  },

  toggle: function() {
    this.checked = !this.checked;
  },

  /** @override */
  ready: function() {
    this.$.events.forward(this.$.checkbox, ['change']);
  },
});


text:
package java.lang;

public class Thread implements Runnable {

    Runnable target;

    public static interface UncaughtExceptionHandler {
    }

    public synchronized void start() {
        run();
    }

    public void run() {
        if (target != null) {
            target.run();
        }
    }

}


text:
<?php

namespace Intuxicated\PersianToolsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PersianToolsBundle extends Bundle {}


text:
package cmd

import (
	"bytes"
	"errors"
	"os"
	"path"
	"testing"
)

func Test_Parse(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	dir := path.Join(cwd, "test")
	in := "test/input/version_1"

	t.Run("Unexistable input directory", func(t *testing.T) {
		parser := NewParser()
		p := path.Join(dir, "unknown_folder")
		_, err := parser.Parse(p, nil)

		if err == nil {
			t.Error("Unknown directory should throw error")
		}
	})

	t.Run("Getwd() error bubbling", func(t *testing.T) {
		parser := &Parser{
			Wd: func() (string, error) {
				return "", errors.New("WD ERROR")
			},
		}
		_, err := parser.Parse("some/folder/", nil)

		if err == nil || err.Error() != "WD ERROR" {
			t.Error("Getwd() error should return error")
		}
	})

	t.Run("Unexistable output directory", func(t *testing.T) {
		parser := NewParser()
		unexisting := path.Join(dir, "input", "unexisting")
		_, err := parser.Parse(unexisting, nil)

		if err == nil {
			t.Error("Unknown directory should return error")
		}
	})

	t.Run("Empty input directory", func(t *testing.T) {
		parser := NewParser()
		p := path.Join(dir, "input", "version_2")
		_, err := parser.Parse(p, nil)

		if err == nil || err.Error() != errEmptyDirectory {
			t.Error("Empty directory should return error")
		}
	})

	t.Run("Empty result from parsing", func(t *testing.T) {
		parser := NewParser()
		p := path.Join(dir, "input", "version_3")
		_, err := parser.Parse(p, nil)

		if err == nil || err.Error() != errEmptyResult {
			t.Error("Empty result from parsing should return error")
		}
	})

	t.Run("Error on wrong template", func(t *testing.T) {
		parser := NewParser()
		p := path.Join(dir, "input", "version_4")
		_, err := parser.Parse(p, nil)

		if err == nil {
			t.Error("Wrong template should return error")
		}
	})

	t.Run("Parse template successfully", func(t *testing.T) {
		parser := NewParser()
		buf, err := parser.Parse(in, map[string]string{
			"Title": "Testing",
		})

		if err != nil {
			t.Error(err)
		}

		if !bytes.Contains(buf, []byte("# Testing")) {
			t.Error("Template don't contain env variables")
		}
	})
}


text:
package ot.internal;

/**
 * Created by Stas on 3/12/16.
 */
public class InsertElementStart extends Change {
    @Override
    Text apply(int pos, Text text) throws ValidationException {
        return null;
    }

    @Override
    int offset() {
        return 0;
    }
}


text:
class CreateStats < ActiveRecord::Migration
  def change
    create_view :stats
  end
end


text:
import random
from queue_ import Queue
from stack import Stack

class Node(object):
    """Implement a Node class with value, left and right."""

    def __init__(self, data=None, value=None, left=None, right=None):
        """The Node initializer with a data, value, left and right child."""
        self.data = data
        self.value = value
        self.left = left
        self.right = right
        self.depth = 1  # i added this during lecture

    def insert(self, nn):   # nn =  new_node
        """Insert a node in the correct place."""
        if nn.value > self.value:
            if self.right:
                self.right.insert(nn)
            else:
                self.right = nn
            self.depth = max(self.depth, self.right.depth + 1)
        elif nn.value < self.value:
            if self.left:
                self.left.insert(nn)
            else:
                self.left = nn
            self.depth = max(self.depth, self.left.depth + 1)

    def in_order(self):
        '''recursive in order traversal'''
        if self.left:
            for node in self.left.in_order():
                yield node
        yield self
        if self.right:
            for node in self.right.in_order():
                yield node

    def post_order(self):
        '''recursive post order traversal'''
        if self.left:
            for item in self.left.post_order():
                yield item
        if self.right:
            for item in self.right.post_order():
                yield item
        yield self.value

    def get_dot(self):          # pragma: no cover
        """
            Return the tree with root "self" as a dot graph for
            visualization.
        """
        return "digraph G{\n%s}" % ("" if self.value is None else (
            "\t%s;\n%s\n" % (
                self.value,
                "\n".join(self._get_dot())
            )
        ))

    def _get_dot(self):         # pragma: no cover
        """Recursively prepare a dot graph entry for this node."""
        if self.left is not None:
            yield "\t%s -> %s;" % (self.value, self.left.value)
            for i in self.left._get_dot():
                yield i
        elif self.right is not None:
            r = random.randint(0, 1e9)
            yield "\tnull%s [shape=point];" % r
            yield "\t%s -> null%s;" % (self.value, r)
        if self.right is not None:
            yield "\t%s -> %s;" % (self.value, self.right.value)
            for i in self.right._get_dot():
                yield i
        elif self.left is not None:
            r = random.randint(0, 1e9)
            yield "\tnull%s [shape=point];" % r
            yield "\t%s -> null%s;" % (self.value, r)

class BST(object):
    """Binary Search Tree class."""

    def __init__(self, root=None):
        """Initialize the Tree."""
        # TODO: what happens when bst = BST(7) is called
        # self.root = Node(value=root)
        self._size = 0
        self.root = root

    def insert(self, val, data):
        """Insert a node with with value=val."""
        new_node = Node(value=val, data=data)

        if self.root is None:
            self.root = new_node
        else:
            self.root.insert(new_node)

        self._size += 1

    def contains(self, val):
        """Return True if val is in the Tree."""
        current = self.root
        while True:
            if val == current.value:
                return True
            elif val > current.value:
                if current.right is None:
                    return False
                else:
                    current = current.right
            else:
                if current.left is None:
                    return False
                else:
                    current = current.left

    def size(self):
        '''reurns the _size'''
        return self._size

    def depth(self):
        """Return the total number of levels."""
        if self.root:
            return self.root.depth
        else:
            return 0

    def balance(self):
        """
            Return the difference in _size in depth of the left and right
            half of the Tree. greater depth on the left returns a positive
            value.
        """
        try:
            depth_left = self.root.left.depth
        except AttributeError:
            depth_left = 0

        try:
            depth_right = self.root.right.depth
        except AttributeError:
            depth_right = 0

        return depth_left - depth_right

    def _traverse(self, add, remove, size):
        '''Traverse function
            takes in other functions and a start_node'''
        while size():
            x = remove()
            if x:
                add(x.left, x.right)
                yield x.value

    def breadth_first_traversal(self):
        '''perform a breadth first traversal, returns a list of
           nodes in the graph
        '''
        q = Queue()
        q.enqueue(self.root)

        def add(a, b):
            q.enqueue(a)
            q.enqueue(b)

        return self._traverse(add, q.dequeue, q.size)

    def pre_order(self):
        '''perform a breadth first traversal, returns a list of
           nodes in the graph
        '''
        s = Stack()
        s.push(self.root)

        def add(a, b):
            s.push(b)
            s.push(a)
        return self._traverse(add, s.pop, s.size)

    def in_order(self):
        '''in_order travers function'''
        if self.root:
            return self.root.in_order()
        else:
            return []

    def post_order(self):
        '''Traverse function
            takes in other functions and a start_node'''
        if self.root:
            return self.root.post_order()
        else:
            return []

    def delete(self, target):
        """a function that removes a child node"""
        # initialization
        current = self.root
        pointer = None

        # search
        while current:
            if target == current.value:
                break
            pointer = current
            if current.value < target:
                current = current.right
            else:
                current = current.left
        if current is None:
            return

        # target has 2 children
        if current.left is not None and current.right is not None:
            y = current.left
            pointer = current
            while y.right:
                pointer = y
                y = y.right
            current.value = y.value
            current = y

        # leaf and 1 child cases
        if pointer is None:  # case where there is only one node
            if current.left:
                self.root = current.left
            else:
                self.root = current.right
        if current.left:
            tmp = current.left
        else:
            tmp = current.right
        if current == pointer.right:
            pointer.right = tmp
        else:
            pointer.left = tmp

if __name__ == "__main__":          # pragma: no cover
    # Best Case Senario
    # Binary Tree built in a way that every node is balanced.
    # With this tree every iteration you can eliminate half of the
    # reamianing possiblities, until you find the value.  In the below example
    # the most values you would have to check would be 4. If you had 65,535
    # values the most you would have to check would be 16 until you found
    # the correct value. The time complexity for this senario is O(log(n))

    best_case = BST()
    best_list = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
    for item in best_list:
        best_case.insert(item)

    # Worst Case Senario
    # Binary Tree built in a way that only has one branch. Each node has
    # only a single left or right child. In this senario you could have to
    # traverse through the whole tree to see if your value is there or not.
    # In the tree below one woulf have to check 7 nodes before finding the
    # value 11.  The time complexity for this senario is O(n)

    worst_case = BST()
    worst_list = [2, 5, 8, 14, 12, 10, 11]
    for item in worst_list:
        worst_case.insert(item)

    # print(bst.root.get_dot())