text:
namespace ceres {
namespace internal {

class ProblemImpl;
class ResidualBlock;

// The parameter block encodes the location of the user's original value, and
// also the "current state" of the parameter. The evaluator uses whatever is in
// the current state of the parameter when evaluating. This is inlined since the
// methods are performance sensitive.
//
// The class is not thread-safe, unless only const methods are called. The
// parameter block may also hold a pointer to a local parameterization; the
// parameter block does not take ownership of this pointer, so the user is
// responsible for the proper disposal of the local parameterization.
class ParameterBlock {
 public:
  // TODO(keir): Decide what data structure is best here. Should this be a set?
  // Probably not, because sets are memory inefficient. However, if it's a
  // vector, you can get into pathological linear performance when removing a
  // residual block from a problem where all the residual blocks depend on one
  // parameter; for example, shared focal length in a bundle adjustment
  // problem. It might be worth making a custom structure that is just an array
  // when it is small, but transitions to a hash set when it has more elements.
  //
  // For now, use a hash set.
  typedef HashSet<ResidualBlock*> ResidualBlockSet;

  // Create a parameter block with the user state, size, and index specified.
  // The size is the size of the parameter block and the index is the position
  // of the parameter block inside a Program (if any).
  ParameterBlock(double* user_state, int size, int index) {
    Init(user_state, size, index, NULL);
  }

  ParameterBlock(double* user_state,
                 int size,
                 int index,
                 LocalParameterization* local_parameterization) {
    Init(user_state, size, index, local_parameterization);
  }

  // The size of the parameter block.
  int Size() const { return size_; }

  // Manipulate the parameter state.
  bool SetState(const double* x) {
    CHECK(x != NULL)
        << "Tried to set the state of constant parameter "
        << "with user location " << user_state_;
    CHECK(!is_constant_)
        << "Tried to set the state of constant parameter "
        << "with user location " << user_state_;

    state_ = x;
    return UpdateLocalParameterizationJacobian();
  }

  // Copy the current parameter state out to x. This is "GetState()" rather than
  // simply "state()" since it is actively copying the data into the passed
  // pointer.
  void GetState(double *x) const {
    if (x != state_) {
      memcpy(x, state_, sizeof(*state_) * size_);
    }
  }

  // Direct pointers to the current state.
  const double* state() const { return state_; }
  const double* user_state() const { return user_state_; }
  double* mutable_user_state() { return user_state_; }
  LocalParameterization* local_parameterization() const {
    return local_parameterization_;
  }
  LocalParameterization* mutable_local_parameterization() {
    return local_parameterization_;
  }

  // Set this parameter block to vary or not.
  void SetConstant() { is_constant_ = true; }
  void SetVarying() { is_constant_ = false; }
  bool IsConstant() const { return is_constant_; }

  // This parameter block's index in an array.
  int index() const { return index_; }
  void set_index(int index) { index_ = index; }

  // This parameter offset inside a larger state vector.
  int state_offset() const { return state_offset_; }
  void set_state_offset(int state_offset) { state_offset_ = state_offset; }

  // This parameter offset inside a larger delta vector.
  int delta_offset() const { return delta_offset_; }
  void set_delta_offset(int delta_offset) { delta_offset_ = delta_offset; }

  // Methods relating to the parameter block's parameterization.

  // The local to global jacobian. Returns NULL if there is no local
  // parameterization for this parameter block. The returned matrix is row-major
  // and has Size() rows and  LocalSize() columns.
  const double* LocalParameterizationJacobian() const {
    return local_parameterization_jacobian_.get();
  }

  int LocalSize() const {
    return (local_parameterization_ == NULL)
        ? size_
        : local_parameterization_->LocalSize();
  }

  // Set the parameterization. The parameterization can be set exactly once;
  // multiple calls to set the parameterization to different values will crash.
  // It is an error to pass NULL for the parameterization. The parameter block
  // does not take ownership of the parameterization.
  void SetParameterization(LocalParameterization* new_parameterization) {
    CHECK(new_parameterization != NULL) << "NULL parameterization invalid.";
    CHECK(new_parameterization->GlobalSize() == size_)
        << "Invalid parameterization for parameter block. The parameter block "
        << "has size " << size_ << " while the parameterization has a global "
        << "size of " << new_parameterization->GlobalSize() << ". Did you "
        << "accidentally use the wrong parameter block or parameterization?";
    if (new_parameterization != local_parameterization_) {
      CHECK(local_parameterization_ == NULL)
          << "Can't re-set the local parameterization; it leads to "
          << "ambiguous ownership.";
      local_parameterization_ = new_parameterization;
      local_parameterization_jacobian_.reset(
          new double[local_parameterization_->GlobalSize() *
                     local_parameterization_->LocalSize()]);
      CHECK(UpdateLocalParameterizationJacobian())
          << "Local parameterization Jacobian computation failed for x: "
          << ConstVectorRef(state_, Size()).transpose();
    } else {
      // Ignore the case that the parameterizations match.
    }
  }

  void SetUpperBound(int index, double upper_bound) {
    CHECK_LT(index, size_);

    if (upper_bounds_.get() == NULL) {
      upper_bounds_.reset(new double[size_]);
      std::fill(upper_bounds_.get(),
                upper_bounds_.get() + size_,
                std::numeric_limits<double>::max());
    }

    upper_bounds_[index] = upper_bound;
  }

  void SetLowerBound(int index, double lower_bound) {
    CHECK_LT(index, size_);

    if (lower_bounds_.get() == NULL) {
      lower_bounds_.reset(new double[size_]);
      std::fill(lower_bounds_.get(),
                lower_bounds_.get() + size_,
                -std::numeric_limits<double>::max());
    }

    lower_bounds_[index] = lower_bound;
  }

  // Generalization of the addition operation. This is the same as
  // LocalParameterization::Plus() followed by projection onto the
  // hyper cube implied by the bounds constraints.
  bool Plus(const double *x, const double* delta, double* x_plus_delta) {
    if (local_parameterization_ != NULL) {
      if (!local_parameterization_->Plus(x, delta, x_plus_delta)) {
        return false;
      }
    } else {
      VectorRef(x_plus_delta, size_) = ConstVectorRef(x, size_) +
                                       ConstVectorRef(delta,  size_);
    }

    // Project onto the box constraints.
    if (lower_bounds_.get() != NULL) {
      for (int i = 0; i < size_; ++i) {
        x_plus_delta[i] = std::max(x_plus_delta[i], lower_bounds_[i]);
      }
    }

    if (upper_bounds_.get() != NULL) {
      for (int i = 0; i < size_; ++i) {
        x_plus_delta[i] = std::min(x_plus_delta[i], upper_bounds_[i]);
      }
    }

    return true;
  }

  std::string ToString() const {
    return StringPrintf("{ this=%p, user_state=%p, state=%p, size=%d, "
                        "constant=%d, index=%d, state_offset=%d, "
                        "delta_offset=%d }",
                        this,
                        user_state_,
                        state_,
                        size_,
                        is_constant_,
                        index_,
                        state_offset_,
                        delta_offset_);
  }

  void EnableResidualBlockDependencies() {
    CHECK(residual_blocks_.get() == NULL)
        << "Ceres bug: There is already a residual block collection "
        << "for parameter block: " << ToString();
    residual_blocks_.reset(new ResidualBlockSet);
  }

  void AddResidualBlock(ResidualBlock* residual_block) {
    CHECK(residual_blocks_.get() != NULL)
        << "Ceres bug: The residual block collection is null for parameter "
        << "block: " << ToString();
    residual_blocks_->insert(residual_block);
  }

  void RemoveResidualBlock(ResidualBlock* residual_block) {
    CHECK(residual_blocks_.get() != NULL)
        << "Ceres bug: The residual block collection is null for parameter "
        << "block: " << ToString();
    CHECK(residual_blocks_->find(residual_block) != residual_blocks_->end())
        << "Ceres bug: Missing residual for parameter block: " << ToString();
    residual_blocks_->erase(residual_block);
  }

  // This is only intended for iterating; perhaps this should only expose
  // .begin() and .end().
  ResidualBlockSet* mutable_residual_blocks() {
    return residual_blocks_.get();
  }

  double LowerBoundForParameter(int index) const {
    if (lower_bounds_.get() == NULL) {
      return -std::numeric_limits<double>::max();
    } else {
      return lower_bounds_[index];
    }
  }

  double UpperBoundForParameter(int index) const {
    if (upper_bounds_.get() == NULL) {
      return std::numeric_limits<double>::max();
    } else {
      return upper_bounds_[index];
    }
  }

 private:
  void Init(double* user_state,
            int size,
            int index,
            LocalParameterization* local_parameterization) {
    user_state_ = user_state;
    size_ = size;
    index_ = index;
    is_constant_ = false;
    state_ = user_state_;

    local_parameterization_ = NULL;
    if (local_parameterization != NULL) {
      SetParameterization(local_parameterization);
    }

    state_offset_ = -1;
    delta_offset_ = -1;
  }

  bool UpdateLocalParameterizationJacobian() {
    if (local_parameterization_ == NULL) {
      return true;
    }

    // Update the local to global Jacobian. In some cases this is
    // wasted effort; if this is a bottleneck, we will find a solution
    // at that time.

    const int jacobian_size = Size() * LocalSize();
    InvalidateArray(jacobian_size,
                    local_parameterization_jacobian_.get());
    if (!local_parameterization_->ComputeJacobian(
            state_,
            local_parameterization_jacobian_.get())) {
      LOG(WARNING) << "Local parameterization Jacobian computation failed"
          "for x: " << ConstVectorRef(state_, Size()).transpose();
      return false;
    }

    if (!IsArrayValid(jacobian_size, local_parameterization_jacobian_.get())) {
      LOG(WARNING) << "Local parameterization Jacobian computation returned"
                   << "an invalid matrix for x: "
                   << ConstVectorRef(state_, Size()).transpose()
                   << "\n Jacobian matrix : "
                   << ConstMatrixRef(local_parameterization_jacobian_.get(),
                                     Size(),
                                     LocalSize());
      return false;
    }
    return true;
  }

  double* user_state_;
  int size_;
  bool is_constant_;
  LocalParameterization* local_parameterization_;

  // The "state" of the parameter. These fields are only needed while the
  // solver is running. While at first glance using mutable is a bad idea, this
  // ends up simplifying the internals of Ceres enough to justify the potential
  // pitfalls of using "mutable."
  mutable const double* state_;
  mutable scoped_array<double> local_parameterization_jacobian_;

  // The index of the parameter. This is used by various other parts of Ceres to
  // permit switching from a ParameterBlock* to an index in another array.
  int32 index_;

  // The offset of this parameter block inside a larger state vector.
  int32 state_offset_;

  // The offset of this parameter block inside a larger delta vector.
  int32 delta_offset_;

  // If non-null, contains the residual blocks this parameter block is in.
  scoped_ptr<ResidualBlockSet> residual_blocks_;

  // Upper and lower bounds for the parameter block.  SetUpperBound
  // and SetLowerBound lazily initialize the upper_bounds_ and
  // lower_bounds_ arrays. If they are never called, then memory for
  // these arrays is never allocated. Thus for problems where there
  // are no bounds, or only one sided bounds we do not pay the cost of
  // allocating memory for the inactive bounds constraints.
  //
  // Upon initialization these arrays are initialized to
  // std::numeric_limits<double>::max() and
  // -std::numeric_limits<double>::max() respectively which correspond
  // to the parameter block being unconstrained.
  scoped_array<double> upper_bounds_;
  scoped_array<double> lower_bounds_;

  // Necessary so ProblemImpl can clean up the parameterizations.
  friend class ProblemImpl;
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_PARAMETER_BLOCK_H_


text:
package onewayfx

import (
	fx "go.uber.org/fx"
	transport "go.uber.org/yarpc/api/transport"
	thrift "go.uber.org/yarpc/encoding/thrift"
	onewayserver "go.uber.org/yarpc/internal/crossdock/thrift/oneway/onewayserver"
)

// ServerParams defines the dependencies for the Oneway server.
type ServerParams struct {
	fx.In

	Handler onewayserver.Interface
}

// ServerResult defines the output of Oneway server module. It provides the
// procedures of a Oneway handler to an Fx application.
//
// The procedures are provided to the "yarpcfx" value group. Dig 1.2 or newer
// must be used for this feature to work.
type ServerResult struct {
	fx.Out

	Procedures []transport.Procedure `group:"yarpcfx"`
}

// Server provides procedures for Oneway to an Fx application. It expects a
// onewayfx.Interface to be present in the container.
//
// 	fx.Provide(
// 		func(h *MyOnewayHandler) onewayserver.Interface {
// 			return h
// 		},
// 		onewayfx.Server(),
// 	)
func Server(opts ...thrift.RegisterOption) interface{} {
	return func(p ServerParams) ServerResult {
		procedures := onewayserver.New(p.Handler, opts...)
		return ServerResult{Procedures: procedures}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.vizzini.ai.geneticalgorithm.geneticprogramming.problem.cartcentering;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.vizzini.ai.geneticalgorithm.CopyOperator;
import org.vizzini.ai.geneticalgorithm.CrossoverOperator;
import org.vizzini.ai.geneticalgorithm.DefaultCopyOperator;
import org.vizzini.ai.geneticalgorithm.DefaultGeneticAlgorithm;
import org.vizzini.ai.geneticalgorithm.DefaultPopulation;
import org.vizzini.ai.geneticalgorithm.DefaultSelectionOperator;
import org.vizzini.ai.geneticalgorithm.Evaluator;
import org.vizzini.ai.geneticalgorithm.GenerationEvent;
import org.vizzini.ai.geneticalgorithm.GenerationListener;
import org.vizzini.ai.geneticalgorithm.GeneticAlgorithm;
import org.vizzini.ai.geneticalgorithm.Genome;
import org.vizzini.ai.geneticalgorithm.GenomeFactory;
import org.vizzini.ai.geneticalgorithm.ListGenome;
import org.vizzini.ai.geneticalgorithm.MutationOperator;
import org.vizzini.ai.geneticalgorithm.Population;
import org.vizzini.ai.geneticalgorithm.SelectionOperator;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.AbsoluteValueFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.AddFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.ConstantTerminal;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.ConstantTerminalFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.Converter;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.DefaultFunctionFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.DefaultSimplifier;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.DefaultTerminalFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.DivideFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.Function;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.FunctionFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.GPCrossoverOperator;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.GPMutationOperator;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.GreaterThanFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.InfixNotationVisitor;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.MultiplyFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.SubtractFunction;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.Terminal;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.TerminalFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.TreeNode;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.TreeNodeUtilities;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.VariableTerminal;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.VariableTerminalFactory;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.problem.Problem;
import org.vizzini.core.DefaultRandomGenerator;
import org.vizzini.core.Factory;
import org.vizzini.core.RandomGenerator;

/**
 * Provides a cart centering problem.
 */
public final class CartCenteringProblem implements GenerationListener, Problem<Double>
{
    /** X threshold. */
    private static final double DELTAX = 0.01;

    /** V threshold. */
    private static final double DELTAV = DELTAX;

    /**
     * Application method.
     *
     * @param args Application arguments.
     */
    public static final void main(final String[] args)
    {
        final CartCenteringProblem problem = new CartCenteringProblem();

        final Genome<TreeNode<Double>> result = problem.determineBest();
        final TreeNode<Double> treeNode = result.get(0);

        System.out.println("\nbest = " + InfixNotationVisitor.toEquation(treeNode) + " fitness = "
                + result.getFitness());
        final TreeNode<Double> simplerTreeNode = DefaultSimplifier.toSimplerTreeNode(treeNode);
        System.out.println("best = " + InfixNotationVisitor.toEquation(simplerTreeNode) + " fitness = "
                + result.getFitness());
    }

    /** Converter. */
    private final Converter<Double> converter = new Converter<Double>(Double.class);

    /** Function builder. */
    final FunctionFactory<Double> functionFactory;

    /** Random number generator. */
    private final RandomGenerator generator = new DefaultRandomGenerator();

    /**
     * Construct this object.
     */
    public CartCenteringProblem()
    {
        final TerminalFactory<Double> terminalFactory = new DefaultTerminalFactory<Double>(getTerminalFactories(),
                converter, generator);

        final int maxLevelCount = 4;
        functionFactory = new DefaultFunctionFactory<Double>(getFunctionExemplars(), maxLevelCount, terminalFactory,
                generator);
    }

    @Override
    public Genome<TreeNode<Double>> determineBest()
    {
        final int popSize = 500;
        final Population<TreeNode<Double>> population = createPopulation(popSize);
        final List<FitnessCase> fitnessCases = createFitnessCases(20, false);
        final Evaluator<TreeNode<Double>> evaluator = new CartCenteringEvaluator(fitnessCases, DELTAX, DELTAV);
        final int selectionCount = (int)Math.round(0.20 * popSize);
        final int copyCount = (int)Math.round(0.05 * popSize);
        final int crossoverCount = (int)Math.round(0.75 * popSize);
        final int generationCount = 50;
        final CopyOperator<TreeNode<Double>> copyOperator = new DefaultCopyOperator<TreeNode<Double>>();
        final SelectionOperator<TreeNode<Double>> selectionOperator = new DefaultSelectionOperator<TreeNode<Double>>(
                selectionCount);
        final GenomeFactory<TreeNode<Double>> genomeFactory = createGenomeFactory();
        final TreeNodeUtilities<Double> treeNodeUtils = new TreeNodeUtilities<Double>();
        final CrossoverOperator<TreeNode<Double>> crossoverOperator = new GPCrossoverOperator<Double>(treeNodeUtils,
                generator);
        final MutationOperator<TreeNode<Double>> mutationOperator = new GPMutationOperator<Double>(treeNodeUtils,
                functionFactory, generator);
        final int backCount = 10;

        final GeneticAlgorithm<TreeNode<Double>> ga = new DefaultGeneticAlgorithm<TreeNode<Double>>(population,
                evaluator, copyCount, crossoverCount, generationCount, copyOperator, selectionOperator, genomeFactory,
                crossoverOperator, mutationOperator, backCount);
        ga.addGenerationListener(this);

        return ga.determineBest();
    }

    @Override
    public void generationCompleted(final GenerationEvent event)
    {
        System.out.println(event);
    }

    @Override
    public Set<Function<Double>> getFunctionExemplars()
    {
        final TreeNode<Double> one = new ConstantTerminal<Double>(converter, 1.0);
        final TreeNode<Double> two = new ConstantTerminal<Double>(converter, 2.0);

        final Set<Function<Double>> exemplars = new HashSet<Function<Double>>();
        exemplars.add(new AddFunction<Double>(converter, one, two));
        exemplars.add(new SubtractFunction<Double>(converter, one, two));
        exemplars.add(new MultiplyFunction<Double>(converter, one, two));
        exemplars.add(new DivideFunction<Double>(converter, one, two));
        exemplars.add(new GreaterThanFunction<Double>(converter, one, two));
        exemplars.add(new AbsoluteValueFunction<Double>(converter, one));

        return exemplars;
    }

    @Override
    public TreeNode<Double> getSolution()
    {
        // -1 * x
        Function<Double> function0;
        {
            final TreeNode<Double> child0 = new ConstantTerminal<Double>(converter, -1.0);
            final TreeNode<Double> child1 = new VariableTerminal<Double>(converter, "x");
            function0 = new MultiplyFunction<Double>(converter, child0, child1);
        }

        // v * abs(v)
        final Function<Double> function1;
        {
            final TreeNode<Double> child0 = new VariableTerminal<Double>(converter, "v");
            final Function<Double> function2;
            {
                final TreeNode<Double> child1 = new VariableTerminal<Double>(converter, "v");
                function2 = new AbsoluteValueFunction<Double>(converter, child1);
            }
            function1 = new MultiplyFunction<Double>(converter, child0, function2);
        }

        // Greater than
        return new GreaterThanFunction<Double>(converter, function0, function1);
    }

    @Override
    public Set<Factory<Terminal<Double>>> getTerminalFactories()
    {
        final Set<String> variableNames = new TreeSet<String>(Arrays.asList(new String[] { "x", "v", }));

        final Set<Factory<Terminal<Double>>> factories = new HashSet<Factory<Terminal<Double>>>();
        factories.add(new ConstantTerminalFactory<Double>(converter, -1.0, generator));
        factories.add(new VariableTerminalFactory<Double>(converter, variableNames, generator));

        return factories;
    }

    /**
     * @param caseCount Fitness case count.
     * @param isVerbose Flag indicating whether to print output.
     *
     * @return a new list of random fitness cases.
     */
    private List<FitnessCase> createFitnessCases(final int caseCount, final boolean isVerbose)
    {
        final List<FitnessCase> answer = new ArrayList<FitnessCase>();

        final double minX = -0.75;
        final double maxX = 0.75;
        final double minV = -0.75;
        final double maxV = 0.75;

        answer.add(new FitnessCase(minX, minV));
        answer.add(new FitnessCase(maxX, minV));
        answer.add(new FitnessCase(minX, maxV));
        answer.add(new FitnessCase(maxX, maxV));

        while (answer.size() < caseCount)
        {
            final double x0 = generator.generateDouble(minX, maxX);
            final double v0 = generator.generateDouble(minV, maxV);
            answer.add(new FitnessCase(x0, v0));
        }

        if (isVerbose)
        {
            System.out.println("\nFitness Cases");
            for (int i = 0; i < answer.size(); i++)
            {
                final FitnessCase fitnessCase = answer.get(i);
                System.out.println(String.format("%2d %8.4f %8.4f", i, fitnessCase.getX0(), fitnessCase.getV0()));
            }
        }

        return answer;
    }

    /**
     * @return a new genome factory.
     */
    private GenomeFactory<TreeNode<Double>> createGenomeFactory()
    {
        return new GenomeFactory<TreeNode<Double>>()
        {
            @Override
            public Genome<TreeNode<Double>> create()
            {
                final TreeNode<Double> function = functionFactory.create();
                final Genome<TreeNode<Double>> answer = new ListGenome<TreeNode<Double>>(1);
                answer.add(function);

                return answer;
            }
        };
    }

    /**
     * @param popSize Population size.
     *
     * @return a new population.
     */
    private Population<TreeNode<Double>> createPopulation(final int popSize)
    {
        final GenomeFactory<TreeNode<Double>> genomeFactory = createGenomeFactory();
        final Population<TreeNode<Double>> answer = new DefaultPopulation<TreeNode<Double>>();

        while (answer.size() < popSize)
        {
            final Genome<TreeNode<Double>> genome = genomeFactory.create();

            if (!answer.contains(genome))
            {
                answer.add(genome);
            }
        }

        return answer;
    }
}


text:
/**
 * Created by bryangill on 2/14/16.
 */
var http;
var q;
var config;

class CommentService {

    constructor($http, $q, siwBlogConfig) {

        http = $http;
        q = $q;
        config = siwBlogConfig;

    }

    getComment(postid) {
        var request = {
            method: 'get',
            url: config.api_url + ':' + config.api_port + '/comment' + '?where={"post_id":' + postid + '}'
        };

        return http(request).then(function (response) {
            if (response) {
                return response;
            } else {
                return q.reject(response);
            }
        }, function (response) {
            return q.reject(response);
        });
    }

}

CommentService.$inject = ['$http', '$q', 'siwBlog.config'];

export default CommentService;


text:
package in.ravidsrk.sample;

import android.app.Activity;
import android.content.Intent;
import android.support.test.rule.ActivityTestRule;
import android.util.Log;

public class MainActivityTestRule<A extends Activity> extends ActivityTestRule<A> {

    public MainActivityTestRule(Class<A> activityClass) {
        super(activityClass);
    }

    @Override
    protected Intent getActivityIntent() {
        Log.e("MainActivityTestRule", "Prepare the activity's intent");
        return super.getActivityIntent();
    }

    @Override
    protected void beforeActivityLaunched() {
        Log.e("MainActivityTestRule", "Execute before the activity is launched");
        super.beforeActivityLaunched();
    }

    @Override
    protected void afterActivityLaunched() {
        Log.e("MainActivityTestRule", "Execute after the activity has been launched");
        super.afterActivityLaunched();
    }

    @Override
    protected void afterActivityFinished() {
        Log.e("MainActivityTestRule", "Cleanup after it has finished");
        super.afterActivityFinished();
    }

    @Override
    public A launchActivity(Intent startIntent) {
        Log.e("MainActivityTestRule", "Launching the activity");
        return super.launchActivity(startIntent);
    }
}


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

namespace CatboobGGStream
{
    public class AppItem
    {
        public String AppPath { get; set; }
        public String AppTitle { get; set; }
        public String AppArgs { get; set; }

        public AppItem()
        {
            this.AppArgs = "";
            this.AppTitle = "";
            this.AppArgs = "";
        }
    }
}


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

using Microsoft.MixedReality.Toolkit.Core.Services;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Core.Utilities
{
    /// <summary>
    /// Helper class for setting up canvases for use in the MRTK.
    /// </summary>
    [DisallowMultipleComponent]
    [RequireComponent(typeof(Canvas))]
    public class CanvasUtility : MonoBehaviour
    {
        [SerializeField]
        [HideInInspector]
        private Canvas canvas;

        /// <summary>
        /// The canvas this helper script is targeting.
        /// </summary>
        public Canvas Canvas
        {
            get => canvas;
            set => canvas = value;
        }

        private void Awake()
        {
            if (Canvas == null)
            {
                Canvas = GetComponent<Canvas>();
            }
        }

        private void Start()
        {
            Debug.Assert(Canvas != null);

            if (MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled &&
                Canvas.isRootCanvas && Canvas.renderMode == RenderMode.WorldSpace)
            {
                Canvas.worldCamera = MixedRealityToolkit.InputSystem?.FocusProvider?.UIRaycastCamera;
            }
        }
    }
}


text:
from .mlcontext import *
from .defmatrix import *
from .converters import *
from .classloader import *

__all__ = mlcontext.__all__
__all__ += defmatrix.__all__
__all__ += converters.__all__
__all__ += classloader.__all__


text:
public class Client extends Foo {
}


text:
""" use bag of words recipe representations to build a random forest classifier """
import time
from features_bow import *
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.cross_validation import cross_val_score

""" train random forest classifier with tf-idf recipe representations """
def train_wc(cv_n_fold=8, random_state=None, n_jobs=1, verbose=0):
    # use term frequencey inverse document frequencey feature representation
    wc_components = build_tfidf_wc(verbose=(verbose > 0))
    # prepare training set
    y_train = wc_components['train']['df']['cuisine_code'].as_matrix()
    X_train = wc_components['train']['features_matrix']
    # create random forest supervised classifier
    time_0 = time.time()
    clf = RandomForestClassifier(n_estimators=100, max_depth=None,
        n_jobs=n_jobs, random_state=random_state, verbose=verbose)
    if cv_n_fold > 0:
        # perform cross validation
        print 'cross validating %s ways...' % cv_n_fold
        scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=n_jobs)
        print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2)
    else:
        # fit random forest model
        print 'training random forest classifier...'
        clf.fit(X_train, y_train)
    time_1 = time.time()
    print 'process took %.3f seconds' % (time_1 - time_0)
    return wc_components, clf

""" apply transforms & classifier to what's cooking test set """
def test_wc(encoder, vectorizer, clf, verbose=False):
    wc_test_df = pd.read_json('data/test.json', orient='records')
    wc_test_recipe_ingrdnts = clean_recipes(wc_test_df['ingredients'].as_matrix(), verbose=verbose)
    wc_test_recipe_ingrdnts = build_recipe_docs(wc_test_recipe_ingrdnts)
    wc_test_features_bow = vectorizer.transform(wc_test_recipe_ingrdnts)
    wc_test_predict = clf.predict(wc_test_features_bow)
    wc_test_predict = encoder.inverse_transform(wc_test_predict)
    wc_test_predict_df = pd.DataFrame({'cuisine': wc_test_predict}, index=wc_test_df['id'])
    wc_test_predict_df.to_csv('data/submission_bow_rf.csv')

""" train & test bag of words random forest classifier """
def run(n_jobs=-1, verbose=1):
    components, clf = train_wc(cv_n_fold=0, n_jobs=n_jobs, verbose=verbose)
    test_wc(components['label_encoder'], components['model'], clf, verbose=(verbose > 0))

if __name__ == '__main__':
    run()


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import {NumbersService} from './numbers.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [NumbersService],
  bootstrap: [AppComponent]
})
export class AppModule { }


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

namespace HTLib2
{
    public static partial class HEnum
    {
        public static IEnumerable<T> HEnumNonNull<T>(this IEnumerable<T> list)
            where T : class
        {
            foreach(var item in list)
            {
                if(item == null)
                    continue;
                yield return item;
            }
        }
    }
}


text:
THRESHOLD_WARNING=50
THRESHOLD_CRITICAL=80

ERROR_MESSAGE="i3blocks default module missing"

# 1 to 3 for left/middle/right mouse button
case "${BLOCK_BUTTON}" in
1) notify-send "🖥CPU hogs" "$(ps axch -o cmd:15,%cpu --sort=-%cpu | head)\\n(100% per core)" ;;
2) setsid "$TERMINAL" -e htop & ;;
3) notify-send "CPU status" "Shows CPU details
- Left click to show intensive processes
- Middle click to open htop
- Right click none" ;;
esac

I3_BLOCKS_DEFAULT="/usr/share/i3blocks/cpu_usage"

if [[ ! -e "${I3_BLOCKS_DEFAULT}" ]]; then
	# i3blocks full_text
	echo "${ERROR_MESSAGE}"
	# i3blocks full_text
	echo "${ERROR_MESSAGE}"
	exit 33
fi

"${I3_BLOCKS_DEFAULT}" -w "${THRESHOLD_WARNING}" -c "${THRESHOLD_CRITICAL}"


text:
namespace ychat
{
	void db_proxy_monitor_t::pingpong_t::close_callback ()
	{
		delete this;
	}

	bool db_proxy_monitor_t::pingpong_t::timeout_callback ()
	{
		checker_->set_alive (false);
		return false;
	}

	bool db_proxy_monitor_t::pingpong_t::read_callback (char* data, int len)
	{
		checker_->set_alive (true);
		return false;
	}

	void db_proxy_monitor_t::pingpong_t::ping ()
	{

	}

	void db_proxy_monitor_t::nio_check (acl::check_client& checker,
										acl::aio_socket_stream& conn)
	{
		pingpong_t *pingpong = new pingpong_t;
		pingpong->checker_ = &checker;
		pingpong->conn_ = &conn;

		conn.add_close_callback (pingpong);
		conn.add_read_callback (pingpong);
		conn.add_timeout_callback (pingpong);
		pingpong->ping ();
	}
}


text:
(function() {

    angular.module('hcare')
        .controller('addCarrierModalController', addCarrierModalController);

    addCarrierModalController.$inject = ['$uibModalInstance', 'DataService', 'carrier', 'DateService'];
    function addCarrierModalController($uibModalInstance, DataService, carrier, DateService) {
        var ctrl = this;

        /**
         * Public API
         *
         */
        ctrl.editing = false;
        ctrl.carrier;
        if(carrier){
        	ctrl.carrier = carrier;
        }
        ctrl.activeStatuses = [0,1,2];

        ctrl.ok = ok;
        ctrl.cancel = cancel;

        /**
         * Get data for modal and set carrier if we are editing
         */
//        getInsuranceCarriers();
        if (carrier) { ctrl.editing = true }
        ctrl.carrier = carrier|| {};

        /**
         * Implementation
         */

        /**
         * Submit the information for adding a carrier. After closing, if it is successful, the
         * carrier object is returned to the calling component to display. We can either append it
         * directly to the carrier list or reload the updated list from the server.
         */
        function ok() {
            var carrierToAdd = angular.copy(ctrl.carrier);
            DataService.addCarrier(carrierToAdd, ctrl.editing)
                .then(function (response) {
                    'Back from adding a carrier';
                    console.log(response);

                })
                .catch(function (error) {
                    console.log('There was an error adding');
                    console.log(error);
                })
            //We want to communicate whether we edited a current carrier or added a new one so we can respond appropriately.
            if (ctrl.editing) {
                $uibModalInstance.close(ctrl.carrier, true);
            } else {
                $uibModalInstance.close(ctrl.carrier, false);
            }
        }

        function cancel() {
            console.log('cancel pressed');
            $uibModalInstance.dismiss('cancel');
        }
    }

})();


text:
arrive.js provides events to watch for DOM elements creation and removal. It makes use of [Mutation Observers](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) internally.

Download [arrive.min.js](https://raw.githubusercontent.com/uzairfarooq/arrive/master/minified/arrive.min.js) (latest)

or use [Bower](http://bower.io/) to install:

```bash
# install arrive.js and add it to bower.json dependencies
$ bower install arrive --save
```

## Usage
**The library does not depend on jQuery, you can replace jQuery elements in the examples below with pure javascript elements and it would work fine.**
###Watch for elements creation
Use `arrive` event to watch for elements creation:
```javascript
// watch for creation of an element which satisfies the selector ".test-elem"
$(document).arrive(".test-elem", function() {
    // 'this' refers to the newly created element
    var $newElem = $(this);
});

// the above event would watch for creation of element in whole document
// it's better to be more specific whenever possible, for example
$(".container-1").arrive(".test-elem", function() {
    var $newElem = $(this);
});
```

In pure javascript you can call the function on `document`, `window`, any `HTMLElement` or `NodeList`, like this:
```javascript
// watch for element creation in the whole HTML document
document.arrive(".test-elem", function() {
    // 'this' refers to the newly created element
});

// this will attach arrive event to all elements in the NodeList
document.getElementsByClass(".container-1").arrive(".test-elem", function() {
    // 'this' refers to the newly created element
});
```

Make sure to remove listeners when they are no longer needed, it's better for performance:
```javascript
// unbind all arrive events on document element
$(document).unbindArrive();

// unbind all arrive events on document element which are watching for ".test-elem" selector
$(document).unbindArrive(".test-elem");

// unbind only a specific callback
$(document).unbindArrive(callbackFunc);

// unbind only a specific callback on ".test-elem" selector
$(document).unbindArrive(".test-elem", callbackFunc);
```

####Options
As of v2.0 `arrive` event accepts an optional `options` object as 2nd argument. Options object consists of following:
```javascript
var options = {
    fireOnAttributesModification: boolean, // Defaults to false. Setting it to true would make arrive event fire on existing elements which start to satisfy selector after some modification in DOM attributes (an arrive event won't fire twice for a single element even if the option is true). If false, it'd only fire for newly created elements.
    onceOnly: boolean                      // Defaults to false. Setting it to true would ensure that registered callbacks fire only once.
};
```
Example:
```javascript
$(document).arrive(".test-elem", {fireOnAttributesModification: true}, function() {
    // 'this' refers to the newly created element
    var $newElem = $(this);
});
```

###Watch for elements removal
Use `leave` event to watch for elements removal.
The first arugument to leave must not be a [descendent](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors) or [child](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors) selector i.e. you cannot pass `.page .test-elem`, instead, pass `.test-elem`. It's because of a limitation in MutationObserver's api.

```javascript
// watch for removal of an element which satisfies the selector ".test-elem"
$(".container-1").leave(".test-elem", function() {
    var $removedElem = $(this);
});
```

You can unbind the `leave` event in the same way as `arrive` event, using `unbindLeave` function.

##Browser Support
arrive.js is built over [Mutation Observers](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) which is introduced in DOM4. It's supported in latest versions of all popular browsers.

| Browser           | Supported Versions
| ------------------|:-----------------:|
| Google Chrome     | 27.0+             |
| Firefox           | 14.0+             |
| Safari            | 6.1+              |
| Internet Explorer | 11.0+             |
| Opera             | 14.0+             |

##Contributing
####Report a bug / Request a feature
If you want to report a bug or request a feature, use the [Issues](https://github.com/uzairfarooq/arrive/issues) section. Before creating a new issue, search the existing ones to make sure that you're not creating a duplicate. When reporting a bug, be sure to include OS/browser version and steps/code to reproduce the bug, a [JSFiddle](http://jsfiddle.net/) would be great.

####Development
If you want ot contribute to arrive, here is the workflow you should use:

1. Fork the repository.
2. Clone the forked repository locally.
3. From the `dev` branch, create and checkout a new feature branch to work upon. (If you want to work on some minor bug fix, you can skip this step and continue to work in `dev` branch)
4. Make your changes in that branch (the actual source file is `/src/arrive.js`).
5. If sensible, add some jasmine tests in `/tests/spec/arriveSpec.js` file.
6. Make sure there are no regressions by executing the unit tests by opening the file `/tests/SpecRunner.html` in a browser. There is a button 'Run tests without jQuery' at the top left of th page, click that button to make sure that the tests passes without jQuery. Run the test cases in all major browsers.
7. Push the changes to your github repository.
8. Submit a pull request from your repo back to the original repository.
9. Once it is accepted, remember to pull those changes back into your develop branch!


text:
namespace ai
{
namespace nn
{
namespace rnn
{

NetworkGraph::NetworkGraph(const std::vector<unsigned>& topology, const std::shared_ptr<NeuralNetwork>& m_neural_network)
{
	for (size_t l_index = 0; l_index < topology.size(); ++l_index)
	{
		m_layers.emplace_back();
		size_t layer_outputs;

		if (l_index == topology.size() - 1)
		{
			layer_outputs = 0;
		}
		else
		{
			layer_outputs = topology[l_index + 1];
		}

		// for each neurons in the current layer of the loop,
		// tell that neuron how many outputs it needs to have and that neurons position in the current layer
		for (size_t n_index = 0; n_index <= topology[l_index]; ++n_index)
		{
			m_layers.back().emplace_back(RecurrentNeuron(layer_outputs, n_index, m_neural_network));
		}

		// force the bias neuron (last neuron created for each layer) to have an ouput initially set to 1.0
		m_layers.back().back().SetNeuronOutput(1.0);
	}
}

void NetworkGraph::ForwardPropogate(const std::deque<double>& inputs)
{
	// set output for each neuron in layer 1 to be a value from inputs
	for (size_t n_index = 0; n_index < inputs.size(); ++n_index)
	{
		m_layers.front()[n_index].SetNeuronOutput(inputs[n_index]);
	}

	for (size_t l_index = 1; l_index < m_layers.size(); ++l_index)
	{
		std::vector<RecurrentNeuron> &prev_layer = m_layers[l_index - 1];

		for (size_t current_neuron = 0; current_neuron < m_layers[l_index].size() - 1; ++current_neuron)
		{
			m_layers[l_index][current_neuron].FeedForward(prev_layer);
		}
	}
}

void NetworkGraph::BackPropogate(const std::deque<double>& targets)
{
	std::vector<RecurrentNeuron> &output_layer = m_layers.back();

	// Calculate gradients for each neuron in last layer excluding the bias neuron
	for (size_t n_index = 0; n_index < output_layer.size() - 1; ++n_index)	// n_index == neuron_index
	{
		output_layer[n_index].CalcOutputGradient(targets[n_index]);
	}

	// Starting with the last hidden layer working backwards toward the first hidden layer
	for (int hl_index = m_layers.size() - 2; hl_index > 0; --hl_index)	// hl_index == hidden_layer_index
	{
		std::vector<RecurrentNeuron> &hidden_layer = m_layers[hl_index];
		std::vector<RecurrentNeuron> &next_hidden_layer = m_layers[hl_index + 1];

		// Calculate gradients for each hidden neuron in the hiddenlayer
		for (size_t hn_index = 0; hn_index < hidden_layer.size(); ++hn_index)	// hn_index == hidden_neuron_index
		{
			hidden_layer[hn_index].CalcHiddenGradient(next_hidden_layer);
		}
	}

	// For all layers starting with the last layer and working backwards toward the second layer
    // (don't need first layer since it has inputs instead of incoming connection weights)
	for (int l_index = m_layers.size() - 1; l_index > 0; --l_index)
	{
		std::vector<RecurrentNeuron> &current_layer = m_layers[l_index];
		std::vector<RecurrentNeuron> &prev_layer = m_layers[l_index - 1];

		// Update connection weights for each neuron in current_layer
		for (size_t n_index = 0; n_index < current_layer.size() - 1; ++n_index)
		{
			current_layer[n_index].UpdateInputWeight(prev_layer);
		}
	}
}

double NetworkGraph::GetErrorRate(const std::deque<double>& targets)
{
	std::vector<RecurrentNeuron> &output_layer = m_layers.back();
	m_mean_square_error = 0.0;

	for (size_t n_index = 0; n_index < output_layer.size() - 1; ++n_index)	// n_index == neuron_index
	{
		double delta = targets[n_index] - output_layer[n_index].GetNeuronOutput();
		m_mean_square_error += (delta * delta);
	}

	m_mean_square_error /= output_layer.size() - 1;
	m_rms = sqrt(m_mean_square_error);

	if (m_average_error== 0)
	{
		m_average_error = (m_smoothing_factor + m_rms) / (m_smoothing_factor + 1.0);
	}
	else
	{
		m_average_error = (m_average_error * m_smoothing_factor + m_rms) / (m_smoothing_factor + 1.0);
	}
	//return _mean_square_error;
	//return _rms;
	return m_average_error;
}

void NetworkGraph::GetOutput(std::vector<double>& ann_output)
{
	for (size_t n_index = 0; n_index < m_layers.back().size() - 1; ++n_index)
	{
		ann_output.emplace_back(m_layers.back()[n_index].GetNeuronOutput());
	}
}

}   // namespace rnn
}  // namespace nn
} // namespace ai


text:
title: Presentations
subtitle:
---

[Olympics](https://rawgit.com/spitalnyd/spitalnyd-Olympics1-presentation/master/piracy.html)3-6-2017

[Piracy](https://rawgit.com/spitalnyd/spitalnyd-piracy101-presentation/master/Spitalnyd-Piracy.html)4-10-2017


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="40dp"
    android:height="40dp"
    android:viewportWidth="40"
    android:viewportHeight="40"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M5.583,10.583H18.542L20,12.042H34.417V31.125H5.583Z"/>
</vector>


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

namespace Codeplex.Reactive.Interactivity
{
    public abstract class TargetedTriggerAction<T> : TargetedTriggerAction
        where T : class
    {
        public TargetedTriggerAction() : base(typeof(T))
        {
        }

        protected new T Target
        {
            get { return (T)base.Target; }
        }
    }
}


text:
package com.thoughtworks.go.http.mocks;

import com.google.gson.Gson;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.mock.web.MockHttpServletRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.nio.charset.Charset;
import java.util.*;

import static java.nio.charset.StandardCharsets.UTF_8;

public class HttpRequestBuilder {

    private static final Gson GSON = new Gson();
    private static final String CONTEXT_PATH = "/go";

    private MockHttpServletRequest request;

    public HttpRequestBuilder() {
        this(new MockHttpServletRequest());
    }

    private HttpRequestBuilder(MockHttpServletRequest request) {
        this.request = request;
    }

    public HttpRequestBuilder withPath(String path) {
        try {
            URIBuilder uri = new URIBuilder(path);
            request.setServerName("test.host");
            request.setContextPath(CONTEXT_PATH);
            request.setParameters(splitQuery(uri));
            request.setRequestURI(CONTEXT_PATH + uri.getPath());
            request.setServletPath(uri.getPath());
            if (!uri.getQueryParams().isEmpty()) {
                request.setQueryString(URLEncodedUtils.format(uri.getQueryParams(), UTF_8));
            }
            return this;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public HttpRequestBuilder withPathSafe(String path) {
        return withPath(StringUtils.isBlank(path) ? "/" : path);
    }

    public MockHttpServletRequest build() {
        return request;
    }

    private static HttpRequestBuilder create() {
        return new HttpRequestBuilder();
    }

    private static HttpRequestBuilder createChunked() {
        MockHttpServletRequest request = new MockHttpServletRequest() {
            @Override
            public int getContentLength() {
                return 0;
            }
        };
        request.addHeader(HttpHeaders.TRANSFER_ENCODING, "chunked");
        return new HttpRequestBuilder(request);
    }

    public static HttpRequestBuilder GET(String path) {
        return create().withMethod("GET").withPathSafe(path);
    }

    public static HttpRequestBuilder HEAD(String path) {
        return create().withMethod("HEAD").withPathSafe(path);
    }

    public static HttpRequestBuilder DELETE(String path) {
        return create().withMethod("DELETE").withPathSafe(path);
    }

    public static HttpRequestBuilder PUT(String path) {
        return create().withMethod("PUT").withPathSafe(path);
    }

    public static HttpRequestBuilder PUTChunked(String path) {
        return createChunked().withMethod("PUT").withPathSafe(path);
    }

    public static HttpRequestBuilder POST(String path) {
        return create().withMethod("POST").withPathSafe(path);
    }

    public static HttpRequestBuilder POSTChunked(String path) {
        return createChunked().withMethod("POST").withPathSafe(path);
    }

    public static HttpRequestBuilder PATCH(String path) {
        return create().withMethod("PATCH").withPathSafe(path);
    }

    public static HttpRequestBuilder PATCHChunked(String path) {
        return createChunked().withMethod("PATCH").withPathSafe(path);
    }

    public HttpRequestBuilder withCookies(Cookie... cookies) {
        List<Cookie> existingCookies = new ArrayList<>();
        final Cookie[] requestCookies = request.getCookies();

        if (requestCookies != null) {
            existingCookies.addAll(Arrays.asList(requestCookies));
        }

        existingCookies.addAll(Arrays.asList(cookies));
        request.setCookies(existingCookies.toArray(new Cookie[0]));
        return this;
    }

    public HttpRequestBuilder withHeaders(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            withHeader(entry.getKey(), entry.getValue());
        }
        return this;
    }

    public HttpRequestBuilder withHeader(String name, Object value) {
        request.addHeader(name, value.toString());
        return this;
    }

    public HttpRequestBuilder withBody(String body, Charset charset) {
        request.setContent(body.getBytes(charset));
        return this;
    }

    public HttpRequestBuilder withBody(String body) {
        return withBody(body, UTF_8);
    }

    public HttpRequestBuilder withJsonBody(Object body) {
        return withBody(GSON.toJson(body));
    }

    private static Map<String, String[]> splitQuery(URIBuilder builder) {
        Map<String, String[]> params = new LinkedHashMap<>();

        for (NameValuePair nameValuePair : builder.getQueryParams()) {
            params.compute(nameValuePair.getName(),
                (key, oldValue) -> oldValue == null ? new String[] {nameValuePair.getValue()} : ArrayUtils.add(oldValue, nameValuePair.getValue()));
        }

        return params;
    }

    public HttpRequestBuilder withMethod(String method) {
        request.setMethod(method.toUpperCase());
        return this;
    }

    public HttpRequestBuilder withSessionAttr(String name, Object value) {
        request.getSession().setAttribute(name, value);
        return this;
    }

    public HttpRequestBuilder withBasicAuth(String username, String password) {
        return withHeader(HttpHeaders.AUTHORIZATION, "basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8)));
    }

    public HttpRequestBuilder withBearerAuth(String token) {
        return withHeader(HttpHeaders.AUTHORIZATION, "bearer " + token);
    }

    public HttpRequestBuilder withSession(HttpSession session) {
        request.setSession(session);
        return this;
    }

    public HttpRequestBuilder withRequestedSessionId(String requestedSessionId) {
        request.setRequestedSessionId(requestedSessionId);
        return this;
    }

    public HttpRequestBuilder withRequestedSessionIdFromSession() {
        return withRequestedSessionId(request.getSession(true).getId());
    }

    public HttpRequestBuilder usingAjax() {
        return withHeader("X-Requested-With", "XMLHttpRequest");
    }
}


text:
namespace vg {

// Represents a node traversed in a certain orientation. The default orientation
// is start to end, but if `backward` is set, represents the node being
// traversed end to start. A list of these can serve as an edit-free version of
// a path, especially if supplemented with a length and an initial node offset.
// A path node has a left and a right side, which are the start and end of the
// node if it is forward, or the end and start of the node if it is backward.
class NodeTraversal {
public:
    Node* node;
    bool backward;

    inline NodeTraversal(Node* node, bool backward = false): node(node), backward(backward) {
        // Nothing to do
    }

    inline NodeTraversal(): NodeTraversal(nullptr) {
        // Nothing to do
    }

    inline bool operator==(const NodeTraversal& other) const {
        return node == other.node && backward == other.backward;
    }

    inline bool operator<(const NodeTraversal& other) const {
        return node < other.node || (node == other.node && backward < other.backward);
    }
};

inline ostream& operator<<(ostream& out, const NodeTraversal& nodetraversal) {
    return out << nodetraversal.node->id() << " " << (nodetraversal.backward ? "rev" : "fwd");
}

// Represents one side of a Node, identified by ID, for the purposes of
// indexing edges.
class NodeSide {
public:
    int64_t node;
    bool is_end;

    // We need this to be a converting constructor so we can represent the empty and deleted item keys in a pair_hash_map.
    inline NodeSide(int64_t node, bool is_end = false): node(node), is_end(is_end) {
        // Nothing to do
    }

    inline NodeSide(): NodeSide(0, false) {
        // Nothing to do
    }

    inline bool operator==(const NodeSide& other) const {
        return node == other.node && is_end == other.is_end;
    }

    inline bool operator<(const NodeSide& other) const {
        return node < other.node || (node == other.node && is_end < other.is_end);
    }

    // Make an edge into a canonically ordered pair of NodeSides
    static inline pair<NodeSide, NodeSide> pair_from_edge(Edge* e) {
        return minmax(NodeSide(e->from(), !e->from_start()), NodeSide(e->to(), e->to_end()));
    }

    // Make an edge into a canonically ordered pair of NodeSides
    static inline pair<NodeSide, NodeSide> pair_from_edge(Edge& e) {
        return pair_from_edge(&e);
    }

    // Make a canonically ordered pair of NodeSides from an edge off of the
    // start of a node, to another node in the given relative orientation.
    static inline pair<NodeSide, NodeSide> pair_from_start_edge(int64_t start_id, const pair<int64_t, bool>& oriented_other) {
        // If it's in the same relative orientation, we go to its end.
        return minmax(NodeSide(start_id, false), NodeSide(oriented_other.first, !oriented_other.second));
    }

    // Make a canonically ordered pair of NodeSides from an edge off of the
    // end of a node, to another node in the given relative orientation.
    static inline pair<NodeSide, NodeSide> pair_from_end_edge(int64_t end_id, const pair<int64_t, bool>& oriented_other) {
        // If it's in the same relative orientation, we go to its start.
        return minmax(NodeSide(end_id, true), NodeSide(oriented_other.first, oriented_other.second));
    }
};

// We create a struct that represents each kmer record we want to send to gcsa2
struct KmerPosition {
    string kmer;
    string pos;
    set<char> prev_chars;
    set<char> next_chars;
    set<string> next_positions;
};

inline ostream& operator<<(ostream& out, const NodeSide& nodeside) {
    return out << nodeside.node << " " << (nodeside.is_end ? "end" : "start");
}

}

// Go up to std namespace for a moment
namespace std {
// We need to implement a hash function for these if we want to be able to use them in keys.
template <> struct hash<vg::NodeSide>
{
    // Produce a hash of a NodeSide
    size_t operator()(const vg::NodeSide& item) const
    {
        // Hash it just as we would a pair.
        return hash<pair<int64_t, bool>>()(make_pair(item.node, item.is_end));
    }
};
}

namespace vg {

// Represents a sequence graph. Graphs consist of nodes, connected by edges.
// Graphs are bidirected and may be cyclic. Nodes carry forward-oriented
// sequences. Edges are directed, with a "from" and to" node, and are generally
// used to connect the end of the "from" node to the start of the "to" node.
// However, edges can connect to either the start or end of either node, in
// general, as long as they do not allow the same node to be visited twice along
// a path. Graphs have "head" and "tail" nodes, which are overall at the
// left/right of the graph, with nothing before/after them. Because otherwise
// identifying these nodes (i.e. classifying a terminal node as a head or a
// tail) would require a topological sort, we require that all head and tail
// nodes be in the same relative orientation. Head nodes must have edges only to
// their right sides, and tail nodes must have edges only to their left sides.
// There must be no possible path in the graph containing two head nodes or two
// tail nodes.
class VG {

public:

    // protobuf-based representation
    // NB: we can't subclass this safely, so it's best as a member
    Graph graph;

    // manages paths of the graph
    // initialized by setting paths._paths = graph.paths
    Paths paths;

    // name
    string name;

    // current id
    int64_t current_id;
    // todo
    //int64_t min_id;
    //int64_t max_id;

    // nodes by id
    hash_map<int64_t, Node*> node_by_id;

    // edges by sides of nodes they connect
    // Since duplicate edges are not permitted, two edges cannot connect the same pair of node sides.
    // Each edge is indexed here with the smaller NodeSide first. The actual node order is recorded in the Edge object.
    pair_hash_map<pair<NodeSide, NodeSide>, Edge*> edge_by_sides;

    // nodes by position in nodes repeated field
    // this is critical to allow fast deletion of nodes
    hash_map<Node*, int> node_index;

    // edges by position in edges repeated field
    // same as for nodes, this allows fast deletion
    hash_map<Edge*, int> edge_index;

    // edges indexed by nodes they connect
    // Stores the destinations and backward flags for edges attached to the starts of nodes (whether that node is "from" or "to").
    hash_map<int64_t, vector<pair<int64_t, bool>>> edges_on_start;
    // Stores the destinations and backward flags for edges attached to the ends of nodes (whether that node is "from" or "to").
    hash_map<int64_t, vector<pair<int64_t, bool>>> edges_on_end;

    // Set the edge indexes through this function. Picks up the sides being
    // connected by the edge automatically, and silently drops the edge if they
    // are already connected.
    void set_edge(Edge*);
    void print_edges(void);

    // access the edge indexes through these functions
    // Get nodes and backward flags following edges that attach to this node's start
    vector<pair<int64_t, bool>>& edges_start(Node* node);
    vector<pair<int64_t, bool>>& edges_start(int64_t id);
    // Get nodes and backward flags following edges that attach to this node's end
    vector<pair<int64_t, bool>>& edges_end(Node* node);
    vector<pair<int64_t, bool>>& edges_end(int64_t id);

    // properties of the graph
    size_t size(void); // number of nodes
    size_t length(void);

    // clear everything
    //void clear(void);

    // constructors

    // default
    VG(void);

    // construct from protobufs
    VG(istream& in, bool showp = false);

    // construct from an arbitrary source of Graph protobuf messages (which
    // populates the given Graph and returns a flag for whether it's valid).
    VG(function<bool(Graph&)>& get_next_graph, bool showp = false);

    // construct from sets of nodes and edges (e.g. subgraph of another graph)
    VG(set<Node*>& nodes, set<Edge*>& edges);

    // construct from VCF
    VG(vcflib::VariantCallFile& variantCallFile,
       FastaReference& reference,
       string& target,
       bool target_is_chrom,
       int vars_per_region,
       int max_node_size = 0,
       bool showprog = false);
    void from_alleles(const map<long, set<vcflib::VariantAllele> >& altp,
                      string& seq,
                      string& chrom);
    void vcf_records_to_alleles(vector<vcflib::Variant>& records,
                                map<long, set<vcflib::VariantAllele> >& altp,
                                int start_pos,
                                int stop_pos,
                                int max_node_size = 0);
    void slice_alleles(map<long, set<vcflib::VariantAllele> >& altp,
                       int start_pos,
                       int stop_pos,
                       int max_node_size);
    void dice_nodes(int max_node_size);

    void from_gfa(istream& in, bool showp = false);

    // default constructor, destructor
    ~VG(void);

    // copy constructor
    VG(const VG& other) {
        init();
        if (this != &other) {
            // cleanup
            clear_indexes();
            // assign
            graph = other.graph;
            paths = other.paths;
            // re-index
            rebuild_indexes();
        }
    }

    // move constructor
    VG(VG&& other) noexcept {
        init();
        graph = other.graph;
        paths = other.paths;
        other.graph.Clear();
        rebuild_indexes();
        // should copy over indexes
    }

    // copy assignment operator
    VG& operator=(const VG& other) {
        VG tmp(other);
        *this = std::move(tmp);
        return *this;
    }

    // move assignment operator
    VG& operator=(VG&& other) noexcept {
        std::swap(graph, other.graph);
        rebuild_indexes();
        return *this;
    }

    // todo
    // set vg up to not build indexes
    // providing very light runtime
    // this would disable a ton of functions
    // and change the deserialization semantics
    //
    //void no_indexes(void);
    //void yes_indexes(void);

    void build_indexes(void);
    void index_paths(void);
    void clear_indexes(void);
    void clear_indexes_no_resize(void);
    void resize_indexes(void);
    void rebuild_indexes(void);

    // literally merge protobufs
    void merge(Graph& g);
    void merge(VG& g);

    // merge protobufs after removing overlaps
    // good when there aren't many overlaps
    void merge_union(VG& g);
    // helper to merge_union
    void remove_duplicated_in(VG& g);

    // limit the local complexity of the graph, connecting pruned components to a head and tail node
    // depending on the direction which we come into the node when the edge_max is passed
    void prune_complex_paths(int length, int edge_max, Node* head_node, Node* tail_node);
    void prune_short_subgraphs(size_t min_size);

    // write to a stream in chunked graphs
    void serialize_to_ostream(ostream& out, int64_t chunk_size = 1000);
    void serialize_to_file(const string& file_name, int64_t chunk_size = 1000);

    // can we handle this with merge?
    //void concatenate(VG& g);

    int64_t max_node_id(void);
    int64_t min_node_id(void);
    // Squish the node IDs down into as small a space as possible. Fixes up paths itself.
    void compact_ids(void);
    // Add the given value to all node IDs. Preserves the paths.
    void increment_node_ids(int64_t increment);
    // Subtract the given value from all the node IDs. Must not create a node with 0 or negative IDs. Invalidates the paths.
    void decrement_node_ids(int64_t decrement);
    // Change the ID of the node with the first id to the second, new ID not
    // used by any node. Invalidates any paths containing the node, since they
    // are not updated.
    void swap_node_id(int64_t node_id, int64_t new_id);
    // Change the ID of the given node to the second, new ID not used by any
    // node. Invalidates the paths. Invalidates any paths containing the node,
    // since they are not updated.
    void swap_node_id(Node* node, int64_t new_id);

    // Iteratively add when nodes and edges are novel. Good when there are very
    // many overlaps. TODO: If you are using this with warn on duplicates on,
    // and you know there shouldn't be any duplicates, maybe you should use
    // merge instead.
    void extend(VG& g, bool warn_on_duplicates = false);
    void extend(Graph& graph, bool warn_on_duplicates = false);

    // modify ids of the second graph to ensure we don't have conflicts
    // then attach tails of this graph to the heads of the other, and extend(g)
    void append(VG& g);

    // don't append or join the nodes in the graphs
    // just ensure that ids are unique, then apply extend
    void combine(VG& g);

    // edit the graph to include the path
    void include(const Path& path);
    // or a set of mappings against one node
    void edit_node(int64_t node_id,
                   const vector<tuple<Mapping, bool, bool> >& mappings,
                   map<pair<size_t, int64_t>, pair<set<Node*>, set<Node*>>>& cut_trans);
    // for each node, modify it with the associated mappings
    void edit(const map<int64_t, vector<tuple<Mapping, bool, bool> > >& mappings,
              map<pair<int64_t, size_t>, pair<int64_t, size_t> >& del_f,
              map<pair<int64_t, size_t>, pair<int64_t, size_t> >& del_t);
    void edit(const vector<Path>& paths);

    // Add in the given node, by value
    void add_node(Node& node);
    void add_nodes(vector<Node>& nodes);
    void add_edge(Edge& edge);
    void add_edges(vector<Edge>& edges);
    void add_nodes(set<Node*>& nodes);
    void add_edges(set<Edge*>& edges);

    int64_t node_count(void);
    int64_t edge_count(void);
    int64_t total_length_of_nodes(void);
    // Number of edges attached to the start of a node
    int start_degree(Node* node);
    // Number of edges attached to the end of a node
    int end_degree(Node* node);
    // Number of edges attached to the left side of a NodeTraversal
    int left_degree(NodeTraversal node);
    // Number of edges attached to the right side of a NodeTraversal
    int right_degree(NodeTraversal node);
    // Get the edges of the specified node, and add them to the given vector.
    // Guaranteed to add each edge only once per call.
    void edges_of_node(Node* node, vector<Edge*>& edges);
    // Get the edges of the specified set of nodes, and add them to the given set of edge pointers.
    void edges_of_nodes(set<Node*>& nodes, set<Edge*>& edges);

    // use the VG class to generate ids
    Node* create_node(string seq, int64_t id = 0);
    Node* get_node(int64_t id);
    // Get the subgraph of a node and all the edges it is responsible for (i.e.
    // where it has the minimal ID) and add it into the given VG.
    void nonoverlapping_node_context_without_paths(Node* node, VG& g);

    // destroy the node at the given pointer. This pointer must point to a Node owned by the graph.
    void destroy_node(Node* node);
    // destroy the node with the given ID.
    void destroy_node(int64_t id);
    bool has_node(int64_t id);
    bool has_node(Node* node);
    bool has_node(Node& node);
    void for_each_node(function<void(Node*)> lambda);
    void for_each_node_parallel(function<void(Node*)> lambda);
    // Go through all the nodes in the same connected component as the given node. Ignores relative orientation.
    void for_each_connected_node(Node* node, function<void(Node*)> lambda);

    // is the graph empty?
    bool empty(void);

    // remove nodes with no sequence
    // these are created in some cases during the process of graph construction
    void remove_null_nodes(void);
    // remove a node but connect all of its predecessor and successor nodes with new edges
    void remove_node_forwarding_edges(Node* node);
    // remove null nodes but connect predecessors and successors, preserving structure
    void remove_null_nodes_forwarding_edges(void);

    // remove edges for which one of the nodes is not present
    void remove_orphan_edges(void);

    // Keep paths in the given set of path names. Populates kept_names with the names of the paths it actually found to keep.
    // The paths specified may not overlap. Removes all nodes and edges not used by one of the specified paths.
    void keep_paths(set<string>& path_names, set<string>& kept_names);
    void keep_path(string& path_name);

    // path stats
    // starting from offset in the first node, how many edges do we cross?
    // path must be nonempty and longer than the given length. offset is
    // interpreted as relative to the first node in its on-path
    // orientation, and is inclusive.
    int path_edge_count(list<NodeTraversal>& path, int32_t offset, int path_length);
    // At what offset in its last node does the path starting at this offset in its first node end?
    // path must be nonempty and longer than the given length. offset is
    // interpreted as relative to the first node in its on-path
    // orientation, and is inclusive. Returned offset is remaining unused length
    // in the last node touched.
    int path_end_node_offset(list<NodeTraversal>& path, int32_t offset, int path_length);

    // edges
    // If the given edge cannot be created, returns null.
    // If the given edge already exists, returns the existing edge.
    Edge* create_edge(Node* from, Node* to, bool from_start = false, bool to_end = false);
    Edge* create_edge(int64_t from, int64_t to, bool from_start = false, bool to_end = false);
    // Makes a left-to-right edge from the left NodeTraversal to the right one, respecting orientations.
    Edge* create_edge(NodeTraversal left, NodeTraversal right);
    // Makes an edge connecting the given sides of nodes.
    Edge* create_edge(NodeSide side1, NodeSide side2);

    // This can take sides in any order
    Edge* get_edge(const NodeSide& side1, const NodeSide& side2);
    // This can take sides in any order
    Edge* get_edge(const pair<NodeSide, NodeSide>& sides);
    // This gets the edge connecting the given oriented nodes in the given order.
    Edge* get_edge(const NodeTraversal& left, const NodeTraversal& right);
    // destroy the edge at the given pointer. This pointer must point to an edge owned by the graph.
    void destroy_edge(Edge* edge);
    // destroy the edge between the given sides of nodes. These can be in either order.
    void destroy_edge(const NodeSide& side1, const NodeSide& side2);
    // This can take sides in any order
    void destroy_edge(const pair<NodeSide, NodeSide>& sides);
    // remove an edge from the node side indexes, so it doesn't show up when you
    // ask for the edges connected to the side of a node. Makes the edge
    // untraversable until the indexes are rebuilt.
    void unindex_edge_by_node_sides(const NodeSide& side1, const NodeSide& side2);
    void unindex_edge_by_node_sides(Edge* edge);
    // add an edge to the node side indexes. Doesn't touch the index of edges by
    // node pairs or the graph; those must be updated seperately.
    void index_edge_by_node_sides(Edge* edge);
    // Get the edge between the given node sides, which can be in either order.
    bool has_edge(const NodeSide& side1, const NodeSide& side2);
    // This can take sides in any order
    bool has_edge(const pair<NodeSide, NodeSide>& sides);
    bool has_edge(Edge* edge);
    bool has_edge(Edge& edge);
    void for_each_edge(function<void(Edge*)> lambda);
    void for_each_edge_parallel(function<void(Edge*)> lambda);

    // connect node -> nodes
    // Connects from the right side of the first to the left side of the second
    void connect_node_to_nodes(NodeTraversal node, vector<NodeTraversal>& nodes);
    // You can optionally use the start of the first node instead of the end
    void connect_node_to_nodes(Node* node, vector<Node*>& nodes, bool from_start = false);
    // connect nodes -> node
    // Connects from the right side of the first to the left side of the second
    void connect_nodes_to_node(vector<NodeTraversal>& nodes, NodeTraversal node);
    // You can optionally use the end of the second node instead of the start
    void connect_nodes_to_node(vector<Node*>& nodes, Node* node, bool to_end = false);

    // utilities
    // These only work on forward nodes.
    void divide_node(Node* node, int pos, Node*& left, Node*& right);
    void divide_path(map<long, int64_t>& path, long pos, Node*& left, Node*& right);
    //void node_replace_prev(Node* node, Node* before, Node* after);
    //void node_replace_next(Node* node, Node* before, Node* after);

    void to_dot(ostream& out, vector<Alignment> alignments = {}, bool show_paths = false, bool walk_paths = false,
                bool annotate_paths = false, int random_seed = 0);
    void to_gfa(ostream& out);
    bool is_valid(void);

    // topologically orders nodes
    // Makes sure that Nodes appear in the Protobuf Graph object in their topological sort order.
    void sort(void);
    // helper function, not really meant for external use
    void topological_sort(deque<NodeTraversal>& l);
    void swap_nodes(Node* a, Node* b);

    // Use a topological sort to order and orient the nodes, and then flip some
    // nodes around so that they are oriented the way they are in the sort.
    // Populates nodes_flipped with the ids of the nodes that have had their
    // orientations changed. TODO: update the paths that touch nodes that
    // flipped around
    void orient_nodes_forward(set<int64_t>& nodes_flipped);

    // Align to the graph. The graph must be acyclic and contain only end-to-start edges.
    // Will modify the graph by re-ordering the nodes.
    Alignment& align(Alignment& alignment);
    Alignment align(const string& sequence);
    void destroy_alignable_graph(void);

    GSSWAligner* gssw_aligner;

    // returns all node-crossing paths with up to length across node boundaries
    // considers each node in forward orientation to produce the kpaths around it
    void for_each_kpath(int k, int edge_max,
                        function<void(NodeTraversal)> handle_prev_maxed,
                        function<void(NodeTraversal)> handle_next_maxed,
                        function<void(list<NodeTraversal>::iterator, list<NodeTraversal>&)> lambda);
    void for_each_kpath_parallel(int k, int edge_max,
                                 function<void(NodeTraversal)> handle_prev_maxed,
                                 function<void(NodeTraversal)> handle_next_maxed,
                                 function<void(list<NodeTraversal>::iterator, list<NodeTraversal>&)> lambda);
    void for_each_kpath(int k, int edge_max,
                        function<void(NodeTraversal)> handle_prev_maxed,
                        function<void(NodeTraversal)> handle_next_maxed,
                        function<void(size_t,Path&)> lambda);
    void for_each_kpath_parallel(int k, int edge_max,
                                 function<void(NodeTraversal)> handle_prev_maxed,
                                 function<void(NodeTraversal)> handle_next_maxed,
                                 function<void(size_t,Path&)> lambda);
    void for_each_kpath_of_node(Node* node, int k, int edge_max,
                                function<void(NodeTraversal)> handle_prev_maxed,
                                function<void(NodeTraversal)> handle_next_maxed,
                                function<void(list<NodeTraversal>::iterator, list<NodeTraversal>&)> lambda);
    void for_each_kpath_of_node(Node* n, int k, int edge_max,
                                function<void(NodeTraversal)> handle_prev_maxed,
                                function<void(NodeTraversal)> handle_next_maxed,
                                function<void(size_t,Path&)> lambda);

    void kpaths(set<list<NodeTraversal> >& paths, int length, int edge_max,
                function<void(NodeTraversal)> prev_maxed, function<void(NodeTraversal)> next_maxed);
    void kpaths(vector<Path>& paths, int length, int edge_max,
                function<void(NodeTraversal)> prev_maxed, function<void(NodeTraversal)> next_maxed);

    void kpaths_of_node(Node* node, set<list<NodeTraversal> >& paths,
                        int length, int edge_max,
                        function<void(NodeTraversal)> prev_maxed, function<void(NodeTraversal)> next_maxed);
    void kpaths_of_node(Node* node, vector<Path>& paths,
                        int length, int edge_max,
                        function<void(NodeTraversal)> prev_maxed, function<void(NodeTraversal)> next_maxed);
    void kpaths_of_node(int64_t node_id, vector<Path>& paths, int length, int edge_max,
                        function<void(NodeTraversal)> prev_maxed, function<void(NodeTraversal)> next_maxed);
    // Given an oriented start node, a length in bp, a maximum number of edges
    // to cross, and a stack of nodes visited so far, fill in the set of paths
    // with all the paths starting at the oriented start node and going left no
    // longer than the specified length, calling maxed_nodes on nodes which
    // can't be visited due to the edge-crossing limit. Produces paths ending
    // with the specified node.
    // TODO: postfix should not be (potentially) copied on every call.
    void prev_kpaths_from_node(NodeTraversal node, int length, int edge_max, bool edge_bounding,
                               list<NodeTraversal> postfix, set<list<NodeTraversal> >& paths,
                               function<void(NodeTraversal)>& maxed_nodes);
    // Do the same as prec_kpaths_from_node, except going right, producing a path starting with the specified node.
    void next_kpaths_from_node(NodeTraversal node, int length, int edge_max, bool edge_bounding,
                               list<NodeTraversal> prefix, set<list<NodeTraversal> >& paths,
                               function<void(NodeTraversal)>& maxed_nodes);

    void paths_between(Node* from, Node* to, vector<Path>& paths);
    void paths_between(int64_t from, int64_t to, vector<Path>& paths);
    void likelihoods(vector<Alignment>& alignments, vector<Path>& paths, vector<long double>& likelihoods);

    string path_sequence(const Path& path);

    // traversal
    // Get the nodes attached to the left side of the given NodeTraversal, in their proper orientations.
    void nodes_prev(NodeTraversal n, vector<NodeTraversal>& nodes);
    // Get the nodes attached to the right side of the given NodeTraversal, in their proper orientations.
    void nodes_next(NodeTraversal n, vector<NodeTraversal>& nodes);
    // Count the nodes attached to the left side of the given NodeTraversal
    int node_count_prev(NodeTraversal n);
    // Count the nodes attached to the right side of the given NodeTraversal
    int node_count_next(NodeTraversal n);

    // paths
    Path create_path(const list<NodeTraversal>& nodes);
    Path create_path(const vector<NodeTraversal>& nodes);
    string path_string(const list<NodeTraversal>& nodes);
    // Assumes the path covers the entirety of any nodes visited. Handles backward nodes.
    string path_string(Path& path);
    void expand_path(const list<NodeTraversal>& path, vector<NodeTraversal>& expanded);
    // Fill in the node_start map with the first index along the path at which each node appears.
    // Caller is responsible for dealing with orientations.
    void node_starts_in_path(const list<NodeTraversal>& path,
                             map<Node*, int>& node_start);

    // These versions handle paths in which nodes can be traversed multiple
    // times. Unfortunately since we're throwing non-const iterators around, we
    // can't take the input path as const.
    void expand_path(list<NodeTraversal>& path, vector<list<NodeTraversal>::iterator>& expanded);
    // To get the starts out of the map this produces, you need to dereference
    // the iterator and then get the address of the NodeTraversal (stored in the
    // list) that you are talking about.
    void node_starts_in_path(list<NodeTraversal>& path,
                             map<NodeTraversal*, int>& node_start);

    // kmers
    void for_each_kmer_parallel(int kmer_size,
                                int edge_max,
                                function<void(string&, list<NodeTraversal>::iterator, int, list<NodeTraversal>&, VG&)> lambda,
                                int stride = 1,
                                bool allow_dups = false,
                                bool allow_negatives = false);
    void for_each_kmer(int kmer_size,
                       int edge_max,
                       function<void(string&, list<NodeTraversal>::iterator, int, list<NodeTraversal>&, VG&)> lambda,
                       int stride = 1,
                       bool allow_dups = false,
                       bool allow_negatives = false);
    void for_each_kmer_of_node(Node* node,
                               int kmer_size,
                               int edge_max,
                               function<void(string&, list<NodeTraversal>::iterator, int, list<NodeTraversal>&, VG&)> lambda,
                               int stride = 1,
                               bool allow_dups = false,
                               bool allow_negatives = false);

    // for gcsa2. For the given kmer of the given length starting at the given
    // offset into the given Node along the given path, fill in end_node and
    // end_offset with where the end of the kmer falls (counting from the right
    // side of the NodeTraversal), prev_chars with the characters that preceed
    // it, next_chars with the characters that follow it, prev_ and
    // next_positions with the ((node ID, orientation), offset) pairs of the
    // places you can come from/go next (from the right end of the kmer).
    // Refuses to follow more than edge_max edges. Offsets are in the path
    // orientation.
    void kmer_context(string& kmer,
                      int kmer_size,
                      int edge_max,
                      bool forward_only,
                      list<NodeTraversal>& path,
                      list<NodeTraversal>::iterator start_node,
                      int32_t start_offset,
                      list<NodeTraversal>::iterator& end_node,
                      int32_t& end_offset,
                      set<tuple<char, int64_t, bool, int32_t>>& prev_positions,
                      set<tuple<char, int64_t, bool, int32_t>>& next_positions);

    void gcsa_handle_node_in_graph(Node* node, int kmer_size, int edge_max, int stride,
                                   bool forward_only,
                                   Node* head_node, Node* tail_node,
                                   function<void(KmerPosition&)> lambda);

    // GCSA kmers are the kmers in the graph with each node
    // existing in both its forward and reverse-complement orientation. Node IDs
    // in the GCSA graph are 2 * original node ID, +1 if the GCSA node
    // represents the reverse complement, and +0 if it does not. Non-reversing
    // edges link the forward copy of the from node to the forward copy of the
    // to node, and similarly for the reverse complement copies, while reversing
    // edges link the forward copy of the from node to the *reverse complement*
    // copy of the to node, and visa versa. This allows us to index both the
    // forward and reverse strands of every node, and to deal with GCSA's lack
    // of support for reversing edges, with the same trick. Note that
    // start_tail_id, if zero, will be replaced with the ID actually used for the
    // start/end node before lambda is ever called.
    void for_each_gcsa_kmer_position_parallel(int kmer_size, int edge_max, int stride,
                                              bool forward_only,
                                              int64_t& head_id, int64_t& tail_id,
                                              function<void(KmerPosition&)> lambda);

    void get_gcsa_kmers(int kmer_size, int edge_max, int stride,
                        bool forward_only,
                        vector<gcsa::KMer>& kmers_out,
                        int64_t& head_id, int64_t& tail_id);

    gcsa::GCSA* build_gcsa_index(int kmer_size, bool forward_only,
                                 size_t doubling_steps = 2,
                                 size_t size_limit = 200);

    // for pruning graph prior to indexing with gcsa2
    // takes all nodes that would introduce paths of > edge_max edge crossings, removes them, and links their neighbors to
    // head_node or tail_node depending on which direction the path extension was stopped
    void prune_complex(int path_length, int edge_max, Node* head_node, Node* tail_node);

private:
    // Call the given function on each kmer. If parallel is specified, goes
    // through nodes one per thread. If node is not null, looks only at kmers of
    // that specific node.
    void _for_each_kmer(int kmer_size,
                        int edge_max,
                        function<void(string&, list<NodeTraversal>::iterator, int, list<NodeTraversal>&, VG&)> lambda,
                        bool parallel,
                        int stride,
                        bool allow_dups,
                        bool allow_negatives,
                        Node* node = nullptr);

public:

    // reads
    // note that even if either_strand is false, having backward nodes in the
    // graph will result in some reads from the global reverse strand.
    string random_read(int length, mt19937& rng, int64_t min_id, int64_t max_id, bool either_strand);

    // subgraphs
    void disjoint_subgraphs(list<VG>& subgraphs);
    // Get the head nodes (nodes with edges only to their right sides). These are required to be oriented forward.
    void head_nodes(vector<Node*>& nodes);
    vector<Node*> head_nodes(void);
    // Get the tail nodes (nodes with edges only to their left sides). These are required to be oriented forward.
    vector<Node*> tail_nodes(void);
    void tail_nodes(vector<Node*>& nodes);
    void collect_subgraph(Node* node, set<Node*>& subgraph);

    // join head nodes of graph to common null node, creating a new single head.
    Node* join_heads(void);
    // or heads and tails to common new single head or tail (optionally from the start/to the end).
    void join_heads(Node* node, bool from_start = false);
    void join_tails(Node* node, bool to_end = false);

    // add singular head and tail null nodes to graph
    void wrap_with_null_nodes(void);

    // Add a single combination start/end node, where all existing heads in the
    // graph are connected to it, and all existing tails in the graph are
    // connected to its end. Any connected components in the graph which do not
    // have a head or tail are connected to the node at an arbitrary point. If
    // head_tail_node is null, a new node will be created. Otherwise, the passed
    // node will be used. The graph ends up having the new node as its only
    // head, and having no tails. If id is 0, and head_tail_node is null, the
    // next free ID will be chosen for the node. Note that this visits every
    // node, to make sure it is attached to all connected components.
    void add_start_end_markers(int length,
                               char start_char, char end_char,
                               Node*& start_node, Node*& end_node,
                               int64_t start_id = 0, int64_t end_id = 0);

    bool show_progress;
    string progress_message;
    long progress_count;
    long last_progress;
    ProgressBar* progress;
    void create_progress(const string& message, long count);
    void create_progress(long count);
    void update_progress(long i);
    void destroy_progress(void);

    // for managing parallel construction
    struct Plan {
        VG* graph;
        map<long, set<vcflib::VariantAllele> >* alleles;
        string seq;
        string name;
        Plan(VG* g,
             map<long, set<vcflib::VariantAllele> >* a,
             string s,
             string n)
            : graph(g)
            , alleles(a)
            , seq(s)
            , name(n) { };
        ~Plan(void) { delete alleles; }
    };

private:

    void init(void); // setup, ensures that gssw == NULL on startup
    // placeholders for empty
    vector<int64_t> empty_ids;
    vector<pair<int64_t, bool>> empty_edge_ends;
};

} // end namespace vg

#endif


text:
package com.digero.maestro.abc;

import java.util.EventObject;

public class AbcPartEvent extends EventObject
{
	public enum AbcPartProperty
	{
		TITLE(false), //
		PART_NUMBER(false), //
		ENABLED, //
		INSTRUMENT, //
		BASE_TRANSPOSE, //
		TRACK_ENABLED, //
		TRACK_TRANSPOSE, //
		DRUM_ENABLED, //
		DRUM_MAPPING, //
		VOLUME_ADJUST; //

		private final boolean renderRelated;

		private AbcPartProperty()
		{
			this.renderRelated = true;
		}

		private AbcPartProperty(boolean renderRelated)
		{
			this.renderRelated = renderRelated;
		}

		public boolean isNoteGraphRelated()
		{
			return renderRelated;
		}

		public boolean isAbcPreviewRelated()
		{
			return renderRelated;
		}
	}

	public static final int NO_TRACK_NUMBER = -1;

	private final boolean abcPreviewRelated;
	private final AbcPartProperty property;
	private final int trackNumber;

	public AbcPartEvent(AbcPart source, AbcPartProperty property, boolean abcPreviewRelated, int trackNumber)
	{
		super(source);
		this.property = property;
		this.abcPreviewRelated = abcPreviewRelated;
		this.trackNumber = trackNumber;
	}

	public AbcPartProperty getProperty()
	{
		return property;
	}

	public boolean hasTrackNumber()
	{
		return trackNumber != NO_TRACK_NUMBER;
	}

	public int getTrackNumber()
	{
		return trackNumber;
	}

	public boolean matchesTrack(int track)
	{
		return !hasTrackNumber() || trackNumber == track;
	}

	public boolean isNoteGraphRelated()
	{
		return property.isNoteGraphRelated();
	}

	public boolean isAbcPreviewRelated()
	{
		return abcPreviewRelated;
	}

	@Override public AbcPart getSource()
	{
		return (AbcPart) super.getSource();
	}
}


text:
- [nativescript-ar](https://github.com/EddyVerbruggen/nativescript-ar)
- [nativescript-drop-down](https://github.com/PeterStaev/NativeScript-Drop-Down)
- [nativescript-flashlight](https://github.com/tjvantoll/nativescript-flashlight)
- [nativescript-insomnia](https://github.com/EddyVerbruggen/nativescript-insomnia)

<img src="../../screenshots/themes/ar.jpg" width="375px"/>


text:
FROM phusion/baseimage:0.9.18
MAINTAINER Christophe Furmaniak <christophe.furmaniak@gmail.com>

RUN \
  echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \
  add-apt-repository -y ppa:webupd8team/java && \
  apt-get update && \
  apt-get install -y oracle-java8-installer && \
  rm -rf /var/lib/apt/lists/* && \
  rm -rf /var/cache/oracle-jdk8-installer

RUN rm -rf /etc/service/sshd /etc/my_init.d/00_regen_ssh_host_keys.sh && \
    add-apt-repository -y ppa:cwchien/gradle && \
	apt-get update && apt-get install -y -q unzip git gradle && \
    mkdir /etc/service/go-agent

ADD go-agent-start.sh /etc/service/go-agent/run

ADD https://download.go.cd/binaries/16.2.1-3027/deb/go-agent-16.2.1-3027.deb /tmp/go-agent.deb

WORKDIR /tmp
RUN dpkg -i /tmp/go-agent.deb && \
    sed -i 's/DAEMON=Y/DAEMON=N/' /etc/default/go-agent && \
    apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
	chmod +x /etc/service/go-agent/run

CMD ["/sbin/my_init"]


text:
#ifndef __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__
#define __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__

#include <iostream>
#include <string>

#include "mem/protocol/AccessPermission.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Consumer.hh"
#include "mem/ruby/common/DataBlock.hh"
#include "mem/ruby/network/Network.hh"
#include "mem/ruby/recorder/CacheRecorder.hh"
#include "params/RubyController.hh"
#include "sim/sim_object.hh"

class MessageBuffer;
class Network;

class AbstractController : public SimObject, public Consumer
{
  public:
    typedef RubyControllerParams Params;
    AbstractController(const Params *p);
    const Params *params() const { return (const Params *)_params; }
    virtual MessageBuffer* getMandatoryQueue() const = 0;
    virtual const int & getVersion() const = 0;
    virtual const std::string toString() const = 0;  // returns text version of
                                                     // controller type
    virtual const std::string getName() const = 0;   // return instance name
    virtual void blockOnQueue(Address, MessageBuffer*) = 0;
    virtual void unblock(Address) = 0;
    virtual void initNetworkPtr(Network* net_ptr) = 0;
    virtual AccessPermission getAccessPermission(const Address& addr) = 0;
    virtual DataBlock& getDataBlock(const Address& addr) = 0;

    virtual void print(std::ostream & out) const = 0;
    virtual void printStats(std::ostream & out) const = 0;
    virtual void printConfig(std::ostream & out) const = 0;
    virtual void wakeup() = 0;
    //  virtual void dumpStats(std::ostream & out) = 0;
    virtual void clearStats() = 0;
    virtual void recordCacheTrace(int cntrl, CacheRecorder* tr) = 0;
    virtual Sequencer* getSequencer() const = 0;
};

#endif // __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__


text:
class Following < ActiveRecord::Base
  has_many :followers
  has_many :leaders
end


text:
from json import dumps as j_dump

from yaml import dump as y_dump

from ffflash.lib.struct import dump_struct

def test_dump_struct_wrong_input_data():
    for fj in [range, set, y_dump, j_dump]:
        with dump_struct(fj, as_yaml=False) as t:
            assert t is None

def test_dump_struct_json():
    for tj in ['', 'a', {}, {'a': 'b'}]:
        with dump_struct(tj, as_yaml=False) as t:
            assert t == j_dump(
                tj, indent=2, sort_keys=True
            )

def test_dump_struct_yaml():
    for ty in [None, 'a', {'a': None}, {'a': 'b'}, {'a': ['b', 'c']}, range]:
        with dump_struct(ty, as_yaml=True) as t:
            assert t == y_dump(
                ty, indent=4, default_flow_style=False
            )


text:
import { TestBed } from '@angular/core/testing';

import { XRequestWithInterceptor } from './x-request-with.interceptor';

describe('XhrInterceptor', () => {
  beforeEach(() => TestBed.configureTestingModule({
    providers: [
      XRequestWithInterceptor
      ]
  }));

  it('should be created', () => {
    const interceptor: XRequestWithInterceptor = TestBed.inject(XRequestWithInterceptor);
    expect(interceptor).toBeTruthy();
  });
});